context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** 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.Permissions;
using System.Security;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Exception))]
[Serializable]
[ComVisible(true)]
public class Exception : ISerializable, _Exception
{
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;
#if FEATURE_SERIALIZATION
_safeSerializationManager = new SafeSerializationManager();
#endif // FEATURE_SERIALIZATION
}
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;
}
[System.Security.SecuritySafeCritical] // auto-generated
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info==null)
throw new ArgumentNullException("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 FEATURE_SERIALIZATION
_safeSerializationManager = info.GetValueNoThrow("SafeSerializationManager", typeof(SafeSerializationManager)) as SafeSerializationManager;
#endif // FEATURE_SERIALIZATION
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 {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (_data == null)
if (IsImmutableAgileException(this))
_data = new EmptyReadOnlyDictionaryInternal();
else
_data = new ListDictionaryInternal();
return _data;
}
}
[System.Security.SecurityCritical] // auto-generated
[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; }
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
[System.Security.SecuritySafeCritical] // auto-generated
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 {
[System.Security.SecuritySafeCritical] // auto-generated
get {
return GetTargetSiteInternal();
}
}
// this function is provided as a private helper to avoid the security demand
[System.Security.SecurityCritical] // auto-generated
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
{
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
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.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private string GetStackTrace(bool needFileInfo)
{
string stackTraceString = _stackTraceString;
string remoteStackTraceString = _remoteStackTraceString;
#if !FEATURE_CORECLR
if (!needFileInfo)
{
// Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString.
// This is used only when generating stack trace for Watson where the strings must be PII-free.
stackTraceString = StripFileInfo(stackTraceString, false);
remoteStackTraceString = StripFileInfo(remoteStackTraceString, true);
}
#endif // !FEATURE_CORECLR
// 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 {
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
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;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
set { _source = value; }
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public override String ToString()
{
return ToString(true, true);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
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;
}
[System.Security.SecurityCritical] // auto-generated
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 {
Contract.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();
}
[System.Security.SecurityCritical] // auto-generated
private MethodBase GetExceptionMethodFromString() {
Contract.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;
}
#if FEATURE_SERIALIZATION
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { _safeSerializationManager.SerializeObjectState += value; }
remove { _safeSerializationManager.SerializeObjectState -= value; }
}
#else
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
add { throw new PlatformNotSupportedException();}
remove { throw new PlatformNotSupportedException();}
}
#endif // FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("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[]));
#if FEATURE_SERIALIZATION
if (_safeSerializationManager != null && _safeSerializationManager.IsActive)
{
info.AddValue("SafeSerializationManager", _safeSerializationManager, typeof(SafeSerializationManager));
// User classes derived from Exception must have a valid _safeSerializationManager.
// Exceptions defined in mscorlib don't use this field might not have it initalized (since they are
// often created in the VM with AllocateObject instead if the managed construtor)
// If you are adding code to use a SafeSerializationManager from an mscorlib exception, update
// this assert to ensure that it fails when that exception's _safeSerializationManager is NULL
Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
"User defined exceptions must have a valid _safeSerializationManager");
// Handle serializing any transparent or partial trust subclass data
_safeSerializationManager.CompleteSerialization(this, info, context);
}
#endif // FEATURE_SERIALIZATION
}
// This is used by remoting to preserve the server side stack trace
// by appending it to the message ... before the exception is rethrown
// at the client call site.
internal Exception PrepForRemoting()
{
String tmp = null;
if (_remoteStackIndex == 0)
{
tmp = Environment.NewLine+ "Server stack trace: " + Environment.NewLine
+ StackTrace
+ Environment.NewLine + Environment.NewLine
+ "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
}
else
{
tmp = StackTrace
+ Environment.NewLine + Environment.NewLine
+ "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine;
}
_remoteStackTraceString = tmp;
_remoteStackIndex++;
return this;
}
// 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;
#if FEATURE_SERIALIZATION
if (_safeSerializationManager == null)
{
_safeSerializationManager = new SafeSerializationManager();
}
else
{
_safeSerializationManager.CompleteDeserialization(this);
}
#endif // FEATURE_SERIALIZATION
}
// This is used by the runtime when re-throwing a managed exception. It will
// copy the stack trace to _remoteStackTraceString.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
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
#if FEATURE_CORESYSTEM
// 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_CORESYSTEM
#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;
}
#if FEATURE_EXCEPTIONDISPATCHINFO
// 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;
}
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PrepareForForeignExceptionRaise();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyStackTrace(object currentStackTrace);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyDynamicMethods(object currentDynamicMethods);
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace);
#endif // !FEATURE_CORECLR
[SecuritySafeCritical]
internal object DeepCopyStackTrace(object currentStackTrace)
{
if (currentStackTrace != null)
{
return CopyStackTrace(currentStackTrace);
}
else
{
return null;
}
}
[SecuritySafeCritical]
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
{
return CopyDynamicMethods(currentDynamicMethods);
}
else
{
return null;
}
}
[SecuritySafeCritical]
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".
[SecuritySafeCritical]
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();
}
}
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
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
#if FEATURE_SERIALIZATION
[OptionalField(VersionAdded = 4)]
private SafeSerializationManager _safeSerializationManager;
#endif // FEATURE_SERIALIZATION
// 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
[System.Security.SecurityCritical] // auto-generated
internal virtual String InternalToString()
{
try
{
#pragma warning disable 618
SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
#pragma warning restore 618
sp.Assert();
}
catch
{
//under normal conditions there should be no exceptions
//however if something wrong happens we still can call the usual ToString
}
// 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
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return nIsTransient(_HResult);
}
}
[System.Security.SecurityCritical] // auto-generated
[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
[System.Security.SecuritySafeCritical] // auto-generated
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg));
return retMesg;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
}
#if FEATURE_CORECLR
//--------------------------------------------------------------------------
// 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.
//--------------------------------------------------------------------------
#if FEATURE_SERIALIZATION
[Serializable]
#endif
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.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal override String InternalToString()
{
return Message;
}
}
#endif
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
#pragma warning disable 0618 // Ignore GvrAudio* deprecation
/// GVR soundfield component that allows playback of first-order ambisonic recordings. The audio
/// sample should be in Ambix (ACN-SN3D) format.
#if UNITY_2017_1_OR_NEWER
[System.Obsolete("Please upgrade to Resonance Audio (https://developers.google.com/resonance-audio/migrate).")]
#endif // UNITY_2017_1_OR_NEWER
[AddComponentMenu("GoogleVR/Audio/GvrAudioSoundfield")]
public class GvrAudioSoundfield : MonoBehaviour {
/// Denotes whether the room effects should be bypassed.
public bool bypassRoomEffects = true;
/// Input gain in decibels.
public float gainDb = 0.0f;
/// Play source on awake.
public bool playOnAwake = true;
/// The default AudioClip to play.
public AudioClip clip0102 {
get { return soundfieldClip0102; }
set {
soundfieldClip0102 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[0].clip = soundfieldClip0102;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0102 = null;
public AudioClip clip0304 {
get { return soundfieldClip0304; }
set {
soundfieldClip0304 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[1].clip = soundfieldClip0304;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0304 = null;
/// Is the clip playing right now (Read Only)?
public bool isPlaying {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].isPlaying;
}
return false;
}
}
/// Is the audio clip looping?
public bool loop {
get { return soundfieldLoop; }
set {
soundfieldLoop = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].loop = soundfieldLoop;
}
}
}
}
[SerializeField]
private bool soundfieldLoop = false;
/// Un- / Mutes the soundfield. Mute sets the volume=0, Un-Mute restore the original volume.
public bool mute {
get { return soundfieldMute; }
set {
soundfieldMute = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].mute = soundfieldMute;
}
}
}
}
[SerializeField]
private bool soundfieldMute = false;
/// The pitch of the audio source.
public float pitch {
get { return soundfieldPitch; }
set {
soundfieldPitch = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].pitch = soundfieldPitch;
}
}
}
}
[SerializeField]
[Range(-3.0f, 3.0f)]
private float soundfieldPitch = 1.0f;
/// Sets the priority of the soundfield.
public int priority {
get { return soundfieldPriority; }
set {
soundfieldPriority = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].priority = soundfieldPriority;
}
}
}
}
[SerializeField]
[Range(0, 256)]
private int soundfieldPriority = 32;
/// Sets how much this soundfield is affected by 3D spatialization calculations
/// (attenuation, doppler).
public float spatialBlend {
get { return soundfieldSpatialBlend; }
set {
soundfieldSpatialBlend = value;
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].spatialBlend = soundfieldSpatialBlend;
}
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float soundfieldSpatialBlend = 0.0f;
/// Sets the Doppler scale for this soundfield.
public float dopplerLevel {
get { return soundfieldDopplerLevel; }
set {
soundfieldDopplerLevel = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].dopplerLevel = soundfieldDopplerLevel;
}
}
}
}
[SerializeField]
[Range(0.0f, 5.0f)]
private float soundfieldDopplerLevel = 0.0f;
/// Playback position in seconds.
public float time {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].time;
}
return 0.0f;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].time = value;
}
}
}
}
/// Playback position in PCM samples.
public int timeSamples {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].timeSamples;
}
return 0;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].timeSamples = value;
}
}
}
}
/// The volume of the audio source (0.0 to 1.0).
public float volume {
get { return soundfieldVolume; }
set {
soundfieldVolume = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].volume = soundfieldVolume;
}
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float soundfieldVolume = 1.0f;
/// Volume rolloff model with respect to the distance.
public AudioRolloffMode rolloffMode {
get { return soundfieldRolloffMode; }
set {
soundfieldRolloffMode = value;
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].rolloffMode = soundfieldRolloffMode;
if (rolloffMode == AudioRolloffMode.Custom) {
// Custom rolloff is not supported, set the curve for no distance attenuation.
audioSources[channelSet].SetCustomCurve(
AudioSourceCurveType.CustomRolloff,
AnimationCurve.Linear(soundfieldMinDistance, 1.0f, soundfieldMaxDistance, 1.0f));
}
}
}
}
}
[SerializeField]
private AudioRolloffMode soundfieldRolloffMode = AudioRolloffMode.Logarithmic;
/// MaxDistance is the distance a sound stops attenuating at.
public float maxDistance {
get { return soundfieldMaxDistance; }
set {
soundfieldMaxDistance = Mathf.Clamp(value, soundfieldMinDistance + GvrAudio.distanceEpsilon,
GvrAudio.maxDistanceLimit);
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].maxDistance = soundfieldMaxDistance;
}
}
}
}
[SerializeField]
private float soundfieldMaxDistance = 500.0f;
/// Within the Min distance the GvrAudioSource will cease to grow louder in volume.
public float minDistance {
get { return soundfieldMinDistance; }
set {
soundfieldMinDistance = Mathf.Clamp(value, 0.0f, GvrAudio.minDistanceLimit);
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].minDistance = soundfieldMinDistance;
}
}
}
}
[SerializeField]
private float soundfieldMinDistance = 1.0f;
// Unique source id.
private int id = -1;
// Unity audio sources per each soundfield channel set.
private AudioSource[] audioSources = null;
// Denotes whether the source is currently paused or not.
private bool isPaused = false;
void Awake () {
#if UNITY_EDITOR && UNITY_2017_1_OR_NEWER
Debug.LogWarningFormat(gameObject,
"Game object '{0}' uses deprecated {1} component.\nPlease upgrade to Resonance Audio ({2}).",
name, GetType().Name, "https://developers.google.com/resonance-audio/migrate");
#endif // UNITY_EDITOR && UNITY_2017_1_OR_NEWER
// Route the source output to |GvrAudioMixer|.
AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer);
if(mixer == null) {
Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK" +
"Unity package is imported properly.");
return;
}
audioSources = new AudioSource[GvrAudio.numFoaChannels / 2];
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
GameObject channelSetObject = new GameObject("Channel Set " + channelSet);
channelSetObject.transform.parent = gameObject.transform;
channelSetObject.transform.localPosition = Vector3.zero;
channelSetObject.transform.localRotation = Quaternion.identity;
channelSetObject.hideFlags = HideFlags.HideAndDontSave;
audioSources[channelSet] = channelSetObject.AddComponent<AudioSource>();
audioSources[channelSet].enabled = false;
audioSources[channelSet].playOnAwake = false;
audioSources[channelSet].bypassReverbZones = true;
#if UNITY_5_5_OR_NEWER
audioSources[channelSet].spatializePostEffects = true;
#endif // UNITY_5_5_OR_NEWER
audioSources[channelSet].outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0];
}
OnValidate();
}
void OnEnable () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = true;
}
if (playOnAwake && !isPlaying && InitializeSoundfield()) {
Play();
}
}
void Start () {
if (playOnAwake && !isPlaying) {
Play();
}
}
void OnDisable () {
Stop();
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = false;
}
}
void OnDestroy () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
Destroy(audioSources[channelSet].gameObject);
}
}
void OnApplicationPause (bool pauseStatus) {
if (pauseStatus) {
Pause();
} else {
UnPause();
}
}
void Update () {
// Update soundfield.
if (!isPlaying && !isPaused) {
Stop();
} else {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
audioSources[channelSet].SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance,
soundfieldMinDistance);
}
GvrAudio.UpdateAudioSoundfield(id, this);
}
}
/// Pauses playing the clip.
public void Pause () {
if (audioSources != null) {
isPaused = true;
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Pause();
}
}
}
/// Plays the clip.
public void Play () {
double dspTime = AudioSettings.dspTime;
PlayScheduled(dspTime);
}
/// Plays the clip with a delay specified in seconds.
public void PlayDelayed (float delay) {
double delayedDspTime = AudioSettings.dspTime + (double)delay;
PlayScheduled(delayedDspTime);
}
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads
/// from.
public void PlayScheduled (double time) {
if (audioSources != null && InitializeSoundfield()) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].PlayScheduled(time);
}
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio soundfield not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Changes the time at which a sound that has already been scheduled to play will end.
public void SetScheduledEndTime(double time) {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].SetScheduledEndTime(time);
}
}
}
/// Changes the time at which a sound that has already been scheduled to play will start.
public void SetScheduledStartTime(double time) {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].SetScheduledStartTime(time);
}
}
}
/// Stops playing the clip.
public void Stop () {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Stop();
}
ShutdownSoundfield();
isPaused = false;
}
}
/// Unpauses the paused playback.
public void UnPause () {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].UnPause();
}
isPaused = false;
}
}
// Initializes the source.
private bool InitializeSoundfield () {
if (id < 0) {
id = GvrAudio.CreateAudioSoundfield();
if (id >= 0) {
GvrAudio.UpdateAudioSoundfield(id, this);
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
InitializeChannelSet(audioSources[channelSet], channelSet);
}
}
}
return id >= 0;
}
// Shuts down the source.
private void ShutdownSoundfield () {
if (id >= 0) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
ShutdownChannelSet(audioSources[channelSet], channelSet);
}
GvrAudio.DestroyAudioSource(id);
id = -1;
}
}
// Initializes given channel set of the soundfield.
private void InitializeChannelSet(AudioSource source, int channelSet) {
source.spatialize = true;
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Type,
(float) GvrAudio.SpatializerType.Soundfield);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.NumChannels,
(float) GvrAudio.numFoaChannels);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ChannelSet, (float) channelSet);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance, soundfieldMinDistance);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 0.0f);
// Soundfield id must be set after all the spatializer parameters, to ensure that the soundfield
// is properly initialized before processing.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, (float) id);
}
// Shuts down given channel set of the soundfield.
private void ShutdownChannelSet(AudioSource source, int channelSet) {
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, -1.0f);
// Ensure that the output is zeroed after shutdown.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 1.0f);
source.spatialize = false;
}
void OnDidApplyAnimationProperties () {
OnValidate();
}
void OnValidate () {
clip0102 = soundfieldClip0102;
clip0304 = soundfieldClip0304;
loop = soundfieldLoop;
mute = soundfieldMute;
pitch = soundfieldPitch;
priority = soundfieldPriority;
spatialBlend = soundfieldSpatialBlend;
volume = soundfieldVolume;
dopplerLevel = soundfieldDopplerLevel;
minDistance = soundfieldMinDistance;
maxDistance = soundfieldMaxDistance;
rolloffMode = soundfieldRolloffMode;
}
}
#pragma warning restore 0618 // Restore warnings
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata.Ecma335
{
internal class NamespaceCache
{
private readonly MetadataReader _metadataReader;
private readonly object _namespaceTableAndListLock = new object();
private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable;
private NamespaceData _rootNamespace;
private ImmutableArray<NamespaceDefinitionHandle> _namespaceList;
internal NamespaceCache(MetadataReader reader)
{
Debug.Assert(reader != null);
_metadataReader = reader;
}
/// <summary>
/// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method
/// on this will probably have a very high amount of overhead.
/// </summary>
internal bool CacheIsRealized
{
get { return _namespaceTable != null; }
}
internal string GetFullName(NamespaceDefinitionHandle handle)
{
Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case.
NamespaceData data = GetNamespaceData(handle);
return data.FullName;
}
internal NamespaceData GetRootNamespace()
{
EnsureNamespaceTableIsPopulated();
Debug.Assert(_rootNamespace != null);
return _rootNamespace;
}
internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle)
{
EnsureNamespaceTableIsPopulated();
NamespaceData result;
if (!_namespaceTable.TryGetValue(handle, out result))
{
ThrowInvalidHandle();
}
return result;
}
// TODO: move throw helpers to common place.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void ThrowInvalidHandle()
{
throw new BadImageFormatException(MetadataResources.InvalidHandle);
}
/// <summary>
/// This will return a StringHandle for the simple name of a namespace name at the given segment index.
/// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number
/// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace
/// name between dots.
///
/// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle':
///
/// reader.GetString(GetSimpleName(handle)) == "Test"
/// reader.GetString(GetSimpleName(handle, 0)) == "System"
/// reader.GetString(GetSimpleName(handle, 1)) == "Collections"
/// reader.GetString(GetSimpleName(handle, 2)) == "Generic"
/// reader.GetString(GetSimpleName(handle, 3)) == "Test"
/// reader.GetString(GetSimpleName(handle, 1000)) == "Test"
/// </summary>
private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue)
{
StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName();
Debug.Assert(!handleContainingSegment.IsVirtual);
int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1;
int currentSegment = 0;
while (currentSegment < segmentIndex)
{
int currentIndex = _metadataReader.StringStream.IndexOfRaw(lastFoundIndex + 1, '.');
if (currentIndex == -1)
{
break;
}
lastFoundIndex = currentIndex;
++currentSegment;
}
Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0);
// + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way,
// we want the next char.
int resultIndex = lastFoundIndex + 1;
return StringHandle.FromOffset(resultIndex).WithDotTermination();
}
/// <summary>
/// Two distinct namespace handles represent the same namespace if their full names are the same. This
/// method merges builders corresponding to such namespace handles.
/// </summary>
private void PopulateNamespaceTable()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceTable != null)
{
return;
}
var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>();
// Make sure to add entry for root namespace. The root namespace is special in that even
// though it might not have types of its own it always has an equivalent representation
// as a nil handle and we don't want to handle it below as dot-terminated synthetic namespace.
// We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so
// that we never hand back a handle to the user that doesn't have a typeid as that prevents
// round-trip conversion to Handle and back. (We may discover other handle aliases for the
// root namespace (any nil/empty string will do), but we need this one to always be there.
NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromFullNameOffset(0);
namespaceBuilderTable.Add(
rootNamespace,
new NamespaceDataBuilder(
rootNamespace,
rootNamespace.GetFullName(),
String.Empty));
PopulateTableWithTypeDefinitions(namespaceBuilderTable);
PopulateTableWithExportedTypes(namespaceBuilderTable);
Dictionary<string, NamespaceDataBuilder> stringTable;
MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable);
List<NamespaceDataBuilder> syntheticNamespaces;
ResolveParentChildRelationships(stringTable, out syntheticNamespaces);
var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>();
foreach (var group in namespaceBuilderTable)
{
// Freeze() caches the result, so any many-to-one relationships
// between keys and values will be preserved and efficiently handled.
namespaceTable.Add(group.Key, group.Value.Freeze());
}
if (syntheticNamespaces != null)
{
foreach (var syntheticNamespace in syntheticNamespaces)
{
namespaceTable.Add(syntheticNamespace.Handle, syntheticNamespace.Freeze());
}
}
_namespaceTable = namespaceTable;
_rootNamespace = namespaceTable[rootNamespace];
}
}
/// <summary>
/// This will take 'table' and merge all of the NamespaceData instances that point to the same
/// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it
/// back to the caller should the caller want to use it.
/// </summary>
private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable)
{
var namespaces = new Dictionary<string, NamespaceDataBuilder>();
List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null;
foreach (var group in table)
{
NamespaceDataBuilder data = group.Value;
NamespaceDataBuilder existingRecord;
if (namespaces.TryGetValue(data.FullName, out existingRecord))
{
// Children should not exist until the next step.
Debug.Assert(data.Namespaces.Count == 0);
data.MergeInto(existingRecord);
if (remaps == null)
{
remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
}
remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord));
}
else
{
namespaces.Add(data.FullName, data);
}
}
// Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it.
if (remaps != null)
{
foreach (var tuple in remaps)
{
table[tuple.Key] = tuple.Value;
}
}
stringTable = namespaces;
}
/// <summary>
/// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle,
/// as well as the name provided.
/// </summary>
private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild)
{
Debug.Assert(realChild.HasFullName);
int numberOfSegments = 0;
foreach (char c in fullName)
{
if (c == '.')
{
numberOfSegments++;
}
}
StringHandle simpleName = GetSimpleName(realChild, numberOfSegments);
var namespaceHandle = NamespaceDefinitionHandle.FromSimpleNameOffset(simpleName.GetHeapOffset());
return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
}
/// <summary>
/// Quick convenience method that handles linking together child + parent
/// </summary>
private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent)
{
Debug.Assert(child != null && parent != null);
Debug.Assert(!child.Handle.IsNil);
child.Parent = parent.Handle;
parent.Namespaces.Add(child.Handle);
}
/// <summary>
/// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a
/// synthetic one. This will automatically link any synthetic namespaces it creates up to its parents.
/// </summary>
private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces,
NamespaceDataBuilder realChild,
ref List<NamespaceDataBuilder> syntheticNamespaces)
{
Debug.Assert(realChild.Handle.HasFullName);
string childName = realChild.FullName;
var child = realChild;
// The condition for this loop is very complex -- essentially, we keep going
// until we:
// A. Encounter the root namespace as 'child'
// B. Find a preexisting namespace as 'parent'
while (true)
{
int lastIndex = childName.LastIndexOf('.');
string parentName;
if (lastIndex == -1)
{
if (childName.Length == 0)
{
return;
}
else
{
parentName = String.Empty;
}
}
else
{
parentName = childName.Substring(0, lastIndex);
}
NamespaceDataBuilder parentData;
if (existingNamespaces.TryGetValue(parentName, out parentData))
{
LinkChildDataToParentData(child, parentData);
return;
}
if (syntheticNamespaces != null)
{
foreach (var data in syntheticNamespaces)
{
if (data.FullName == parentName)
{
LinkChildDataToParentData(child, data);
return;
}
}
}
else
{
syntheticNamespaces = new List<NamespaceDataBuilder>();
}
var syntheticParent = SynthesizeNamespaceData(parentName, realChild.Handle);
LinkChildDataToParentData(child, syntheticParent);
syntheticNamespaces.Add(syntheticParent);
childName = syntheticParent.FullName;
child = syntheticParent;
}
}
/// <summary>
/// This will link all parents/children in the given namespaces dictionary up to each other.
///
/// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders
/// of their own, but do have child namespaces. These are returned via the syntheticNamespaces out
/// parameter.
/// </summary>
private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> syntheticNamespaces)
{
syntheticNamespaces = null;
foreach (var namespaceData in namespaces.Values)
{
LinkChildToParentNamespace(namespaces, namespaceData, ref syntheticNamespaces);
}
}
/// <summary>
/// Loops through all type definitions in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var typeHandle in _metadataReader.TypeDefinitions)
{
TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle);
if (type.Attributes.IsNested())
{
continue;
}
NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeHandle);
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.TypeDefinitions.Add(typeHandle);
}
else
{
StringHandle name = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName);
newData.TypeDefinitions.Add(typeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Loops through all type forwarders in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var exportedTypeHandle in _metadataReader.ExportedTypes)
{
ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle);
if (exportedType.Implementation.Kind == HandleKind.ExportedType)
{
continue; // skip nested exported types.
}
NamespaceDefinitionHandle namespaceHandle = exportedType.NamespaceDefinition;
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.ExportedTypes.Add(exportedTypeHandle);
}
else
{
Debug.Assert(namespaceHandle.HasFullName);
StringHandle simpleName = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
newData.ExportedTypes.Add(exportedTypeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Populates namespaceList with distinct namespaces. No ordering is guaranteed.
/// </summary>
private void PopulateNamespaceList()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceList != null)
{
return;
}
Debug.Assert(_namespaceTable != null);
var namespaceNameSet = new HashSet<string>();
var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
foreach (var group in _namespaceTable)
{
var data = group.Value;
if (namespaceNameSet.Add(data.FullName))
{
namespaceListBuilder.Add(group.Key);
}
}
_namespaceList = namespaceListBuilder.ToImmutable();
}
}
/// <summary>
/// If the namespace table doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceTableIsPopulated()
{
// PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily.
if (_namespaceTable == null)
{
PopulateNamespaceTable();
}
Debug.Assert(_namespaceTable != null);
}
/// <summary>
/// If the namespace list doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceListIsPopulated()
{
if (_namespaceList == null)
{
PopulateNamespaceList();
}
Debug.Assert(_namespaceList != null);
}
/// <summary>
/// An intermediate class used to build NamespaceData instances. This was created because we wanted to
/// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the
/// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace
/// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles
/// and NamespaceData. So, the pointer semantics must be preserved.
///
/// This class assumes that the builders will not be modified in any way after the first call to
/// Freeze().
/// </summary>
private class NamespaceDataBuilder
{
public readonly NamespaceDefinitionHandle Handle;
public readonly StringHandle Name;
public readonly string FullName;
public NamespaceDefinitionHandle Parent;
public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces;
public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions;
public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes;
private NamespaceData _frozen;
public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName)
{
Handle = handle;
Name = name;
FullName = fullName;
Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>();
}
/// <summary>
/// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling
/// this method, it is an error to use any methods or fields except Freeze() on the target
/// NamespaceDataBuilder.
/// </summary>
public NamespaceData Freeze()
{
// It is not an error to call this function multiple times. We cache the result
// because it's immutable.
if (_frozen == null)
{
var namespaces = Namespaces.ToImmutable();
Namespaces = null;
var typeDefinitions = TypeDefinitions.ToImmutable();
TypeDefinitions = null;
var exportedTypes = ExportedTypes.ToImmutable();
ExportedTypes = null;
_frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes);
}
return _frozen;
}
public void MergeInto(NamespaceDataBuilder other)
{
Parent = default(NamespaceDefinitionHandle);
other.Namespaces.AddRange(this.Namespaces);
other.TypeDefinitions.AddRange(this.TypeDefinitions);
other.ExportedTypes.AddRange(this.ExportedTypes);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for ProjectProperty</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Build.UnitTests.OM.Definition
{
/// <summary>
/// Tests for ProjectProperty
/// </summary>
[TestClass]
public class ProjectProperty_Tests
{
/// <summary>
/// Project getter
/// </summary>
[TestMethod]
public void ProjectGetter()
{
Project project = new Project();
ProjectProperty property = project.SetProperty("p", "v");
Assert.AreEqual(true, Object.ReferenceEquals(project, property.Project));
}
/// <summary>
/// Property with nothing to expand
/// </summary>
[TestMethod]
public void NoExpansion()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>
";
ProjectProperty property = GetFirstProperty(content);
Assert.IsNotNull(property.Xml);
Assert.AreEqual("p", property.Name);
Assert.AreEqual("v1", property.EvaluatedValue);
Assert.AreEqual("v1", property.UnevaluatedValue);
}
/// <summary>
/// Embedded property
/// </summary>
[TestMethod]
public void ExpandProperty()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<o>v1</o>
<p>$(o)</p>
</PropertyGroup>
</Project>
";
ProjectProperty property = GetFirstProperty(content);
Assert.IsNotNull(property.Xml);
Assert.AreEqual("p", property.Name);
Assert.AreEqual("v1", property.EvaluatedValue);
Assert.AreEqual("$(o)", property.UnevaluatedValue);
}
/// <summary>
/// Set the value of a property
/// </summary>
[TestMethod]
public void SetValue()
{
Project project = new Project();
ProjectProperty property = project.SetProperty("p", "v1");
project.ReevaluateIfNecessary();
property.UnevaluatedValue = "v2";
Assert.AreEqual("v2", property.EvaluatedValue);
Assert.AreEqual("v2", property.UnevaluatedValue);
Assert.AreEqual(true, project.IsDirty);
}
/// <summary>
/// Set the value of a property
/// </summary>
[TestMethod]
public void SetValue_Escaped()
{
Project project = new Project();
ProjectProperty property = project.SetProperty("p", "v1");
project.ReevaluateIfNecessary();
property.UnevaluatedValue = "v%282%29";
Assert.AreEqual("v(2)", property.EvaluatedValue);
Assert.AreEqual("v%282%29", property.UnevaluatedValue);
Assert.AreEqual(true, project.IsDirty);
}
/// <summary>
/// Set the value of a property to the same value.
/// This should not dirty the project.
/// </summary>
[TestMethod]
public void SetValueSameValue()
{
Project project = new Project();
ProjectProperty property = project.SetProperty("p", "v1");
project.ReevaluateIfNecessary();
property.UnevaluatedValue = "v1";
Assert.AreEqual(false, project.IsDirty);
}
/// <summary>
/// Attempt to set the value of a built-in property
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void InvalidSetValueBuiltInProperty()
{
Project project = new Project();
ProjectProperty property = project.GetProperty("MSBuildProjectDirectory");
property.UnevaluatedValue = "v";
}
/// <summary>
/// Set the value of a property originating in the environment.
/// Should work even though there is no XML behind it.
/// Also, should persist.
/// </summary>
[TestMethod]
public void SetValueEnvironmentProperty()
{
Project project = new Project();
ProjectProperty property = project.GetProperty("Username");
property.UnevaluatedValue = "v";
Assert.AreEqual("v", property.EvaluatedValue);
Assert.AreEqual("v", property.UnevaluatedValue);
project.ReevaluateIfNecessary();
property = project.GetProperty("Username");
Assert.AreEqual("v", property.UnevaluatedValue);
}
/// <summary>
/// Test IsEnvironmentVariable
/// </summary>
[TestMethod]
public void IsEnvironmentVariable()
{
Project project = new Project();
Assert.AreEqual(true, project.GetProperty("username").IsEnvironmentProperty);
Assert.AreEqual(false, project.GetProperty("username").IsGlobalProperty);
Assert.AreEqual(false, project.GetProperty("username").IsReservedProperty);
Assert.AreEqual(false, project.GetProperty("username").IsImported);
}
/// <summary>
/// Test IsGlobalProperty
/// </summary>
[TestMethod]
public void IsGlobalProperty()
{
Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties["g"] = String.Empty;
Project project = new Project(globalProperties, null, ProjectCollection.GlobalProjectCollection);
Assert.AreEqual(false, project.GetProperty("g").IsEnvironmentProperty);
Assert.AreEqual(true, project.GetProperty("g").IsGlobalProperty);
Assert.AreEqual(false, project.GetProperty("g").IsReservedProperty);
Assert.AreEqual(false, project.GetProperty("g").IsImported);
}
/// <summary>
/// Test IsReservedProperty
/// </summary>
[TestMethod]
public void IsReservedProperty()
{
Project project = new Project();
project.FullPath = @"c:\x";
project.ReevaluateIfNecessary();
Assert.AreEqual(false, project.GetProperty("MSBuildProjectFile").IsEnvironmentProperty);
Assert.AreEqual(false, project.GetProperty("MSBuildProjectFile").IsGlobalProperty);
Assert.AreEqual(true, project.GetProperty("MSBuildProjectFile").IsReservedProperty);
Assert.AreEqual(false, project.GetProperty("MSBuildProjectFile").IsImported);
}
/// <summary>
/// Verify properties are expanded in new property values
/// </summary>
[TestMethod]
public void SetPropertyWithPropertyExpression()
{
Project project = new Project();
project.SetProperty("p0", "v0");
ProjectProperty property = project.SetProperty("p1", "v1");
property.UnevaluatedValue = "$(p0)";
Assert.AreEqual("v0", project.GetPropertyValue("p1"));
Assert.AreEqual("v0", property.EvaluatedValue);
Assert.AreEqual("$(p0)", property.UnevaluatedValue);
}
/// <summary>
/// Verify item expressions are not expanded in new property values.
/// NOTE: They aren't expanded to "blank". It just seems like that, because
/// when you output them, item expansion happens after property expansion, and
/// they may evaluate to blank then. (Unless items do exist at that point.)
/// </summary>
[TestMethod]
public void SetPropertyWithItemAndMetadataExpression()
{
Project project = new Project();
project.SetProperty("p0", "v0");
ProjectProperty property = project.SetProperty("p1", "v1");
property.UnevaluatedValue = "@(i)-%(m)";
Assert.AreEqual("@(i)-%(m)", project.GetPropertyValue("p1"));
Assert.AreEqual("@(i)-%(m)", property.EvaluatedValue);
Assert.AreEqual("@(i)-%(m)", property.UnevaluatedValue);
}
/// <summary>
/// Attempt to set value on imported property should fail
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void SetPropertyImported()
{
string file = null;
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
Project import = new Project();
import.SetProperty("p", "v0");
import.Save(file);
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddImport(file);
Project project = new Project(xml);
ProjectProperty property = project.GetProperty("p");
property.UnevaluatedValue = "v1";
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Get the property named "p" in the project provided
/// </summary>
private static ProjectProperty GetFirstProperty(string content)
{
ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
Project project = new Project(projectXml);
ProjectProperty property = project.GetProperty("p");
return property;
}
}
}
| |
//
// SmallXmlParser.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// small xml parser that is mostly compatible with
//
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
namespace Mono.Xml
{
internal class DefaultHandler : SmallXmlParser.IContentHandler
{
public void OnStartParsing (SmallXmlParser parser)
{
}
public void OnEndParsing (SmallXmlParser parser)
{
}
public void OnStartElement (string name, SmallXmlParser.IAttrList attrs)
{
}
public void OnEndElement (string name)
{
}
public void OnChars (string s)
{
}
public void OnIgnorableWhitespace (string s)
{
}
public void OnProcessingInstruction (string name, string text)
{
}
}
internal class SmallXmlParser
{
public interface IContentHandler
{
void OnStartParsing (SmallXmlParser parser);
void OnEndParsing (SmallXmlParser parser);
void OnStartElement (string name, IAttrList attrs);
void OnEndElement (string name);
void OnProcessingInstruction (string name, string text);
void OnChars (string text);
void OnIgnorableWhitespace (string text);
}
public interface IAttrList
{
int Length { get; }
bool IsEmpty { get; }
string GetName (int i);
string GetValue (int i);
string GetValue (string name);
string [] Names { get; }
string [] Values { get; }
}
class AttrListImpl : IAttrList
{
public int Length {
get { return attrNames.Count; }
}
public bool IsEmpty {
get { return attrNames.Count == 0; }
}
public string GetName (int i)
{
return (string) attrNames [i];
}
public string GetValue (int i)
{
return (string) attrValues [i];
}
public string GetValue (string name)
{
for (int i = 0; i < attrNames.Count; i++)
if ((string) attrNames [i] == name)
return (string) attrValues [i];
return null;
}
public string [] Names {
get { return (string []) attrNames.ToArray (typeof (string)); }
}
public string [] Values {
get { return (string []) attrValues.ToArray (typeof (string)); }
}
ArrayList attrNames = new ArrayList ();
ArrayList attrValues = new ArrayList ();
internal void Clear ()
{
attrNames.Clear ();
attrValues.Clear ();
}
internal void Add (string name, string value)
{
attrNames.Add (name);
attrValues.Add (value);
}
}
IContentHandler handler;
TextReader reader;
Stack elementNames = new Stack ();
Stack xmlSpaces = new Stack ();
string xmlSpace;
StringBuilder buffer = new StringBuilder (200);
char [] nameBuffer = new char [30];
bool isWhitespace;
AttrListImpl attributes = new AttrListImpl ();
int line = 1, column;
bool resetColumn;
public SmallXmlParser ()
{
}
private Exception Error (string msg)
{
return new SmallXmlParserException (msg, line, column);
}
private Exception UnexpectedEndError ()
{
string [] arr = new string [elementNames.Count];
// COMPACT FRAMEWORK NOTE: CopyTo is not visible through the Stack class
(elementNames as ICollection).CopyTo (arr, 0);
return Error (String.Format (
"Unexpected end of stream. Element stack content is {0}", String.Join (",", arr)));
}
private bool IsNameChar (char c, bool start)
{
switch (c) {
case ':':
case '_':
return true;
case '-':
case '.':
return !start;
}
if (c > 0x100) { // optional condition for optimization
switch (c) {
case '\u0559':
case '\u06E5':
case '\u06E6':
return true;
}
if ('\u02BB' <= c && c <= '\u02C1')
return true;
}
switch (Char.GetUnicodeCategory (c)) {
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.LetterNumber:
return true;
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.DecimalDigitNumber:
return !start;
default:
return false;
}
}
private bool IsWhitespace (int c)
{
switch (c) {
case ' ':
case '\r':
case '\t':
case '\n':
return true;
default:
return false;
}
}
public void SkipWhitespaces ()
{
SkipWhitespaces (false);
}
private void HandleWhitespaces ()
{
while (IsWhitespace (Peek ()))
buffer.Append ((char) Read ());
if (Peek () != '<' && Peek () >= 0)
isWhitespace = false;
}
public void SkipWhitespaces (bool expected)
{
while (true) {
switch (Peek ()) {
case ' ':
case '\r':
case '\t':
case '\n':
Read ();
if (expected)
expected = false;
continue;
}
if (expected)
throw Error ("Whitespace is expected.");
return;
}
}
private int Peek ()
{
return reader.Peek ();
}
private int Read ()
{
int i = reader.Read ();
if (i == '\n')
resetColumn = true;
if (resetColumn) {
line++;
resetColumn = false;
column = 1;
}
else
column++;
return i;
}
public void Expect (int c)
{
int p = Read ();
if (p < 0)
throw UnexpectedEndError ();
else if (p != c)
throw Error (String.Format ("Expected '{0}' but got {1}", (char) c, (char) p));
}
private string ReadUntil (char until, bool handleReferences)
{
while (true) {
if (Peek () < 0)
throw UnexpectedEndError ();
char c = (char) Read ();
if (c == until)
break;
else if (handleReferences && c == '&')
ReadReference ();
else
buffer.Append (c);
}
string ret = buffer.ToString ();
buffer.Length = 0;
return ret;
}
public string ReadName ()
{
int idx = 0;
if (Peek () < 0 || !IsNameChar ((char) Peek (), true))
throw Error ("XML name start character is expected.");
for (int i = Peek (); i >= 0; i = Peek ()) {
char c = (char) i;
if (!IsNameChar (c, false))
break;
if (idx == nameBuffer.Length) {
char [] tmp = new char [idx * 2];
// COMPACT FRAMEWORK NOTE: Array.Copy(sourceArray, destinationArray, count) is not available.
Array.Copy (nameBuffer, 0, tmp, 0, idx);
nameBuffer = tmp;
}
nameBuffer [idx++] = c;
Read ();
}
if (idx == 0)
throw Error ("Valid XML name is expected.");
return new string (nameBuffer, 0, idx);
}
public void Parse (TextReader input, IContentHandler handler)
{
this.reader = input;
this.handler = handler;
handler.OnStartParsing (this);
while (Peek () >= 0)
ReadContent ();
HandleBufferedContent ();
if (elementNames.Count > 0)
throw Error (String.Format ("Insufficient close tag: {0}", elementNames.Peek ()));
handler.OnEndParsing (this);
Cleanup ();
}
private void Cleanup ()
{
line = 1;
column = 0;
handler = null;
reader = null;
#if CF_1_0
elementNames = new Stack ();
xmlSpaces = new Stack ();
#else
elementNames.Clear ();
xmlSpaces.Clear ();
#endif
attributes.Clear ();
buffer.Length = 0;
xmlSpace = null;
isWhitespace = false;
}
public void ReadContent ()
{
string name;
if (IsWhitespace (Peek ())) {
if (buffer.Length == 0)
isWhitespace = true;
HandleWhitespaces ();
}
if (Peek () == '<') {
Read ();
switch (Peek ()) {
case '!': // declarations
Read ();
if (Peek () == '[') {
Read ();
if (ReadName () != "CDATA")
throw Error ("Invalid declaration markup");
Expect ('[');
ReadCDATASection ();
return;
}
else if (Peek () == '-') {
ReadComment ();
return;
}
else if (ReadName () != "DOCTYPE")
throw Error ("Invalid declaration markup.");
else
throw Error ("This parser does not support document type.");
case '?': // PIs
HandleBufferedContent ();
Read ();
name = ReadName ();
SkipWhitespaces ();
string text = String.Empty;
if (Peek () != '?') {
while (true) {
text += ReadUntil ('?', false);
if (Peek () == '>')
break;
text += "?";
}
}
handler.OnProcessingInstruction (
name, text);
Expect ('>');
return;
case '/': // end tags
HandleBufferedContent ();
if (elementNames.Count == 0)
throw UnexpectedEndError ();
Read ();
name = ReadName ();
SkipWhitespaces ();
string expected = (string) elementNames.Pop ();
xmlSpaces.Pop ();
if (xmlSpaces.Count > 0)
xmlSpace = (string) xmlSpaces.Peek ();
else
xmlSpace = null;
if (name != expected)
throw Error (String.Format ("End tag mismatch: expected {0} but found {1}", expected, name));
handler.OnEndElement (name);
Expect ('>');
return;
default: // start tags (including empty tags)
HandleBufferedContent ();
name = ReadName ();
while (Peek () != '>' && Peek () != '/')
ReadAttribute (attributes);
handler.OnStartElement (name, attributes);
attributes.Clear ();
SkipWhitespaces ();
if (Peek () == '/') {
Read ();
handler.OnEndElement (name);
}
else {
elementNames.Push (name);
xmlSpaces.Push (xmlSpace);
}
Expect ('>');
return;
}
}
else
ReadCharacters ();
}
private void HandleBufferedContent ()
{
if (buffer.Length == 0)
return;
if (isWhitespace)
handler.OnIgnorableWhitespace (buffer.ToString ());
else
handler.OnChars (buffer.ToString ());
buffer.Length = 0;
isWhitespace = false;
}
private void ReadCharacters ()
{
isWhitespace = false;
while (true) {
int i = Peek ();
switch (i) {
case -1:
return;
case '<':
return;
case '&':
Read ();
ReadReference ();
continue;
default:
buffer.Append ((char) Read ());
continue;
}
}
}
private void ReadReference ()
{
if (Peek () == '#') {
// character reference
Read ();
ReadCharacterReference ();
} else {
string name = ReadName ();
Expect (';');
switch (name) {
case "amp":
buffer.Append ('&');
break;
case "quot":
buffer.Append ('"');
break;
case "apos":
buffer.Append ('\'');
break;
case "lt":
buffer.Append ('<');
break;
case "gt":
buffer.Append ('>');
break;
default:
throw Error ("General non-predefined entity reference is not supported in this parser.");
}
}
}
private int ReadCharacterReference ()
{
int n = 0;
if (Peek () == 'x') { // hex
Read ();
for (int i = Peek (); i >= 0; i = Peek ()) {
if ('0' <= i && i <= '9')
n = n << 4 + i - '0';
else if ('A' <= i && i <='F')
n = n << 4 + i - 'A' + 10;
else if ('a' <= i && i <='f')
n = n << 4 + i - 'a' + 10;
else
break;
Read ();
}
} else {
for (int i = Peek (); i >= 0; i = Peek ()) {
if ('0' <= i && i <= '9')
n = n << 4 + i - '0';
else
break;
Read ();
}
}
return n;
}
private void ReadAttribute (AttrListImpl a)
{
SkipWhitespaces (true);
if (Peek () == '/' || Peek () == '>')
// came here just to spend trailing whitespaces
return;
string name = ReadName ();
string value;
SkipWhitespaces ();
Expect ('=');
SkipWhitespaces ();
switch (Read ()) {
case '\'':
value = ReadUntil ('\'', true);
break;
case '"':
value = ReadUntil ('"', true);
break;
default:
throw Error ("Invalid attribute value markup.");
}
if (name == "xml:space")
xmlSpace = value;
a.Add (name, value);
}
private void ReadCDATASection ()
{
int nBracket = 0;
while (true) {
if (Peek () < 0)
throw UnexpectedEndError ();
char c = (char) Read ();
if (c == ']')
nBracket++;
else if (c == '>' && nBracket > 1) {
for (int i = nBracket; i > 2; i--)
buffer.Append (']');
break;
}
else {
for (int i = 0; i < nBracket; i++)
buffer.Append (']');
nBracket = 0;
buffer.Append (c);
}
}
}
private void ReadComment ()
{
Expect ('-');
Expect ('-');
while (true) {
if (Read () != '-')
continue;
if (Read () != '-')
continue;
if (Read () != '>')
throw Error ("'--' is not allowed inside comment markup.");
break;
}
}
}
internal class SmallXmlParserException : SystemException
{
int line;
int column;
public SmallXmlParserException (string msg, int line, int column)
: base (String.Format ("{0}. At ({1},{2})", msg, line, column))
{
this.line = line;
this.column = column;
}
public int Line {
get { return line; }
}
public int Column {
get { return column; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
public class FileController
{
public static void RemakeDirectory(string localFolderPath)
{
if (Directory.Exists(localFolderPath)) Directory.Delete(localFolderPath, true);
Directory.CreateDirectory(localFolderPath);
}
/**
default is "overwrite same path" by filepath.
*/
public static void CopyFile(string absoluteSourceFilePath, string localTargetFilePath)
{
var parentDirectoryPath = Path.GetDirectoryName(localTargetFilePath);
Directory.CreateDirectory(parentDirectoryPath);
File.Copy(absoluteSourceFilePath, localTargetFilePath, true);
}
public static string LiftupPath(string path, int level)
{
var splitted = path.Split('/').ToList();
if (splitted.Count <= level) throw new Exception("lifting path deepness is too short:" + path + " by required level:" + level);
for (var i = 0; i < level; i++) splitted.RemoveAt(0);
var removed = string.Join("/", splitted.ToArray());
return removed;
}
// public static void DeleteFileThenDeleteFolderIfEmpty (string localTargetFilePath) {
// File.Delete(localTargetFilePath);
// File.Delete(localTargetFilePath + AssetBundleGraphSettings.UNITY_METAFILE_EXTENSION);
// var directoryPath = Directory.GetParent(localTargetFilePath).FullName;
// var restFiles = FilePathsInFolder(directoryPath);
// if (!restFiles.Any()) {
// Directory.Delete(directoryPath, true);
// File.Delete(directoryPath + AssetBundleGraphSettings.UNITY_METAFILE_EXTENSION);
// }
// }
public static List<string> FilePathsOfFile(string filePath)
{
var folderPath = Path.GetDirectoryName(filePath);
var results = FilePathsInFolder(folderPath);
return results;
}
public static List<string> FilePathsInFolder(string localFolderPath)
{
var filePaths = new List<string>();
if (string.IsNullOrEmpty(localFolderPath)) return filePaths;
if (!Directory.Exists(localFolderPath)) return filePaths;
GetFilePathsRecursive(localFolderPath, filePaths);
return filePaths;
}
private static void GetFilePathsRecursive(string localFolderPath, List<string> filePaths)
{
var folders = Directory.GetDirectories(localFolderPath);
foreach (var folder in folders)
{
GetFilePathsRecursive(folder, filePaths);
}
var files = FilePathsInFolderOnly1Level(localFolderPath);
filePaths.AddRange(files);
}
public static List<string> FolderPathsInFolder(string path)
{
// change platform-depends folder delimiter -> '/'
return ConvertSeparater(Directory.GetDirectories(path).ToList());
}
public static void CreateDirectoryRecursively(string path)
{
var paths = path.Split('/');
CreateDirectoryRecursively(paths);
}
public static void CreateDirectoryRecursively(string[] paths)
{
var basePath = string.Empty;
foreach (var path in paths)
{
basePath = Path.Combine(basePath, path);
Directory.CreateDirectory(basePath);
}
}
/**
returns file paths which are located in the folder.
this method is main point for supporting path format of cross platform.
Usually Unity Editor uses '/' as folder delimter.
e.g.
Application.dataPath returns
C:/somewhere/projectPath/Assets @ Windows.
or
/somewhere/projectPath/Assets @ Mac, Linux.
but "Directory.GetFiles(localFolderPath + "/")" method returns different formatted path by platform.
@ Windows:
localFolderPath + / + somewhere\folder\file.extention
@ Mac/Linux:
localFolderPath + / + somewhere/folder/file.extention
the problem is, "Directory.GetFiles" returns mixed format path of files @ Windows.
this is the point of failure.
this method replaces folder delimiters to '/'.
*/
public static List<string> FilePathsInFolderOnly1Level(string localFolderPath)
{
// change platform-depends folder delimiter -> '/'
var filePaths = ConvertSeparater(Directory.GetFiles(localFolderPath)
.Where(path => !(Path.GetFileName(path).StartsWith(".")))
.ToList());
if (true) filePaths = filePaths.Where(path => !IsMetaFile(path)).ToList();
return filePaths;
}
public static List<string> ConvertSeparater(List<string> source)
{
return source.Select(filePath => filePath.Replace(Path.DirectorySeparatorChar.ToString(), "/")).ToList();
}
/**
create combination of path.
delimiter is always '/'.
*/
public static string PathCombine(params string[] paths)
{
if (paths.Length < 2)
{
throw new ArgumentException("Argument must contain at least 2 strings to combine.");
}
var combinedPath = _PathCombine(paths[0], paths[1]);
var restPaths = new string[paths.Length - 2];
Array.Copy(paths, 2, restPaths, 0, restPaths.Length);
foreach (var path in restPaths) combinedPath = _PathCombine(combinedPath, path);
return combinedPath;
}
private static string _PathCombine(string head, string tail)
{
if (!head.EndsWith("/")) head = head + "/";
if (string.IsNullOrEmpty(tail)) return head;
if (tail.StartsWith("/")) tail = tail.Substring(1);
return Path.Combine(head, tail);
}
public static string GetPathWithProjectPath(string pathUnderProjectFolder)
{
var assetPath = Application.dataPath;
var projectPath = Directory.GetParent(assetPath).ToString();
return PathCombine(projectPath, pathUnderProjectFolder);
}
public static string GetPathWithAssetsPath(string pathUnderAssetsFolder)
{
var assetPath = Application.dataPath;
return PathCombine(assetPath, pathUnderAssetsFolder);
}
public static string ProjectPathWithSlash()
{
var assetPath = Application.dataPath;
return Directory.GetParent(assetPath).ToString() + "/";
}
public static bool IsMetaFile(string filePath)
{
if (filePath.EndsWith(".meta")) return true;
return false;
}
public static bool ContainsHiddenFiles(string filePath)
{
var pathComponents = filePath.Split("/".ToCharArray());
foreach (var path in pathComponents)
{
if (path.StartsWith(".")) 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.Linq;
using System.Xml.Linq;
namespace System.Xml.XPath
{
internal class XNodeNavigator : XPathNavigator, IXmlLineInfo
{
internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName;
internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName;
private const int DocumentContentMask =
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment);
private static readonly int[] s_ElementContentMasks = {
0, // Root
(1 << (int)XmlNodeType.Element), // Element
0, // Attribute
0, // Namespace
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text), // Text
0, // SignificantWhitespace
0, // Whitespace
(1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction
(1 << (int)XmlNodeType.Comment), // Comment
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment) // All
};
private const int TextMask =
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text);
private static XAttribute s_XmlNamespaceDeclaration;
// The navigator position is encoded by the tuple (source, parent).
// Namespace declaration uses (instance, parent element).
// Common XObjects uses (instance, null).
private XObject _source;
private XElement _parent;
private XmlNameTable _nameTable;
public XNodeNavigator(XNode node, XmlNameTable nameTable)
{
_source = node;
_nameTable = nameTable != null ? nameTable : CreateNameTable();
}
public XNodeNavigator(XNodeNavigator other)
{
_source = other._source;
_parent = other._parent;
_nameTable = other._nameTable;
}
public override string BaseURI
{
get
{
if (_source != null)
{
return _source.BaseUri;
}
if (_parent != null)
{
return _parent.BaseUri;
}
return string.Empty;
}
}
public override bool HasAttributes
{
get
{
XElement element = _source as XElement;
if (element != null)
{
foreach (XAttribute attribute in element.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
return true;
}
}
}
return false;
}
}
public override bool HasChildren
{
get
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
return true;
}
}
}
return false;
}
}
public override bool IsEmptyElement
{
get
{
XElement e = _source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return _nameTable.Add(GetLocalName()); }
}
string GetLocalName()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null && a.Name.NamespaceName.Length == 0)
{
return string.Empty; // backcompat
}
return a.Name.LocalName;
}
XProcessingInstruction p = _source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return _nameTable.Add(GetLocalName());
}
return _nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return _nameTable.Add(GetNamespaceURI()); }
}
string GetNamespaceURI()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
return a.Name.NamespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
public override XPathNodeType NodeType
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return XPathNodeType.Element;
case XmlNodeType.Attribute:
XAttribute attribute = (XAttribute)_source;
return attribute.IsNamespaceDeclaration ? XPathNodeType.Namespace : XPathNodeType.Attribute;
case XmlNodeType.Document:
return XPathNodeType.Root;
case XmlNodeType.Comment:
return XPathNodeType.Comment;
case XmlNodeType.ProcessingInstruction:
return XPathNodeType.ProcessingInstruction;
default:
return XPathNodeType.Text;
}
}
return XPathNodeType.Text;
}
}
public override string Prefix
{
get { return _nameTable.Add(GetPrefix()); }
}
string GetPrefix()
{
XElement e = _source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override object UnderlyingObject
{
get
{
return _source;
}
}
public override string Value
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return ((XElement)_source).Value;
case XmlNodeType.Attribute:
return ((XAttribute)_source).Value;
case XmlNodeType.Document:
XElement root = ((XDocument)_source).Root;
return root != null ? root.Value : string.Empty;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return CollectText((XText)_source);
case XmlNodeType.Comment:
return ((XComment)_source).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)_source).Data;
default:
return string.Empty;
}
}
return string.Empty;
}
}
public override XPathNavigator Clone()
{
return new XNodeNavigator(this);
}
public override bool IsSamePosition(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other == null)
{
return false;
}
return IsSamePosition(this, other);
}
public override bool MoveTo(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other != null)
{
_source = other._source;
_parent = other._parent;
return true;
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.Name.LocalName == localName &&
attribute.Name.NamespaceName == namespaceName &&
!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToChild(string localName, string namespaceName)
{
XContainer c = _source as XContainer;
if (c != null)
{
foreach (XElement element in c.Elements())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToChild(XPathNodeType type)
{
XContainer c = _source as XContainer;
if (c != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument)
{
mask &= ~TextMask;
}
foreach (XNode node in c.Nodes())
{
if (((1 << (int)node.NodeType) & mask) != 0)
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToFirstChild()
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
XElement e = _source as XElement;
if (e != null)
{
XAttribute a = null;
switch (scope)
{
case XPathNamespaceScope.Local:
a = GetFirstNamespaceDeclarationLocal(e);
break;
case XPathNamespaceScope.ExcludeXml:
a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null && a.Name.LocalName == "xml")
{
a = GetNextNamespaceDeclarationGlobal(a);
}
break;
case XPathNamespaceScope.All:
a = GetFirstNamespaceDeclarationGlobal(e);
if (a == null)
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToId(string id)
{
throw new NotSupportedException(SR.NotSupported_MoveToId);
}
public override bool MoveToNamespace(string localName)
{
XElement e = _source as XElement;
if (e != null)
{
if (localName == "xmlns")
{
return false; // backcompat
}
if (localName != null && localName.Length == 0)
{
localName = "xmlns"; // backcompat
}
XAttribute a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null)
{
if (a.Name.LocalName == localName)
{
_source = a;
_parent = e;
return true;
}
a = GetNextNamespaceDeclarationGlobal(a);
}
if (localName == "xml")
{
_source = GetXmlNamespaceDeclaration();
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToNext()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (next == null)
{
break;
}
if (IsContent(container, next) && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNext(string localName, string namespaceName)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
foreach (XElement element in currentNode.ElementsAfterSelf())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToNext(XPathNodeType type)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && container.GetParent() == null && container is XDocument)
{
mask &= ~TextMask;
}
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (((1 << (int)next.NodeType) & mask) != 0 && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextAttribute()
{
XAttribute currentAttribute = _source as XAttribute;
if (currentAttribute != null && _parent == null)
{
XElement e = (XElement)currentAttribute.GetParent();
if (e != null)
{
for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute)
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
XAttribute a = _source as XAttribute;
if (a != null && _parent != null && !IsXmlNamespaceDeclaration(a))
{
switch (scope)
{
case XPathNamespaceScope.Local:
if (a.GetParent() != _parent)
{
return false;
}
a = GetNextNamespaceDeclarationLocal(a);
break;
case XPathNamespaceScope.ExcludeXml:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
(a.Name.LocalName == "xml" ||
HasNamespaceDeclarationInScope(a, _parent)));
break;
case XPathNamespaceScope.All:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
HasNamespaceDeclarationInScope(a, _parent));
if (a == null &&
!HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent))
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
return true;
}
}
return false;
}
public override bool MoveToParent()
{
if (_parent != null)
{
_source = _parent;
_parent = null;
return true;
}
XNode parentNode = _source.GetParent();
if (parentNode != null)
{
_source = parentNode;
return true;
}
return false;
}
public override bool MoveToPrevious()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode previous = null;
foreach (XNode node in container.Nodes())
{
if (node == currentNode)
{
if (previous != null)
{
_source = previous;
return true;
}
return false;
}
if (IsContent(container, node))
{
previous = node;
}
}
}
}
return false;
}
public override XmlReader ReadSubtree()
{
XContainer c = _source as XContainer;
if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType));
return c.CreateReader();
}
bool IXmlLineInfo.HasLineInfo()
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
return 0;
}
}
static string CollectText(XText n)
{
string s = n.Value;
if (n.GetParent() != null)
{
foreach (XNode node in n.NodesAfterSelf())
{
XText t = node as XText;
if (t == null) break;
s += t.Value;
}
}
return s;
}
static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(xmlnsPrefixNamespace);
nameTable.Add(xmlPrefixNamespace);
return nameTable;
}
static bool IsContent(XContainer c, XNode n)
{
if (c.GetParent() != null || c is XElement)
{
return true;
}
return ((1 << (int)n.NodeType) & DocumentContentMask) != 0;
}
static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2)
{
return n1._source == n2._source && n1._source.GetParent() == n2._source.GetParent();
}
static bool IsXmlNamespaceDeclaration(XAttribute a)
{
return (object)a == (object)GetXmlNamespaceDeclaration();
}
static int GetElementContentMask(XPathNodeType type)
{
return s_ElementContentMasks[(int)type];
}
static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e)
{
do
{
XAttribute a = GetFirstNamespaceDeclarationLocal(e);
if (a != null)
{
return a;
}
e = e.Parent;
} while (e != null);
return null;
}
static XAttribute GetFirstNamespaceDeclarationLocal(XElement e)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.IsNamespaceDeclaration)
{
return attribute;
}
}
return null;
}
static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a)
{
XElement e = (XElement)a.GetParent();
if (e == null)
{
return null;
}
XAttribute next = GetNextNamespaceDeclarationLocal(a);
if (next != null)
{
return next;
}
e = e.Parent;
if (e == null)
{
return null;
}
return GetFirstNamespaceDeclarationGlobal(e);
}
static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a)
{
XElement e = a.Parent;
if (e == null)
{
return null;
}
a = a.NextAttribute;
while (a != null)
{
if (a.IsNamespaceDeclaration)
{
return a;
}
a = a.NextAttribute;
}
return null;
}
static XAttribute GetXmlNamespaceDeclaration()
{
if (s_XmlNamespaceDeclaration == null)
{
System.Threading.Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null);
}
return s_XmlNamespaceDeclaration;
}
static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e)
{
XName name = a.Name;
while (e != null && e != a.GetParent())
{
if (e.Attribute(name) != null)
{
return true;
}
e = e.Parent;
}
return false;
}
}
struct XPathEvaluator
{
public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class
{
XPathNavigator navigator = node.CreateNavigator();
object result = navigator.Evaluate(expression, resolver);
XPathNodeIterator iterator = result as XPathNodeIterator;
if (iterator != null)
{
return EvaluateIterator<T>(iterator);
}
if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType()));
return (T)result;
}
IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result)
{
foreach (XPathNavigator navigator in result)
{
object r = navigator.UnderlyingObject;
if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType()));
yield return (T)r;
XText t = r as XText;
if (t != null && t.GetParent() != null)
{
foreach (XNode node in t.GetParent().Nodes())
{
t = node as XText;
if (t == null) break;
yield return (T)(object)t;
}
}
}
}
}
/// <summary>
/// Extension methods
/// </summary>
public static class Extensions
{
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node)
{
return node.CreateNavigator(null);
}
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by
/// the <see cref="XPathNavigator"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType));
XText text = node as XText;
if (text != null)
{
if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace));
node = CalibrateText(text);
}
return new XNodeNavigator(node, nameTable);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression)
{
return node.XPathEvaluate(expression, null);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace
/// prefixes used in the XPath expression</see></param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return new XPathEvaluator().Evaluate<object>(node, expression, resolver);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression)
{
return node.XPathSelectElement(expression, null);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
return node.XPathSelectElements(expression, resolver).FirstOrDefault();
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression)
{
return node.XPathSelectElements(expression, null);
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver);
}
static XText CalibrateText(XText n)
{
XContainer parentNode = n.GetParent();
if (parentNode == null)
{
return n;
}
foreach (XNode node in parentNode.Nodes())
{
XText t = node as XText;
bool isTextNode = t != null;
if (isTextNode && node == n)
{
return t;
}
}
System.Diagnostics.Debug.Fail("Parent node doesn't contain itself.");
return null;
}
}
}
| |
// ReSharper disable All
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
using Frapid.WebApi;
using Frapid.Account.Entities;
using Frapid.Account.DataAccess;
namespace Frapid.Account.Api
{
/// <summary>
/// Provides a direct HTTP access to execute the function ResetAccount.
/// </summary>
[RoutePrefix("api/v1.0/account/procedures/reset-account")]
public class ResetAccountController : FrapidApiController
{
/// <summary>
/// The ResetAccount repository.
/// </summary>
private IResetAccountRepository repository;
public class Annotation
{
public string Email { get; set; }
public string Browser { get; set; }
public string IpAddress { get; set; }
}
public ResetAccountController()
{
}
public ResetAccountController(IResetAccountRepository repository)
{
this.repository = repository;
}
protected override void Initialize(HttpControllerContext context)
{
base.Initialize(context);
if (this.repository == null)
{
this.repository = new ResetAccountProcedure
{
_Catalog = this.MetaUser.Catalog,
_LoginId = this.MetaUser.LoginId,
_UserId = this.MetaUser.UserId
};
}
}
/// <summary>
/// Creates meta information of "reset account" annotation.
/// </summary>
/// <returns>Returns the "reset account" annotation meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("annotation")]
[Route("~/api/account/procedures/reset-account/annotation")]
[RestAuthorize]
public EntityView GetAnnotation()
{
return new EntityView
{
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "_email",
PropertyName = "Email",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "_browser",
PropertyName = "Browser",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "_ip_address",
PropertyName = "IpAddress",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
/// <summary>
/// Creates meta information of "reset account" entity.
/// </summary>
/// <returns>Returns the "reset account" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/account/procedures/reset-account/meta")]
[RestAuthorize]
public EntityView GetEntityView()
{
return new EntityView
{
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "request_id",
PropertyName = "RequestId",
DataType = "System.Guid",
DbDataType = "uuid",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "user_id",
PropertyName = "UserId",
DataType = "int",
DbDataType = "integer",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "email",
PropertyName = "Email",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "name",
PropertyName = "Name",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "requested_on",
PropertyName = "RequestedOn",
DataType = "DateTime",
DbDataType = "timestamp with time zone",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "expires_on",
PropertyName = "ExpiresOn",
DataType = "DateTime",
DbDataType = "timestamp with time zone",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "browser",
PropertyName = "Browser",
DataType = "string",
DbDataType = "text",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "ip_address",
PropertyName = "IpAddress",
DataType = "string",
DbDataType = "character varying",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "confirmed",
PropertyName = "Confirmed",
DataType = "bool",
DbDataType = "boolean",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "confirmed_on",
PropertyName = "ConfirmedOn",
DataType = "DateTime",
DbDataType = "timestamp with time zone",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
[AcceptVerbs("POST")]
[Route("execute")]
[Route("~/api/account/procedures/reset-account/execute")]
[RestAuthorize]
public IEnumerable<DbResetAccountResult> Execute([FromBody] Annotation annotation)
{
try
{
this.repository.Email = annotation.Email;
this.repository.Browser = annotation.Browser;
this.repository.IpAddress = annotation.IpAddress;
return this.repository.Execute();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#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.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public class InteractiveWindowTests : IDisposable
{
#region Helpers
private InteractiveWindowTestHost _testHost;
private List<InteractiveWindow.State> _states;
private readonly TestClipboard _testClipboard;
public InteractiveWindowTests()
{
_states = new List<InteractiveWindow.State>();
_testHost = new InteractiveWindowTestHost(_states.Add);
_testClipboard = new TestClipboard();
((InteractiveWindow)Window).InteractiveWindowClipboard = _testClipboard;
}
void IDisposable.Dispose()
{
_testHost.Dispose();
}
private IInteractiveWindow Window => _testHost.Window;
private static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames)
{
foreach (var name in commandNames)
{
var mock = new Mock<IInteractiveWindowCommand>();
mock.Setup(m => m.Names).Returns(new[] { name });
yield return mock.Object;
}
}
private static ITextSnapshot MockSnapshot(string content)
{
var snapshotMock = new Mock<ITextSnapshot>();
snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]);
snapshotMock.Setup(m => m.Length).Returns(content.Length);
snapshotMock.Setup(m => m.GetText()).Returns(content);
snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length));
snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length));
return snapshotMock.Object;
}
#endregion
[Fact]
public void InteractiveWindow__CommandParsing()
{
var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray();
var commands = new Commands.Commands(null, "%", commandList);
AssertEx.Equal(commands.GetCommands(), commandList);
var cmdBar = commandList[1];
Assert.Equal("bar", cmdBar.Names.First());
Assert.Equal("%", commands.CommandPrefix);
commands.CommandPrefix = "#";
Assert.Equal("#", commands.CommandPrefix);
//// 111111
//// 0123456789012345
var s1 = MockSnapshot("#bar arg1 arg2 ");
SnapshotSpan prefixSpan, commandSpan, argsSpan;
IInteractiveWindowCommand cmd;
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(2, commandSpan.End);
Assert.Equal(2, argsSpan.Start);
Assert.Equal(2, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(3, commandSpan.End);
Assert.Equal(3, argsSpan.Start);
Assert.Equal(3, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(4, argsSpan.Start);
Assert.Equal(4, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(5, argsSpan.End);
cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(14, argsSpan.End);
////
//// 0123456789
var s2 = MockSnapshot(" #bar ");
cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(3, commandSpan.Start);
Assert.Equal(6, commandSpan.End);
Assert.Equal(9, argsSpan.Start);
Assert.Equal(9, argsSpan.End);
//// 111111
//// 0123456789012345
var s3 = MockSnapshot(" # bar args");
cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(6, commandSpan.Start);
Assert.Equal(9, commandSpan.End);
Assert.Equal(11, argsSpan.Start);
Assert.Equal(15, argsSpan.End);
}
[Fact]
public void InteractiveWindow_GetCommands()
{
var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands(
Window,
"#",
_testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray());
var commands = interactiveCommands.GetCommands();
Assert.NotEmpty(commands);
Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count());
Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count());
Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault());
Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault());
}
[WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")]
[Fact]
public void ResetStateTransitions()
{
Window.Operations.ResetAsync().PumpingWait();
Assert.Equal(_states, new[]
{
InteractiveWindow.State.Initializing,
InteractiveWindow.State.WaitingForInput,
InteractiveWindow.State.Resetting,
InteractiveWindow.State.WaitingForInput,
});
}
[Fact]
public void DoubleInitialize()
{
try
{
Window.InitializeAsync().PumpingWait();
Assert.True(false);
}
catch (AggregateException e)
{
Assert.IsType<InvalidOperationException>(e.InnerExceptions.Single());
}
}
[Fact]
public void AccessPropertiesOnUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
property.GetMethod.Invoke(Window, Array.Empty<object>());
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
[Fact]
public void AccessPropertiesOnNonUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
Task.Run(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).PumpingWait();
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
/// <remarks>
/// Confirm that we are, in fact, running on a non-UI thread.
/// </remarks>
[Fact]
public void NonUIThread()
{
Task.Run(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).PumpingWait();
}
[Fact]
public void CallCloseOnNonUIThread()
{
Task.Run(() => Window.Close()).PumpingWait();
}
[Fact]
public void CallInsertCodeOnNonUIThread()
{
Task.Run(() => Window.InsertCode("1")).PumpingWait();
}
[Fact]
public void CallSubmitAsyncOnNonUIThread()
{
Task.Run(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).PumpingWait();
}
[Fact]
public void CallWriteOnNonUIThread()
{
Task.Run(() => Window.WriteLine("1")).PumpingWait();
Task.Run(() => Window.Write("1")).PumpingWait();
Task.Run(() => Window.WriteErrorLine("1")).PumpingWait();
Task.Run(() => Window.WriteError("1")).PumpingWait();
}
[Fact]
public void CallFlushOutputOnNonUIThread()
{
Window.Write("1"); // Something to flush.
Task.Run(() => Window.FlushOutput()).PumpingWait();
}
[Fact]
public void CallAddInputOnNonUIThread()
{
Task.Run(() => Window.AddInput("1")).PumpingWait();
}
/// <remarks>
/// Call is blocking, so we can't write a simple non-failing test.
/// </remarks>
[Fact]
public void CallReadStandardInputOnUIThread()
{
Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput());
}
[Fact]
public void CallBackspaceOnNonUIThread()
{
Window.InsertCode("1"); // Something to backspace.
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
}
[Fact]
public void CallBreakLineOnNonUIThread()
{
Task.Run(() => Window.Operations.BreakLine()).PumpingWait();
}
[Fact]
public void CallClearHistoryOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.ClearHistory()).PumpingWait();
}
[Fact]
public void CallClearViewOnNonUIThread()
{
Window.InsertCode("1"); // Something to clear.
Task.Run(() => Window.Operations.ClearView()).PumpingWait();
}
[Fact]
public void CallHistoryNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistoryNext()).PumpingWait();
}
[Fact]
public void CallHistoryPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistoryPrevious()).PumpingWait();
}
[Fact]
public void CallHistorySearchNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistorySearchNext()).PumpingWait();
}
[Fact]
public void CallHistorySearchPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
Task.Run(() => Window.Operations.HistorySearchPrevious()).PumpingWait();
}
[Fact]
public void CallHomeOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
Task.Run(() => Window.Operations.Home(true)).PumpingWait();
}
[Fact]
public void CallEndOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
Task.Run(() => Window.Operations.End(true)).PumpingWait();
}
[Fact]
public void ScrollToCursorOnHomeAndEndOnNonUIThread()
{
Window.InsertCode(new string('1', 512)); // a long input string
var textView = Window.TextView;
Window.Operations.Home(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
Window.Operations.End(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
}
[Fact]
public void CallSelectAllOnNonUIThread()
{
Window.InsertCode("1"); // Something to select.
Task.Run(() => Window.Operations.SelectAll()).PumpingWait();
}
[Fact]
public void CallPasteOnNonUIThread()
{
Task.Run(() => Window.Operations.Paste()).PumpingWait();
}
[Fact]
public void CallCutOnNonUIThread()
{
Task.Run(() => Window.Operations.Cut()).PumpingWait();
}
[Fact]
public void CallDeleteOnNonUIThread()
{
Task.Run(() => Window.Operations.Delete()).PumpingWait();
}
[Fact]
public void CallReturnOnNonUIThread()
{
Task.Run(() => Window.Operations.Return()).PumpingWait();
}
[Fact]
public void CallTrySubmitStandardInputOnNonUIThread()
{
Task.Run(() => Window.Operations.TrySubmitStandardInput()).PumpingWait();
}
[Fact]
public void CallResetAsyncOnNonUIThread()
{
Task.Run(() => Window.Operations.ResetAsync()).PumpingWait();
}
[Fact]
public void CallExecuteInputOnNonUIThread()
{
Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait();
}
[Fact]
public void CallCancelOnNonUIThread()
{
Task.Run(() => Window.Operations.Cancel()).PumpingWait();
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation1()
{
TestIndentation(indentSize: 1);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation2()
{
TestIndentation(indentSize: 2);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation3()
{
TestIndentation(indentSize: 3);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[Fact]
public void TestIndentation4()
{
TestIndentation(indentSize: 4);
}
private void TestIndentation(int indentSize)
{
const int promptWidth = 2;
_testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent(
promptWidth,
promptWidth + indentSize,
promptWidth
);
AssertCaretVirtualPosition(0, promptWidth);
Window.InsertCode("{");
AssertCaretVirtualPosition(0, promptWidth + 1);
Window.Operations.BreakLine();
AssertCaretVirtualPosition(1, promptWidth + indentSize);
Window.InsertCode("Console.WriteLine();");
Window.Operations.BreakLine();
AssertCaretVirtualPosition(2, promptWidth);
Window.InsertCode("}");
AssertCaretVirtualPosition(2, promptWidth + 1);
}
private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn)
{
ITextSnapshotLine actualLine;
int actualColumn;
Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn);
Assert.Equal(expectedLine, actualLine.LineNumber);
Assert.Equal(expectedColumn, actualColumn);
}
[Fact]
public void ResetCommandArgumentParsing_Success()
{
bool initialize;
Assert.True(ResetCommand.TryParseArguments("", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments(" ", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize));
Assert.False(initialize);
}
[Fact]
public void ResetCommandArgumentParsing_Failure()
{
bool initialize;
Assert.False(ResetCommand.TryParseArguments("a", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize));
Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize));
Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize));
}
[Fact]
public void ResetCommandNoConfigClassification()
{
Assert.Empty(ResetCommand.GetNoConfigPositions(""));
Assert.Empty(ResetCommand.GetNoConfigPositions("a"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig "));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig"));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig "));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n"));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n"));
Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig"));
Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig"));
Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig"));
}
[WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")]
[Fact]
public void ReformatBraces()
{
var buffer = Window.CurrentLanguageBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal(0, snapshot.Length);
// Text before reformatting.
snapshot = ApplyChanges(
buffer,
new TextChange(0, 0, "{ {\r\n } }"));
// Text after reformatting.
Assert.Equal(9, snapshot.Length);
snapshot = ApplyChanges(
buffer,
new TextChange(1, 1, "\r\n "),
new TextChange(5, 1, " "),
new TextChange(7, 1, "\r\n"));
// Text from language buffer.
var actualText = snapshot.GetText();
Assert.Equal("{\r\n {\r\n }\r\n}", actualText);
// Text including prompts.
buffer = Window.TextView.TextBuffer;
snapshot = buffer.CurrentSnapshot;
actualText = snapshot.GetText();
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText);
// Prompts should be read-only.
var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length));
AssertEx.SetEqual(regions,
new Span(0, 2),
new Span(5, 2),
new Span(14, 2),
new Span(23, 2));
}
[Fact]
public void CopyWithinInput()
{
_testClipboard.Clear();
Window.InsertCode("1 + 2");
Window.Operations.SelectAll();
Window.Operations.Copy();
VerifyClipboardData("1 + 2", "1 + 2", @"[{""content"":""1 + 2"",""kind"":2}]");
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 1, span.Length - 2), isReversed: false);
Window.Operations.Copy();
VerifyClipboardData(" + ", " + ", @"[{""content"":"" + "",""kind"":2}]");
}
[Fact]
public void CopyInputAndOutput()
{
_testClipboard.Clear();
Submit(
@"foreach (var o in new[] { 1, 2, 3 })
System.Console.WriteLine();",
@"1
2
3
");
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.Copy();
VerifyClipboardData(@"> foreach (var o in new[] { 1, 2, 3 })
> System.Console.WriteLine();
1
2
3
> ",
@"> foreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3\par > ",
@"[{""content"":""> "",""kind"":0},{""content"":""foreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":0},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3\u000d\u000a"",""kind"":1},{""content"":""> "",""kind"":0}]");
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false);
Window.Operations.Copy();
VerifyClipboardData(@"oreach (var o in new[] { 1, 2, 3 })
> System.Console.WriteLine();
1
2
3",
@"oreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3",
@"[{""content"":""oreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":0},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3"",""kind"":1}]");
}
[Fact]
public void CutWithinInput()
{
_testClipboard.Clear();
Window.InsertCode("foreach (var o in new[] { 1, 2, 3 })");
Window.Operations.BreakLine();
Window.InsertCode("System.Console.WriteLine();");
Window.Operations.BreakLine();
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false);
Window.Operations.Cut();
VerifyClipboardData(
@"each (var o in new[] { 1, 2, 3 })
System.Console.WriteLine()",
expectedRtf: null,
expectedRepl: null);
}
[Fact]
public void CutInputAndOutput()
{
_testClipboard.Clear();
Submit(
@"foreach (var o in new[] { 1, 2, 3 })
System.Console.WriteLine();",
@"1
2
3
");
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.Cut();
VerifyClipboardData(null, null, null);
}
/// <summary>
/// When there is no selection, copy
/// should copy the current line.
/// </summary>
[Fact]
public void CopyNoSelection()
{
Submit(
@"s +
t",
@" 1
2 ");
CopyNoSelectionAndVerify(0, 7, "> s +\r\n", @"> s +\par ", @"[{""content"":""> "",""kind"":0},{""content"":""s +\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(7, 11, "> \r\n", @"> \par ", @"[{""content"":""> "",""kind"":0},{""content"":""\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(11, 17, "> t\r\n", @"> t\par ", @"[{""content"":""> "",""kind"":0},{""content"":"" t\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(17, 21, " 1\r\n", @" 1\par ", @"[{""content"":"" 1\u000d\u000a"",""kind"":1}]");
CopyNoSelectionAndVerify(21, 23, "\r\n", @"\par ", @"[{""content"":""\u000d\u000a"",""kind"":1}]");
CopyNoSelectionAndVerify(23, 28, "2 > ", "2 > ", @"[{""content"":""2 "",""kind"":1},{""content"":""> "",""kind"":0}]");
}
private void CopyNoSelectionAndVerify(int start, int end, string expectedText, string expectedRtf, string expectedRepl)
{
var caret = Window.TextView.Caret;
var snapshot = Window.TextView.TextBuffer.CurrentSnapshot;
for (int i = start; i < end; i++)
{
_testClipboard.Clear();
caret.MoveTo(new SnapshotPoint(snapshot, i));
Window.Operations.Copy();
VerifyClipboardData(expectedText, expectedRtf, expectedRepl);
}
}
[Fact]
public void Paste()
{
var blocks = new[]
{
new BufferBlock(ReplSpanKind.Output, "a\r\nbc"),
new BufferBlock(ReplSpanKind.Prompt, "> "),
new BufferBlock(ReplSpanKind.Prompt, "< "),
new BufferBlock(ReplSpanKind.Input, "12"),
new BufferBlock(ReplSpanKind.StandardInput, "3"),
new BufferBlock((ReplSpanKind)10, "xyz")
};
// Paste from text clipboard format.
CopyToClipboard(blocks, includeRepl: false);
Window.Operations.Paste();
var text = Window.TextView.TextBuffer.CurrentSnapshot.GetText();
Assert.Equal("> a\r\n> bc> < 123xyz", text);
Window.Operations.ClearView();
text = Window.TextView.TextBuffer.CurrentSnapshot.GetText();
Assert.Equal("> ", text);
// Paste from custom clipboard format.
CopyToClipboard(blocks, includeRepl: true);
Window.Operations.Paste();
text = Window.TextView.TextBuffer.CurrentSnapshot.GetText();
Assert.Equal("> a\r\n> bc123", text);
}
private void CopyToClipboard(BufferBlock[] blocks, bool includeRepl)
{
_testClipboard.Clear();
var data = new DataObject();
var builder = new StringBuilder();
foreach (var block in blocks)
{
builder.Append(block.Content);
}
var text = builder.ToString();
data.SetData(DataFormats.UnicodeText, text);
data.SetData(DataFormats.StringFormat, text);
if (includeRepl)
{
data.SetData(InteractiveWindow.ClipboardFormat, BufferBlock.Serialize(blocks));
}
_testClipboard.SetDataObject(data, false);
}
[Fact]
public void JsonSerialization()
{
var expectedContent = new []
{
new BufferBlock(ReplSpanKind.Prompt, "> "),
new BufferBlock(ReplSpanKind.Input, "Hello"),
new BufferBlock(ReplSpanKind.Prompt, ". "),
new BufferBlock(ReplSpanKind.StandardInput, "world"),
new BufferBlock(ReplSpanKind.Output, "Hello world"),
};
var actualJson = BufferBlock.Serialize(expectedContent);
var expectedJson = @"[{""content"":""> "",""kind"":0},{""content"":""Hello"",""kind"":2},{""content"":"". "",""kind"":0},{""content"":""world"",""kind"":3},{""content"":""Hello world"",""kind"":1}]";
Assert.Equal(expectedJson, actualJson);
var actualContent = BufferBlock.Deserialize(actualJson);
Assert.Equal(expectedContent.Length, actualContent.Length);
for (int i = 0; i < expectedContent.Length; i++)
{
var expectedBuffer = expectedContent[i];
var actualBuffer = actualContent[i];
Assert.Equal(expectedBuffer.Kind, actualBuffer.Kind);
Assert.Equal(expectedBuffer.Content, actualBuffer.Content);
}
}
[Fact]
public void CancelMultiLineInput()
{
ApplyChanges(
Window.CurrentLanguageBuffer,
new TextChange(0, 0, "{\r\n {\r\n }\r\n}"));
// Text including prompts.
var buffer = Window.TextView.TextBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText());
Task.Run(() => Window.Operations.Cancel()).PumpingWait();
// Text after cancel.
snapshot = buffer.CurrentSnapshot;
Assert.Equal("> ", snapshot.GetText());
}
[Fact]
public void SelectAllInHeader()
{
Window.WriteLine("Header");
Window.FlushOutput();
var fullText = Window.TextView.TextBuffer.CurrentSnapshot.GetText();
Assert.Equal("Header\r\n> ", fullText);
Window.TextView.Caret.MoveTo(new SnapshotPoint(Window.TextView.TextBuffer.CurrentSnapshot, 1));
Window.Operations.SelectAll(); // Used to throw.
// Everything is selected.
Assert.Equal(new Span(0, fullText.Length), Window.TextView.Selection.SelectedSpans.Single().Span);
}
[Fact]
public void DeleteWithOutSelectionInReadOnlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("2");
var caret = Window.TextView.Caret;
// with empty selection, Delete() only handles caret movement,
// so we can only test caret location.
// Delete() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Task.Run(() => Window.Operations.Delete()).PumpingWait();
AssertCaretVirtualPosition(1, 1);
// Delete() with caret in active prompt, move caret to
// closest editable buffer
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Task.Run(() => Window.Operations.Delete()).PumpingWait();
AssertCaretVirtualPosition(2, 2);
}
[Fact]
public void DeleteWithSelectionInReadonlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Delete() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Task.Run(() => Window.Operations.Delete()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Delete() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Delete()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Delete() with selection overlaps with editable buffer,
// delete editable content and move caret to closest editable location
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
Task.Run(() => Window.Operations.Delete()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 2);
}
[Fact]
public void BackspaceWithOutSelectionInReadOnlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
// Backspace() with caret in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
AssertCaretVirtualPosition(1, 1);
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Backspace() with caret in 2nd active prompt, move caret to
// closest editable buffer then delete prvious characer (breakline)
caret.MoveToNextCaretPosition();
Window.Operations.End(false);
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(3, 1);
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
AssertCaretVirtualPosition(2, 7);
Assert.Equal("> 1\r\n1\r\n> int x;", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
}
[Fact]
public void BackspaceWithSelectionInReadonlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Backspace() with selection in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Backspace() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Backspace() with selection overlaps with editable buffer
selection.Clear();
Window.Operations.End(false);
start = caret.Position.VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(3, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Backspace()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> int x;", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 7);
}
[Fact]
public void ReturnWithOutSelectionInReadOnlyArea()
{
Submit(
@"1",
@"1
");
var caret = Window.TextView.Caret;
// Return() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Task.Run(() => Window.Operations.Return()).PumpingWait();
AssertCaretVirtualPosition(1, 1);
// Return() with caret in active prompt, move caret to
// closest editable buffer first
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Task.Run(() => Window.Operations.Return()).PumpingWait();
AssertCaretVirtualPosition(3, 2);
}
[Fact]
public void ReturnWithSelectionInReadonlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Return() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Task.Run(() => Window.Operations.Return()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Return() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Return()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Delete() with selection overlaps with editable buffer,
// delete editable content and move caret to closest editable location and insert a return
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
Task.Run(() => Window.Operations.Return()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> \r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(3, 2);
}
[Fact]
public void CutWithOutSelectionInReadOnlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("2");
var caret = Window.TextView.Caret;
_testClipboard.Clear();
// Cut() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Task.Run(() => Window.Operations.Cut()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 2", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(1, 1);
VerifyClipboardData(null, null, null);
// Cut() with caret in active prompt
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Task.Run(() => Window.Operations.Cut()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> ", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData("2", expectedRtf: null, expectedRepl: null);
}
[Fact]
public void CutWithSelectionInReadonlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
_testClipboard.Clear();
// Cut() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Task.Run(() => Window.Operations.Cut()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
VerifyClipboardData(null, null, null);
// Cut() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Cut()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
VerifyClipboardData(null, null, null);
// Cut() with selection overlaps with editable buffer,
// Cut editable content and move caret to closest editable location
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
Task.Run(() => Window.Operations.Cut()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData("2", expectedRtf: null, expectedRepl: null);
}
[Fact]
public void PasteWithOutSelectionInReadOnlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("2");
var caret = Window.TextView.Caret;
_testClipboard.Clear();
Window.Operations.Home(true);
Window.Operations.Copy();
VerifyClipboardData("2", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 2", @"[{""content"":""2"",""kind"":2}]");
// Paste() with caret in readonly area, no-op
Window.TextView.Selection.Clear();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Task.Run(() => Window.Operations.Paste()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 2", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(1, 1);
// Paste() with caret in active prompt
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
Task.Run(() => Window.Operations.Paste()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 22", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 3);
}
[Fact]
public void PasteWithSelectionInReadonlyArea()
{
Submit(
@"1",
@"1
");
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
_testClipboard.Clear();
Window.Operations.Home(true);
Window.Operations.Copy();
VerifyClipboardData("23", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 23", @"[{""content"":""23"",""kind"":2}]");
// Paste() with selection in readonly area, no-op
selection.Clear();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
Task.Run(() => Window.Operations.Paste()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Paste() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
Task.Run(() => Window.Operations.Paste()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
// Paste() with selection overlaps with editable buffer,
// Cut editable content, move caret to closest editable location and insert text
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
Task.Run(() => Window.Operations.Paste()).PumpingWait();
Assert.Equal("> 1\r\n1\r\n> 233", Window.TextView.TextBuffer.CurrentSnapshot.GetText());
AssertCaretVirtualPosition(2, 4);
}
private void Submit(string submission, string output)
{
Task.Run(() => Window.SubmitAsync(new[] { submission })).PumpingWait();
// TestInteractiveEngine.ExecuteCodeAsync() simply returns
// success rather than executing the submission, so add the
// expected output to the output buffer.
var buffer = Window.OutputBuffer;
using (var edit = buffer.CreateEdit())
{
edit.Replace(buffer.CurrentSnapshot.Length, 0, output);
edit.Apply();
}
}
private void VerifyClipboardData(string expectedText, string expectedRtf, string expectedRepl)
{
var data = _testClipboard.GetDataObject();
Assert.Equal(expectedText, data?.GetData(DataFormats.StringFormat));
Assert.Equal(expectedText, data?.GetData(DataFormats.Text));
Assert.Equal(expectedText, data?.GetData(DataFormats.UnicodeText));
Assert.Equal(expectedRepl, (string)data?.GetData(InteractiveWindow.ClipboardFormat));
var actualRtf = (string)data?.GetData(DataFormats.Rtf);
if (expectedRtf == null)
{
Assert.Null(actualRtf);
}
else
{
Assert.True(actualRtf.StartsWith(@"{\rtf"));
Assert.True(actualRtf.EndsWith(expectedRtf + "}"));
}
}
private struct TextChange
{
internal readonly int Start;
internal readonly int Length;
internal readonly string Text;
internal TextChange(int start, int length, string text)
{
Start = start;
Length = length;
Text = text;
}
}
private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Start, change.Length, change.Text);
}
return edit.Apply();
}
}
}
internal static class OperationsExtensions
{
internal static void Copy(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).Copy();
}
}
}
| |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BlockchainAnalysis
{
public class CoinJoinAnonScoreTests
{
[Fact]
public void BasicCalculation()
{
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participants, 1 is you, your anonset is 10.
Assert.Equal(10, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void Inheritance()
{
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 100) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participants, 1 is you, your anonset is 10 and you inherit 99 anonset,
// because you don't want to count yourself twice.
Assert.Equal(109, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void ChangeOutput()
{
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(6.2m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(5m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var active = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var change = tx.WalletOutputs.First(x => x.Amount == Money.Coins(5m));
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(10, active.HdPubKey.AnonymitySet);
Assert.Equal(1, change.HdPubKey.AnonymitySet);
}
[Fact]
public void ChangeOutputInheritance()
{
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(6.2m), 100) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(5m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var active = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var change = tx.WalletOutputs.First(x => x.Amount == Money.Coins(5m));
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(109, active.HdPubKey.AnonymitySet);
Assert.Equal(100, change.HdPubKey.AnonymitySet);
}
[Fact]
public void MultiDenomination()
{
// Multiple standard denomination outputs should be accounted separately.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersOutputs = new[] { 1, 1, 1, 2, 2 };
var tx = BitcoinFactory.CreateSmartTransaction(
9,
othersOutputs.Select(x => Money.Coins(x)),
new[] { (Money.Coins(3.2m), 1) },
new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(2m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var level1 = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var level2 = tx.WalletOutputs.First(x => x.Amount == Money.Coins(2m));
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(4, level1.HdPubKey.AnonymitySet);
Assert.Equal(3, level2.HdPubKey.AnonymitySet);
}
[Fact]
public void MultiDenominationInheritance()
{
// Multiple denominations inherit properly.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersOutputs = new[] { 1, 1, 1, 2, 2 };
var tx = BitcoinFactory.CreateSmartTransaction(
9,
othersOutputs.Select(x => Money.Coins(x)),
new[] { (Money.Coins(3.2m), 100) },
new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(2m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var level1 = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var level2 = tx.WalletOutputs.First(x => x.Amount == Money.Coins(2m));
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(103, level1.HdPubKey.AnonymitySet);
Assert.Equal(102, level2.HdPubKey.AnonymitySet);
}
[Fact]
public void SelfAnonsetSanityCheck()
{
// If we have multiple same denomination in the same CoinJoin, then our anonset would be total coins/our coins.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersOutputs = new[] { 1, 1, 1 };
var ownOutputs = new[] { 1, 1 };
var tx = BitcoinFactory.CreateSmartTransaction(
9,
othersOutputs.Select(x => Money.Coins(x)),
new[] { (Money.Coins(3.2m), 1) },
ownOutputs.Select(x => (Money.Coins(x), HdPubKey.DefaultHighAnonymitySet)));
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.All(tx.WalletOutputs, x => Assert.Equal(5 / 2, x.HdPubKey.AnonymitySet));
}
[Fact]
public void InputSanityCheck()
{
// Anonset can never be larger than the number of inputs.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(2, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(3, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void InputSanityBeforeSelfAnonsetSanityCheck()
{
// Input sanity check is executed before self anonset sanity check.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersOutputs = new[] { 1, 1, 1 };
var ownOutputs = new[] { 1, 1 };
var tx = BitcoinFactory.CreateSmartTransaction(
2,
othersOutputs.Select(x => Money.Coins(x)),
new[] { (Money.Coins(3.2m), 1) },
ownOutputs.Select(x => (Money.Coins(x), HdPubKey.DefaultHighAnonymitySet)));
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// The anonset calculation naively would be 5,
// but there's only 3 inputs so that limits our anonset to 3.
// After that we should get 3/2 because 2 out of 3 is ours.
// Finally we don't mess around with decimal precisions, so
// conservatively 3/2 = 1.
Assert.All(tx.WalletOutputs, x => Assert.Equal(1, x.HdPubKey.AnonymitySet));
}
[Fact]
public void InputMergePunishment()
{
// Input merging results in worse inherited anonset.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(
9,
Enumerable.Repeat(Money.Coins(1m), 9),
new[] { (Money.Coins(1.1m), 100), (Money.Coins(1.2m), 200), (Money.Coins(1.3m), 300), (Money.Coins(1.4m), 400) },
new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.All(tx.WalletInputs, x => Assert.True(x.HdPubKey.AnonymitySet < 100));
// 10 participants, 1 is you, your added anonset would be 10.
// Smallest input anonset is 100 so your anonset would be 109 normally, but 4 inputs are merged so it should be worse.
Assert.True(tx.WalletOutputs.First().HdPubKey.AnonymitySet < 109);
}
[Fact]
public void InputMergePunishmentNoInheritance()
{
// Input merging results in worse inherited anonset, but does not punish gains from output indistinguishability.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var tx = BitcoinFactory.CreateSmartTransaction(
9,
Enumerable.Repeat(Money.Coins(1m), 9),
new[] { (Money.Coins(1.1m), 1), (Money.Coins(1.2m), 1), (Money.Coins(1.3m), 1), (Money.Coins(1.4m), 1) },
new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.All(tx.WalletInputs, x => Assert.Equal(1, x.HdPubKey.AnonymitySet));
// 10 participants, 1 is you, your anonset would be 10 normally and now too:
Assert.Equal(10, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void InputMergeProportionalPunishment()
{
// Input merging more coins results in worse anonset.
// In this test tx1 consolidates less inputs than tx2.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersInputCount = 9;
var othersOutputs = Enumerable.Repeat(Money.Coins(1m), 9);
var ownInputs1 = new[] { (Money.Coins(1.1m), 100), (Money.Coins(1.2m), 200), (Money.Coins(1.3m), 300), (Money.Coins(1.4m), 400) };
var ownInputs2 = ownInputs1.Concat(new[] { (Money.Coins(1.5m), 100) });
var ownOutputs = new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) };
var tx1 = BitcoinFactory.CreateSmartTransaction(
othersInputCount,
othersOutputs,
ownInputs1,
ownOutputs);
var tx2 = BitcoinFactory.CreateSmartTransaction(
othersInputCount,
othersOutputs,
ownInputs2,
ownOutputs);
analyser.Analyze(tx1);
analyser.Analyze(tx2);
Assert.All(tx1.WalletInputs, x => Assert.All(tx2.WalletInputs, y => Assert.True(x.HdPubKey.AnonymitySet > y.HdPubKey.AnonymitySet)));
Assert.True(tx1.WalletOutputs.First().HdPubKey.AnonymitySet > tx2.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void InputMergePunishmentDependsOnCjSize()
{
// Input merging in larger coinjoin results in less punishmnent.
var analyser = ServiceFactory.CreateBlockchainAnalyzer();
var othersInputCount1 = 10;
var othersInputCount2 = 9;
var othersOutputs = Enumerable.Repeat(Money.Coins(1m), 9);
var ownInputs = new[] { (Money.Coins(1.1m), 100), (Money.Coins(1.2m), 200), (Money.Coins(1.3m), 300), (Money.Coins(1.4m), 400) };
var ownOutputs = new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) };
var tx1 = BitcoinFactory.CreateSmartTransaction(
othersInputCount1,
othersOutputs,
ownInputs,
ownOutputs);
var tx2 = BitcoinFactory.CreateSmartTransaction(
othersInputCount2,
othersOutputs,
ownInputs,
ownOutputs);
analyser.Analyze(tx1);
analyser.Analyze(tx2);
Assert.All(tx1.WalletInputs, x => Assert.All(tx2.WalletInputs, y => Assert.True(x.HdPubKey.AnonymitySet > y.HdPubKey.AnonymitySet)));
Assert.True(tx1.WalletOutputs.First().HdPubKey.AnonymitySet > tx2.WalletOutputs.First().HdPubKey.AnonymitySet);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.ComponentModel.Composition;
using QuantConnect.Api;
using QuantConnect.API;
namespace QuantConnect.Interfaces
{
/// <summary>
/// API for QuantConnect.com
/// </summary>
[InheritedExport(typeof(IApi))]
public interface IApi : IDisposable
{
/// <summary>
/// Initialize the control system
/// </summary>
void Initialize(int userId, string token, string dataFolder);
/// <summary>
/// Create a project with the specified name and language via QuantConnect.com API
/// </summary>
/// <param name="name">Project name</param>
/// <param name="language">Programming language to use</param>
/// <returns><see cref="ProjectResponse"/> that includes information about the newly created project</returns>
ProjectResponse CreateProject(string name, Language language);
/// <summary>
/// Read in a project from the QuantConnect.com API.
/// </summary>
/// <param name="projectId">Project id you own</param>
/// <returns><see cref="ProjectResponse"/> about a specific project</returns>
ProjectResponse ReadProject(int projectId);
/// <summary>
/// Add a file to a project
/// </summary>
/// <param name="projectId">The project to which the file should be added</param>
/// <param name="name">The name of the new file</param>
/// <param name="content">The content of the new file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes information about the newly created file</returns>
ProjectFilesResponse AddProjectFile(int projectId, string name, string content);
/// <summary>
/// Update the name of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="oldFileName">The current name of the file</param>
/// <param name="newFileName">The new name for the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
RestResponse UpdateProjectFileName(int projectId, string oldFileName, string newFileName);
/// <summary>
/// Update the contents of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file that should be updated</param>
/// <param name="newFileContents">The new contents of the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
RestResponse UpdateProjectFileContent(int projectId, string fileName, string newFileContents);
/// <summary>
/// Read a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the file information</returns>
ProjectFilesResponse ReadProjectFile(int projectId, string fileName);
/// <summary>
/// Read all files in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
ProjectFilesResponse ReadProjectFiles(int projectId);
/// <summary>
/// Delete a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="name">The name of the file that should be deleted</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
RestResponse DeleteProjectFile(int projectId, string name);
/// <summary>
/// Delete a specific project owned by the user from QuantConnect.com
/// </summary>
/// <param name="projectId">Project id we own and wish to delete</param>
/// <returns>RestResponse indicating success</returns>
RestResponse DeleteProject(int projectId);
/// <summary>
/// Read back a list of all projects on the account for a user.
/// </summary>
/// <returns>Container for list of projects</returns>
ProjectResponse ListProjects();
/// <summary>
/// Create a new compile job request for this project id.
/// </summary>
/// <param name="projectId">Project id we wish to compile.</param>
/// <returns>Compile object result</returns>
Compile CreateCompile(int projectId);
/// <summary>
/// Read a compile packet job result.
/// </summary>
/// <param name="projectId">Project id we sent for compile</param>
/// <param name="compileId">Compile id return from the creation request</param>
/// <returns>Compile object result</returns>
Compile ReadCompile(int projectId, string compileId);
/// <summary>
/// Create a new backtest from a specified projectId and compileId
/// </summary>
/// <param name="projectId"></param>
/// <param name="compileId"></param>
/// <param name="backtestName"></param>
/// <returns></returns>
Backtest CreateBacktest(int projectId, string compileId, string backtestName);
/// <summary>
/// Read out the full result of a specific backtest
/// </summary>
/// <param name="projectId">Project id for the backtest we'd like to read</param>
/// <param name="backtestId">Backtest id for the backtest we'd like to read</param>
/// <returns>Backtest result object</returns>
Backtest ReadBacktest(int projectId, string backtestId);
/// <summary>
/// Update the backtest name
/// </summary>
/// <param name="projectId">Project id to update</param>
/// <param name="backtestId">Backtest id to update</param>
/// <param name="backtestName">New backtest name to set</param>
/// <param name="backtestNote">Note attached to the backtest</param>
/// <returns>Rest response on success</returns>
RestResponse UpdateBacktest(int projectId, string backtestId, string backtestName = "", string backtestNote = "");
/// <summary>
/// Delete a backtest from the specified project and backtestId.
/// </summary>
/// <param name="projectId">Project for the backtest we want to delete</param>
/// <param name="backtestId">Backtest id we want to delete</param>
/// <returns>RestResponse on success</returns>
RestResponse DeleteBacktest(int projectId, string backtestId);
/// <summary>
/// Get a list of backtests for a specific project id
/// </summary>
/// <param name="projectId">Project id to search</param>
/// <returns>BacktestList container for list of backtests</returns>
BacktestList ListBacktests(int projectId);
/// <summary>
/// Gets the logs of a specific live algorithm
/// </summary>
/// <param name="projectId">Project Id of the live running algorithm</param>
/// <param name="algorithmId">Algorithm Id of the live running algorithm</param>
/// <param name="startTime">No logs will be returned before this time. Should be in UTC</param>
/// <param name="endTime">No logs will be returned after this time. Should be in UTC</param>
/// <returns>List of strings that represent the logs of the algorithm</returns>
LiveLog ReadLiveLogs(int projectId, string algorithmId, DateTime? startTime = null, DateTime? endTime = null);
/// <summary>
/// Gets the link to the downloadable data.
/// </summary>
/// <param name="symbol">Symbol of security of which data will be requested.</param>
/// <param name="resolution">Resolution of data requested.</param>
/// <param name="date">Date of the data requested.</param>
/// <returns>Link to the downloadable data.</returns>
Link ReadDataLink(Symbol symbol, Resolution resolution, DateTime date);
/// <summary>
/// Method to download and save the data purchased through QuantConnect
/// </summary>
/// <param name="symbol">Symbol of security of which data will be requested.</param>
/// <param name="resolution">Resolution of data requested.</param>
/// <param name="date">Date of the data requested.</param>
/// <returns>A bool indicating whether the data was successfully downloaded or not.</returns>
bool DownloadData(Symbol symbol, Resolution resolution, DateTime date);
/// <summary>
/// Create a new live algorithm for a logged in user.
/// </summary>
/// <param name="projectId">Id of the project on QuantConnect</param>
/// <param name="compileId">Id of the compilation on QuantConnect</param>
/// <param name="serverType">Type of server instance that will run the algorithm</param>
/// <param name="baseLiveAlgorithmSettings">Brokerage specific <see cref="BaseLiveAlgorithmSettings">BaseLiveAlgorithmSettings</see>.</param>
/// <returns>Information regarding the new algorithm <see cref="LiveAlgorithm"/></returns>
LiveAlgorithm CreateLiveAlgorithm(int projectId, string compileId, string serverType, BaseLiveAlgorithmSettings baseLiveAlgorithmSettings, string versionId = "-1");
/// <summary>
/// Get a list of live running algorithms for a logged in user.
/// </summary>
/// <param name="status">Filter the statuses of the algorithms returned from the api</param>
/// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param>
/// <param name="endTime">Latest launched time of the algorithms returned by the Api</param>
/// <returns>List of live algorithm instances</returns>
LiveList ListLiveAlgorithms(AlgorithmStatus? status = null, DateTime? startTime = null, DateTime? endTime = null);
/// <summary>
/// Read out a live algorithm in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="deployId">Specific instance id to read</param>
/// <returns>Live object with the results</returns>
LiveAlgorithmResults ReadLiveAlgorithm(int projectId, string deployId);
/// <summary>
/// Liquidate a live algorithm from the specified project.
/// </summary>
/// <param name="projectId">Project for the live instance we want to stop</param>
/// <returns></returns>
RestResponse LiquidateLiveAlgorithm(int projectId);
/// <summary>
/// Stop a live algorithm from the specified project.
/// </summary>
/// <param name="projectId">Project for the live algo we want to delete</param>
/// <returns></returns>
RestResponse StopLiveAlgorithm(int projectId);
//Status StatusRead(int projectId, string algorithmId);
//RestResponse StatusUpdate(int projectId, string algorithmId, AlgorithmStatus status, string message = "");
//LogControl LogAllowanceRead();
//void LogAllowanceUpdate(string backtestId, string url, int length);
//void StatisticsUpdate(int projectId, string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe);
//void NotifyOwner(int projectId, string algorithmId, string subject, string body);
//IEnumerable<MarketHoursSegment> MarketHours(int projectId, DateTime time, Symbol symbol);
/// <summary>
/// Get the algorithm current status, active or cancelled from the user
/// </summary>
/// <param name="algorithmId"></param>
/// <returns></returns>
AlgorithmControl GetAlgorithmStatus(string algorithmId);
/// <summary>
/// Set the algorithm status from the worker to update the UX e.g. if there was an error.
/// </summary>
/// <param name="algorithmId">Algorithm id we're setting.</param>
/// <param name="status">Status enum of the current worker</param>
/// <param name="message">Message for the algorithm status event</param>
void SetAlgorithmStatus(string algorithmId, AlgorithmStatus status, string message = "");
/// <summary>
/// Send the statistics to storage for performance tracking.
/// </summary>
/// <param name="algorithmId">Identifier for algorithm</param>
/// <param name="unrealized">Unrealized gainloss</param>
/// <param name="fees">Total fees</param>
/// <param name="netProfit">Net profi</param>
/// <param name="holdings">Algorithm holdings</param>
/// <param name="equity">Total equity</param>
/// <param name="netReturn">Algorithm return</param>
/// <param name="volume">Volume traded</param>
/// <param name="trades">Total trades since inception</param>
/// <param name="sharpe">Sharpe ratio since inception</param>
void SendStatistics(string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe);
/// <summary>
/// Send an email to the user associated with the specified algorithm id
/// </summary>
/// <param name="algorithmId">The algorithm id</param>
/// <param name="subject">The email subject</param>
/// <param name="body">The email message body</param>
void SendUserEmail(string algorithmId, string subject, string body);
}
}
| |
/*
* 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 Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using System;
using System.Collections.Generic;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.World.Objects.BuySell
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BuySellModule")]
public class BuySellModule : IBuySellModule, INonSharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IDialogModule m_dialogModule;
protected Scene m_scene = null;
public string Name { get { return "Object BuySell Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IBuySellModule>(this);
m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
}
public bool BuyObject(IClientAPI remoteClient, UUID categoryID, uint localID, byte saleType, int salePrice)
{
SceneObjectPart part = m_scene.GetSceneObjectPart(localID);
if (part == null)
return false;
SceneObjectGroup group = part.ParentGroup;
switch (saleType)
{
case 1: // Sell as original (in-place sale)
uint effectivePerms = group.GetEffectivePermissions();
if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
{
if (m_dialogModule != null)
m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
return false;
}
group.SetOwnerId(remoteClient.AgentId);
group.SetRootPartOwner(part, remoteClient.AgentId, remoteClient.ActiveGroupId);
if (m_scene.Permissions.PropagatePermissions())
{
foreach (SceneObjectPart child in group.Parts)
{
child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
child.TriggerScriptChangedEvent(Changed.OWNER);
child.ApplyNextOwnerPermissions();
}
}
part.ObjectSaleType = 0;
part.SalePrice = 10;
group.HasGroupChanged = true;
part.SendPropertiesToClient(remoteClient);
part.TriggerScriptChangedEvent(Changed.OWNER);
group.ResumeScripts();
part.ScheduleFullUpdate();
break;
case 2: // Sell a copy
Vector3 inventoryStoredPosition = new Vector3(
Math.Min(group.AbsolutePosition.X, m_scene.RegionInfo.RegionSizeX - 6),
Math.Min(group.AbsolutePosition.Y, m_scene.RegionInfo.RegionSizeY - 6),
group.AbsolutePosition.Z);
Vector3 originalPosition = group.AbsolutePosition;
group.AbsolutePosition = inventoryStoredPosition;
string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
group.AbsolutePosition = originalPosition;
uint perms = group.GetEffectivePermissions();
if ((perms & (uint)PermissionMask.Transfer) == 0)
{
if (m_dialogModule != null)
m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
return false;
}
AssetBase asset = m_scene.CreateAsset(
group.GetPartName(localID),
group.GetPartDescription(localID),
(sbyte)AssetType.Object,
Utils.StringToBytes(sceneObjectXml),
group.OwnerID);
m_scene.AssetService.Store(asset);
InventoryItemBase item = new InventoryItemBase();
item.CreatorId = part.CreatorID.ToString();
item.CreatorData = part.CreatorData;
item.ID = UUID.Random();
item.Owner = remoteClient.AgentId;
item.AssetID = asset.FullID;
item.Description = asset.Description;
item.Name = asset.Name;
item.AssetType = asset.Type;
item.InvType = (int)InventoryType.Object;
item.Folder = categoryID;
PermissionsUtil.ApplyFoldedPermissions(perms, ref perms);
item.BasePermissions = perms & part.NextOwnerMask;
item.CurrentPermissions = perms & part.NextOwnerMask;
item.NextPermissions = part.NextOwnerMask;
item.EveryOnePermissions = part.EveryoneMask &
part.NextOwnerMask;
item.GroupPermissions = part.GroupMask &
part.NextOwnerMask;
item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
item.CreationDate = Util.UnixTimeSinceEpoch();
if (m_scene.AddInventoryItem(item))
{
remoteClient.SendInventoryItemCreateUpdate(item, 0);
}
else
{
if (m_dialogModule != null)
m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
return false;
}
break;
case 3: // Sell contents
List<UUID> invList = part.Inventory.GetInventoryList();
bool okToSell = true;
foreach (UUID invID in invList)
{
TaskInventoryItem item1 = part.Inventory.GetInventoryItem(invID);
if ((item1.CurrentPermissions &
(uint)PermissionMask.Transfer) == 0)
{
okToSell = false;
break;
}
}
if (!okToSell)
{
if (m_dialogModule != null)
m_dialogModule.SendAlertToUser(
remoteClient, "This item's inventory doesn't appear to be for sale");
return false;
}
if (invList.Count > 0)
m_scene.MoveTaskInventoryItems(remoteClient.AgentId, part.Name, part, invList);
break;
}
return true;
}
public void Close()
{
RemoveRegion(m_scene);
}
public void Initialise(IConfigSource source)
{
}
public void RegionLoaded(Scene scene)
{
m_dialogModule = scene.RequestModuleInterface<IDialogModule>();
}
public void RemoveRegion(Scene scene)
{
m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
}
public void SubscribeToClientEvents(IClientAPI client)
{
client.OnObjectSaleInfo += ObjectSaleInfo;
}
protected void ObjectSaleInfo(
IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
{
SceneObjectPart part = m_scene.GetSceneObjectPart(localID);
if (part == null)
return;
if (part.ParentGroup.IsDeleted)
return;
if (part.OwnerID != client.AgentId && (!m_scene.Permissions.IsGod(client.AgentId)))
return;
part = part.ParentGroup.RootPart;
part.ObjectSaleType = saleType;
part.SalePrice = salePrice;
part.ParentGroup.HasGroupChanged = true;
part.SendPropertiesToClient(client);
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections.Generic;
namespace JinxNeuralNetwork
{
//neural network class
/// <summary>
/// Neural network.
/// </summary>
public class NeuralNetwork
{
public NeuralNetworkLayer inputLayer;
public NeuralNetworkLayer outputLayer;
public NeuralNetworkLayer[] hiddenLayers;
public NeuralNetworkLayerConnection outputConnection;
public NeuralNetworkLayerConnection[] hiddenConnections, hiddenRecurringConnections;
public int maxNumberOfHiddenNeurons, maxNumberOfSynapses;
/// <summary>
/// Create new NeuralNetwork from existing(src).
/// </summary>
/// <param name="src">Existing NeuralNetwork to copy.</param>
public NeuralNetwork(NeuralNetwork src)
{
inputLayer = new NeuralNetworkLayer(src.inputLayer);
hiddenLayers = new NeuralNetworkLayer[src.hiddenLayers.Length];
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i] = new NeuralNetworkLayer(src.hiddenLayers[i]);
hiddenLayers[i].Init();
}
outputLayer = new NeuralNetworkLayer(src.outputLayer);
outputLayer.Init();
//setup layer connections
if (hiddenLayers.Length > 0)
{
//hidden layer connections
hiddenConnections = new NeuralNetworkLayerConnection[hiddenLayers.Length];
hiddenRecurringConnections = new NeuralNetworkLayerConnection[hiddenLayers.Length];
maxNumberOfHiddenNeurons = 0;
maxNumberOfSynapses = 0;
for (int i = 0; i < hiddenLayers.Length; i++)
{
if (i == 0) hiddenConnections[0] = new NeuralNetworkLayerConnection(inputLayer, hiddenLayers[0]);
else hiddenConnections[i] = new NeuralNetworkLayerConnection(hiddenLayers[i - 1], hiddenLayers[i]);
//recurrent connection for hidden layer
if (hiddenLayers[i].recurring)
{
hiddenRecurringConnections[i] = new NeuralNetworkLayerConnection(hiddenLayers[i], hiddenLayers[i]);
}
else
{
hiddenRecurringConnections[i] = null;
}
//calc max hidden neurons
if (hiddenLayers[i].numberOfNeurons > maxNumberOfHiddenNeurons)
{
maxNumberOfHiddenNeurons = hiddenLayers[i].numberOfNeurons;
}
if (hiddenConnections[i].numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = hiddenConnections[i].numberOfSynapses;
}
//output connection
outputConnection = new NeuralNetworkLayerConnection(hiddenLayers[hiddenLayers.Length - 1], outputLayer);
if (outputConnection.numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = outputConnection.numberOfSynapses;
}
else
{
maxNumberOfHiddenNeurons = 0;
maxNumberOfSynapses = 0;
//direct input to output connection
outputConnection = new NeuralNetworkLayerConnection(inputLayer, outputLayer);
if (outputConnection.numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = outputConnection.numberOfSynapses;
}
}
/// <summary>
/// Create new NeuralNetwork.
/// </summary>
/// <param name="input"></param>
/// <param name="hidden"></param>
/// <param name="output"></param>
public NeuralNetwork(NeuralNetworkLayer input, NeuralNetworkLayer[] hidden, NeuralNetworkLayer output)
{
inputLayer = input;
hiddenLayers = hidden;
outputLayer = output;
outputLayer.Init();
//setup layer connections
if (hidden.Length > 0)
{
//hidden layer connections
hiddenConnections = new NeuralNetworkLayerConnection[hidden.Length];
hiddenRecurringConnections = new NeuralNetworkLayerConnection[hidden.Length];
maxNumberOfHiddenNeurons = 0;
maxNumberOfSynapses = 0;
for (int i = 0; i < hidden.Length; i++)
{
if (i == 0) hiddenConnections[0] = new NeuralNetworkLayerConnection(input, hidden[0]);
else hiddenConnections[i] = new NeuralNetworkLayerConnection(hidden[i - 1], hidden[i]);
hiddenLayers[i].Init();
//recurrent connection for hidden layer
if (hidden[i].recurring)
{
hiddenRecurringConnections[i] = new NeuralNetworkLayerConnection(hidden[i], hidden[i]);
}
else
{
hiddenRecurringConnections[i] = null;
}
//calc max hidden neurons
if (hidden[i].numberOfNeurons > maxNumberOfHiddenNeurons)
{
maxNumberOfHiddenNeurons = hidden[i].numberOfNeurons;
}
if (hiddenConnections[i].numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = hiddenConnections[i].numberOfSynapses;
}
//output connection
outputConnection = new NeuralNetworkLayerConnection(hidden[hidden.Length - 1], output);
if (outputConnection.numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = outputConnection.numberOfSynapses;
}
else
{
maxNumberOfHiddenNeurons = 0;
maxNumberOfSynapses = 0;
//direct input to output connection
outputConnection = new NeuralNetworkLayerConnection(input, output);
if (outputConnection.numberOfSynapses > maxNumberOfSynapses) maxNumberOfSynapses = outputConnection.numberOfSynapses;
}
}
//execute neural network
/// <summary>
/// Execute NeuralNetwork.
/// </summary>
/// <param name="context">Execution memory.</param>
public void Execute(NeuralNetworkContext context)
{
float[] input = context.inputData,
output = context.outputData,
hidden = context.hiddenData;
float[][] hiddenRecurring = context.hiddenRecurringData;
int i, weightIndex, recurringWeightIndex;
NeuronActivationFunction activeFunc;
if (hiddenLayers.Length > 0)
{
int lastNumNeurons = 0;
float[] weights, biases, recurringWeights;
for (i = 0; i < hiddenLayers.Length; i++)
{
weights = hiddenConnections[i].weights;
biases = hiddenLayers[i].biases;
activeFunc = hiddenLayers[i].activationFunction;
float[] ina;
int alen;
if (i == 0)
{
ina = input;
alen = input.Length;
}
else
{
ina = hidden;
alen = lastNumNeurons;
}
if (hiddenLayers[i].recurring)
{
//recurring hidden layer
recurringWeights = hiddenRecurringConnections[i].weights;
weightIndex = 0;
recurringWeightIndex = 0;
float[] hrec = hiddenRecurring[i];
int k = biases.Length;
while (k-- > 0)
{
float ov = biases[k];
int j = alen;
while (j-- > 0)
{
ov += ina[j] * weights[weightIndex++];
}
j = hrec.Length;
while (j-- > 0)
{
ov += hrec[j] * recurringWeights[recurringWeightIndex++];
}
hidden[k] = activeFunc(ov);
}
Array.Copy(hidden, hrec, biases.Length);
}
else
{
//non recurring hidden layer
weightIndex = 0;
int k = biases.Length;
while (k-- > 0)
{
float ov = biases[k];
int j = alen;
while (j-- > 0)
{
ov += ina[j] * weights[weightIndex++];
}
hidden[k] = activeFunc(ov);
}
}
lastNumNeurons = biases.Length;
}
activeFunc = outputLayer.activationFunction;
//last output layer
//run input to output layer connection
weights = outputConnection.weights;
biases = outputLayer.biases;
weightIndex = 0;
recurringWeightIndex = 0;
i = output.Length;
while (i-- > 0)
{
float ov = biases[i];
//input connections
int k = lastNumNeurons;
while (k-- > 0)
{
ov += hidden[k] * weights[weightIndex++];
}
output[i] = activeFunc(ov);
}
}
else
{
activeFunc = outputLayer.activationFunction;
//run input to output layer connection with recurring output
float[] weights = outputConnection.weights,
biases = outputLayer.biases;
weightIndex = 0;
recurringWeightIndex = 0;
i = output.Length;
while (i-- > 0)
{
float ov = biases[i];
//input connections
int k = input.Length;
while (k-- > 0)
{
ov += input[k] * weights[weightIndex++];
}
output[i] = activeFunc(ov);
}
}
}
//execute neural network and save all calculation results in fullContext for adagrad
/// <summary>
/// Execute neural network and save all calculation results in fullContext for adagrad
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <param name="fullContext"></param>
public void Execute_FullContext(NeuralNetworkContext context, NeuralNetworkFullContext fullContext)
{
float[] input = context.inputData,
output = context.outputData,
hidden = context.hiddenData;
float[][] hiddenRecurring = context.hiddenRecurringData;
int i, weightIndex, recurringWeightIndex;
NeuronActivationFunction activeFunc;
if (hiddenLayers.Length > 0)
{
int lastNumNeurons = 0;
float[] weights, biases, recurringWeights;
for (i = 0; i < hiddenLayers.Length; i++)
{
weights = hiddenConnections[i].weights;
biases = hiddenLayers[i].biases;
activeFunc = hiddenLayers[i].activationFunction;
float[] ina;
int alen;
if (i == 0)
{
ina = input;
alen = input.Length;
}
else
{
ina = hidden;
alen = lastNumNeurons;
}
if (hiddenLayers[i].recurring)
{
//recurring hidden layer
float[] hrec = hiddenRecurring[i];
recurringWeights = hiddenRecurringConnections[i].weights;
//copy over data needed for training
Array.Copy(hrec, fullContext.hiddenRecurringBuffer[i], hrec.Length);
weightIndex = 0;
recurringWeightIndex = 0;
int k = biases.Length;
while (k-- > 0)
{
float ov = biases[k];
int j = alen;
while (j-- > 0)
{
ov += ina[j] * weights[weightIndex++];
}
j = hrec.Length;
while (j-- > 0)
{
ov += hrec[j] * recurringWeights[recurringWeightIndex++];
}
hidden[k] = activeFunc(ov);
}
Array.Copy(hidden, hrec, biases.Length);
}
else
{
//non recurring hidden layer
weightIndex = 0;
int k = biases.Length;
while (k-- > 0)
{
float ov = biases[k];
int j = alen;
while (j-- > 0)
{
ov += ina[j] * weights[weightIndex++];
}
hidden[k] = activeFunc(ov);
}
}
Array.Copy(hidden, fullContext.hiddenBuffer[i], biases.Length);
lastNumNeurons = biases.Length;
}
activeFunc = outputLayer.activationFunction;
//last output layer
//run input to output layer connection
weights = outputConnection.weights;
biases = outputLayer.biases;
weightIndex = 0;
recurringWeightIndex = 0;
i = output.Length;
while (i-- > 0)
{
float ov = biases[i];
//input connections
int k = lastNumNeurons;
while (k-- > 0)
{
ov += hidden[k] * weights[weightIndex++];
}
output[i] = activeFunc(ov);
}
}
else
{
activeFunc = outputLayer.activationFunction;
//run input to output layer connection with recurring output
float[] weights = outputConnection.weights,
biases = outputLayer.biases;
weightIndex = 0;
recurringWeightIndex = 0;
i = output.Length;
while (i-- > 0)
{
float ov = biases[i];
//input connections
int k = input.Length;
while (k-- > 0)
{
ov += input[k] * weights[weightIndex++];
}
output[i] = activeFunc(ov);
}
}
}
/// <summary>
/// Run neural network backwards calculating derivatives to use for adagrad or generation.
/// </summary>
/// <param name="target"></param>
/// <param name="context"></param>
/// <param name="fullContext"></param>
/// <param name="derivMem"></param>
public void ExecuteBackwards(float[] target, NeuralNetworkContext context, NeuralNetworkFullContext fullContext, NeuralNetworkPropagationState propState, int lossType, int crossEntropyTarget)
{
//prepare for back propagation
for (int i = 0; i < propState.state.Length; i++) {
Utils.Fill(propState.state[i], 0.0f);
}
//back propagation + calculate max loss
int lid = hiddenLayers.Length;
float lossAvg = 0.0f;
for (int i = 0; i < target.Length; i++)
{
float deriv = context.outputData[i] - target[i];
if (lossType == NeuralNetworkTrainer.LOSS_TYPE_MAX)
{
float aderiv = Math.Abs(deriv);
if (aderiv > lossAvg) lossAvg = aderiv;
}
else if (lossType == NeuralNetworkTrainer.LOSS_TYPE_AVERAGE)
{
lossAvg += Math.Abs(deriv);
}
backpropagate(lid, i, deriv, propState);
}
if (lossType == NeuralNetworkTrainer.LOSS_TYPE_AVERAGE)
{
lossAvg /= (float)target.Length;
}
else
{
if (lossType == NeuralNetworkTrainer.LOSS_TYPE_CROSSENTROPY && crossEntropyTarget != -1)
{
lossAvg = (float)-Math.Log(context.outputData[crossEntropyTarget]);
if (float.IsInfinity(lossAvg))
{
lossAvg = 1e8f;
}
}
}
propState.loss = lossAvg;
propState.derivativeMemory.SwapBPBuffers();
int k = lid;
while (k-- > 0)
{
int l = hiddenLayers[k].numberOfNeurons;
while (l-- > 0)
{
backpropagate(k, l, propState.state[k][l], propState);
}
}
}
private void backpropagate(int level, int index, float deriv, NeuralNetworkPropagationState propState)
{
if (level < 0) return;
int i, weightIndex;
float[] b, m, w;
//recurring weights
if (level < propState.recurrWeightMems.Length && propState.recurrWeightMems[level] != null)
{
b = propState.recurrBuf[level];
m = propState.recurrWeightMems[level];
w = propState.recurrWeights[level];
i = b.Length;
weightIndex = w.Length - (index + 1) * i;
float nhderiv = 0.0f;
while (i-- > 0)
{
m[weightIndex] += deriv * b[i];
nhderiv += deriv * w[weightIndex];
weightIndex++;
}
#pragma warning disable 414,1718
if (nhderiv != nhderiv || float.IsInfinity(nhderiv))
{
nhderiv = 0.0f;
}
#pragma warning restore 1718
propState.derivativeMemory.altRecurringBPBuffer[level][index] = nhderiv;
}
float[] bpb = null;
//biases and weights
b = propState.buf[level];
m = propState.weightMems[level];
w = propState.weights[level];
bpb = null;
if (level != 0) bpb = propState.derivativeMemory.recurringBPBuffer[level - 1];
propState.biasMems[level][index] += deriv;
i = b.Length;
weightIndex = w.Length - (index + 1) * i;
while (i-- > 0)
{
float nderiv = b[i];
m[weightIndex] += deriv * nderiv;
if (level != 0)
{
nderiv *= nderiv;
float bpropderiv = 0.0f;
if (bpb != null)
{
bpropderiv = bpb[i];
}
propState.state[level - 1][i] += (1.0f - nderiv) * (deriv * w[weightIndex] + bpropderiv);
}
else
{
if (propState.inputMem != null)
{
nderiv *= nderiv;
float bpropderiv = 0.0f;
if (bpb != null)
{
bpropderiv = bpb[i];
}
nderiv = (1.0f - nderiv) * (deriv * w[weightIndex] + bpropderiv);
propState.inputMem[i] += nderiv;
}
}
weightIndex++;
}
}
//breed data with partner
//partPartner is a value from 0 - 1 indicating the % of data to take from partner, 0 being no data and 1 being 100% partner data
/// <summary>
/// Breed weights/biases with partner.
/// </summary>
/// <param name="partner"></param>
public void Breed(NeuralNetwork partner)
{
outputLayer.Breed(partner.outputLayer);
outputConnection.Breed(partner.outputConnection);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].Breed(partner.hiddenLayers[i]);
hiddenConnections[i].Breed(partner.hiddenConnections[i]);
if (hiddenLayers[i].recurring) hiddenRecurringConnections[i].Breed(partner.hiddenRecurringConnections[i]);
}
}
//mutate weights and biases
/// <summary>
/// Mutate weights and biases.
/// </summary>
/// <param name="selectionChance">Chance(0-1) of a weight/bias being mutated.</param>
public void Mutate(float selectionChance)
{
outputLayer.Mutate(selectionChance);
outputConnection.Mutate(selectionChance);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].Mutate(selectionChance);
hiddenConnections[i].Mutate(selectionChance);
if (hiddenLayers[i].recurring) hiddenRecurringConnections[i].Mutate(selectionChance);
}
}
/// <summary>
/// Randomize weights and biases specifically for adagrad.
/// </summary>
public void RandomizeWeightsAndBiasesForAdagrad()
{
NeuralNetworkLayer.MIN_BIAS = 0.0f;
NeuralNetworkLayer.MAX_BIAS = 0.0f;
NeuralNetworkLayerConnection.MIN_WEIGHT = 0.0f;
NeuralNetworkLayerConnection.MAX_WEIGHT = 1.0f / maxNumberOfHiddenNeurons;
RandomizeWeightsAndBiases();
}
//randomize weights and biases of layers and connections
/// <summary>
/// Randomize all weights/biases.
/// </summary>
public void RandomizeWeightsAndBiases()
{
outputLayer.RandomizeBiases();
outputConnection.RandomizeWeights();
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].RandomizeBiases();
hiddenConnections[i].RandomizeWeights();
if (hiddenLayers[i].recurring) hiddenRecurringConnections[i].RandomizeWeights();
}
}
/// <summary>
/// Randomize all weights and biases between specified min/max values.
/// </summary>
public void RandomizeWeightsAndBiases(float minBias, float maxBias, float minWeight, float maxWeight)
{
NeuralNetworkLayer.MIN_BIAS = minBias;
NeuralNetworkLayer.MAX_BIAS = maxBias;
NeuralNetworkLayerConnection.MIN_WEIGHT = minWeight;
NeuralNetworkLayerConnection.MAX_WEIGHT = maxWeight;
outputLayer.RandomizeBiases();
outputConnection.RandomizeWeights();
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].RandomizeBiases();
hiddenConnections[i].RandomizeWeights();
if (hiddenLayers[i].recurring) hiddenRecurringConnections[i].RandomizeWeights();
}
}
//copy weights and biases from another neural network
/// <summary>
/// Copy weights and biases from another NeuralNetwork(nn).
/// </summary>
/// <param name="nn"></param>
public void CopyWeightsAndBiases(NeuralNetwork nn)
{
outputLayer.CopyBiases(nn.outputLayer);
outputConnection.CopyWeights(nn.outputConnection);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].CopyBiases(nn.hiddenLayers[i]);
hiddenConnections[i].CopyWeights(nn.hiddenConnections[i]);
if (hiddenLayers[i].recurring) hiddenRecurringConnections[i].CopyWeights(nn.hiddenRecurringConnections[i]);
}
}
/// <summary>
/// Setup data arrays for execution.
/// </summary>
/// <param name="ina"></param>
/// <param name="outa"></param>
/// <param name="hiddena"></param>
/// <param name="hiddenRecurra"></param>
public void SetupExecutionArrays(out float[] ina, out float[] outa, out float[] hiddena, out float[][] hiddenRecurra)
{
ina = new float[inputLayer.numberOfNeurons];
outa = new float[outputLayer.numberOfNeurons];
hiddena = new float[maxNumberOfHiddenNeurons];
hiddenRecurra = new float[hiddenLayers.Length][];
for (int i = 0; i < hiddenLayers.Length; i++)
{
if (hiddenLayers[i].recurring)
{
hiddenRecurra[i] = new float[hiddenLayers[i].numberOfNeurons];
}
}
}
/// <summary>
/// Save structure of NeuralNetwork layers to stream.
/// </summary>
/// <param name="s"></param>
public void SaveStructure(Stream s)
{
inputLayer.SaveStructure(s);
Utils.IntToStream(hiddenLayers.Length, s);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].SaveStructure(s);
}
outputLayer.SaveStructure(s);
}
/// <summary>
/// Load NeuralNetwork structure from stream.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static NeuralNetwork LoadStructure(Stream s)
{
NeuralNetworkLayer inLayer = new NeuralNetworkLayer();
inLayer.LoadStructure(s);
NeuralNetworkLayer[] hidden = new NeuralNetworkLayer[Utils.IntFromStream(s)];
for (int i = 0; i < hidden.Length; i++)
{
hidden[i] = new NeuralNetworkLayer();
hidden[i].LoadStructure(s);
}
NeuralNetworkLayer outLayer = new NeuralNetworkLayer();
outLayer.LoadStructure(s);
return new NeuralNetwork(inLayer, hidden, outLayer);
}
//save data to stream
/// <summary>
/// Save NeuralNetwork data(weights/biases, no structure data like input/hidden/output) to stream.
/// </summary>
/// <param name="s"></param>
public void Save(Stream s)
{
outputLayer.Save(s);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].Save(s);
}
outputConnection.Save(s);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenConnections[i].Save(s);
if (hiddenLayers[i].recurring)
{
hiddenRecurringConnections[i].Save(s);
}
}
}
//load data from stream
/// <summary>
/// Load NeuralNetwork from stream(s).
/// </summary>
/// <param name="s"></param>
public void Load(Stream s)
{
outputLayer.Load(s);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenLayers[i].Load(s);
}
outputConnection.Load(s);
for (int i = 0; i < hiddenLayers.Length; i++)
{
hiddenConnections[i].Load(s);
if (hiddenLayers[i].recurring)
{
hiddenRecurringConnections[i].Load(s);
}
}
}
//get total number of neurons in network
/// <summary>
/// Get total number of neurons in network.
/// </summary>
/// <returns></returns>
public int TotalNumberOfNeurons()
{
int nneurons = inputLayer.numberOfNeurons + outputLayer.numberOfNeurons;
for (int i = 0; i < hiddenLayers.Length; i++)
{
nneurons += hiddenLayers[i].numberOfNeurons;
}
return nneurons;
}
//get total number of synapses in network
/// <summary>
/// Get total number of synapses in network.
/// </summary>
/// <returns></returns>
public int TotalNumberOfSynapses()
{
int nsynapses = outputConnection.numberOfSynapses;
if (hiddenConnections != null)
{
for (int i = 0; i < hiddenConnections.Length; i++)
{
nsynapses += hiddenConnections[i].numberOfSynapses;
if (hiddenLayers[i].recurring) nsynapses += hiddenRecurringConnections[i].numberOfSynapses;
}
}
return nsynapses;
}
public int NumberOfLayers()
{
return hiddenLayers.Length + 1;
}
public NeuralNetworkLayer GetLayer(int i)
{
if (i < hiddenLayers.Length) return hiddenLayers[i];
return outputLayer;
}
public NeuralNetworkLayerConnection GetConnection(int i)
{
if (i < hiddenLayers.Length) return hiddenConnections[i];
return outputConnection;
}
public NeuralNetworkLayerConnection GetRecurringConnection(int i)
{
if (i < hiddenLayers.Length) return hiddenRecurringConnections[i];
return null;
}
public delegate float NeuronActivationFunction(float v);
}
/// <summary>
/// Neural network layer.
/// </summary>
public class NeuralNetworkLayer
{
/// <summary>
/// Minimum bias when randomly generating biases.
/// </summary>
public static float MIN_BIAS = 0.0f;
/// <summary>
/// Maximum bias when randomly generating biases.
/// </summary>
public static float MAX_BIAS = 0.0f;
/// <summary>
/// Number of neurons in layer.
/// </summary>
public int numberOfNeurons;
/// <summary>
/// Flag indicating whether or not neurons are recurring(last state is fed back in as input).
/// </summary>
public bool recurring;
/// <summary>
/// Array of biases.
/// </summary>
public float[] biases;
/// <summary>
/// Neuron activation function to use for all neurons in layer.
/// </summary>
public NeuralNetwork.NeuronActivationFunction activationFunction;
/// <summary>
/// Create new struct from existing.
/// </summary>
/// <param name="src">Existing layer to copy.</param>
public NeuralNetworkLayer(NeuralNetworkLayer src)
{
numberOfNeurons = src.numberOfNeurons;
recurring = src.recurring;
activationFunction = src.activationFunction;
biases = null;
}
/// <summary>
/// Create new struct.
/// </summary>
/// <param name="numNeurons">Number of neurons in layer.</param>
/// <param name="recurrin">Are neurons in layer recurring.</param>
/// <param name="activeFunc">Neuron activation function.</param>
public NeuralNetworkLayer(int numNeurons, bool recurrin, NeuralNetwork.NeuronActivationFunction activeFunc)
{
numberOfNeurons = numNeurons;
recurring = recurrin;
activationFunction = activeFunc;
biases = null;
}
public NeuralNetworkLayer(){}
/// <summary>
/// Allocate biases float array.
/// </summary>
public void Init()
{
biases = new float[numberOfNeurons];
}
public void SaveStructure(Stream s)
{
Utils.IntToStream(numberOfNeurons, s);
s.WriteByte(recurring ? (byte)1 : (byte)0);
Utils.IntToStream(Utils.GetActivationFunctionID(activationFunction), s);
}
public void LoadStructure(Stream s)
{
numberOfNeurons = Utils.IntFromStream(s);
recurring = s.ReadByte() == 1;
activationFunction = Utils.GetActivationFunctionFromID(Utils.IntFromStream(s));
}
/// <summary>
/// Save layer to stream.
/// </summary>
/// <param name="s">Stream.</param>
public void Save(Stream s)
{
int i = numberOfNeurons;
while (i-- > 0)
{
s.Write(Utils.FloatToBytes(biases[i]), 0, 4);
}
}
/// <summary>
/// Load layer from stream.
/// </summary>
/// <param name="s">Stream.</param>
public void Load(Stream s)
{
byte[] rbuf = new byte[4];
int i = numberOfNeurons;
while (i-- > 0)
{
s.Read(rbuf, 0, 4);
biases[i] = Utils.FloatFromBytes(rbuf);
}
}
/// <summary>
/// Generate random biases for layer from MIN_BIAS to MAX_BIAS.
/// </summary>
public void RandomizeBiases()
{
int i = numberOfNeurons;
while (i-- > 0)
{
biases[i] = Utils.NextFloat01() * (MAX_BIAS - MIN_BIAS) + MIN_BIAS;
}
}
/// <summary>
/// Copy biases from layer.
/// </summary>
/// <param name="nnl">Layer.</param>
public void CopyBiases(NeuralNetworkLayer nnl)
{
float[] cb = nnl.biases;
int i = numberOfNeurons;
while (i-- > 0)
{
biases[i] = cb[i];
}
}
/// <summary>
/// Mutate a selection of biases randomly.
/// </summary>
/// <param name="selectionChance">The chance(0-1) of a bias being mutated.</param>
public void Mutate(float selectionChance)
{
int i = numberOfNeurons;
while (i-- > 0)
{
if (Utils.NextFloat01() <= selectionChance)
{
biases[i] = Utils.NextFloat01() * (MAX_BIAS - MIN_BIAS) + MIN_BIAS;
}
}
}
//breed data with partner, partner must have the same # neurons/synapses
//takes a random selection of weights and biases from partner and replaces the a %(partPartner) of this classes weights/classes with those
//partPartner is the % of weights and biases to use from the partner, 0 being none and 1 being all the weights/biases
/// <summary>
/// Breed with another layer(partner) taking a %(partPartner) of randomly selected biases.
/// </summary>
/// <param name="partner">Partner layer.</param>
/// <param name="partPartner">Percent(0-1) of biases to take from partner.</param>
public void Breed(NeuralNetworkLayer partner)
{
int i = numberOfNeurons;
while (i-- > 0)
{
//randomly mix
float val = Utils.NextFloat01();
biases[i] = biases[i] * val + partner.biases[i] * (1.0f - val);
}
}
}
/// <summary>
/// Neural network layer connection.
/// </summary>
public class NeuralNetworkLayerConnection
{
/// <summary>
/// Minimum weight value when randomly generating weights.
/// </summary>
public static float MIN_WEIGHT = 0.0f;
/// <summary>
/// Maximum weight value when randomly generating weights.
/// </summary>
public static float MAX_WEIGHT = 0.06f;
/// <summary>
/// Number of synapses(neuron connections).
/// </summary>
public int numberOfSynapses;
/// <summary>
/// Array of synapse weights.
/// </summary>
public float[] weights;
/// <summary>
/// Create new struct from existing.
/// </summary>
/// <param name="src">Existing to copy.</param>
public NeuralNetworkLayerConnection(NeuralNetworkLayerConnection src)
{
numberOfSynapses = src.numberOfSynapses;
weights = new float[numberOfSynapses];
}
/// <summary>
/// Create new struct.
/// </summary>
/// <param name="inLayer">Input layer.</param>
/// <param name="outLayer">Output layer.</param>
public NeuralNetworkLayerConnection(NeuralNetworkLayer inLayer, NeuralNetworkLayer outLayer)
{
numberOfSynapses = inLayer.numberOfNeurons * outLayer.numberOfNeurons;
weights = new float[numberOfSynapses];
}
/// <summary>
/// Randomly generate weights.
/// </summary>
public void RandomizeWeights()
{
int i = numberOfSynapses;
while (i-- > 0)
{
weights[i] = Utils.NextFloat01() * (MAX_WEIGHT - MIN_WEIGHT) + MIN_WEIGHT;
}
}
/// <summary>
/// Copy weights from another connection struct.
/// </summary>
/// <param name="nnc">Source to copy from.</param>
public void CopyWeights(NeuralNetworkLayerConnection nnc)
{
float[] cb = nnc.weights;
int i = numberOfSynapses;
while (i-- > 0)
{
weights[i] = cb[i];
}
}
/// <summary>
/// Mutates a selection of weights randomly.
/// </summary>
/// <param name="selectionChance">The chance(0-1) of a weight being mutated.</param>
public void Mutate(float selectionChance)
{
int i = numberOfSynapses;
while (i-- > 0)
{
if (Utils.NextFloat01() <= selectionChance)
{
weights[i] = Utils.NextFloat01() * (MAX_WEIGHT - MIN_WEIGHT) + MIN_WEIGHT;
}
}
}
//breed with another layer connection data class(partner), partner must have the same # of synapses
//takes a random selection of weights and biases from partner and replaces the a %(partPartner) of this classes weights/classes with those
//partPartner is the % of weights and biases to use from the partner, 0 being none and 1 being all the weights/biases
/// <summary>
/// Breed with another connection(partner) taking a %(partPartner) of randomly selected weights.
/// </summary>
/// <param name="partner">Partner layer.</param>
/// <param name="partPartner">Percent(0-1) of weights to take from partner.</param>
public void Breed(NeuralNetworkLayerConnection partner)
{
int i = numberOfSynapses;
while (i-- > 0)
{
//randomly mix
float val = Utils.NextFloat01();
weights[i] = weights[i] * val + partner.weights[i] * (1.0f - val);
}
}
/// <summary>
/// Save connection to stream.
/// </summary>
/// <param name="s">Stream.</param>
public void Save(Stream s)
{
int i = numberOfSynapses;
while (i-- > 0)
{
s.Write(Utils.FloatToBytes(weights[i]), 0, 4);
}
}
//load data from stream
/// <summary>
/// Load connection from stream.
/// </summary>
/// <param name="s">Stream.</param>
public void Load(Stream s)
{
byte[] buf = new byte[4];
int i = numberOfSynapses;
while (i-- > 0)
{
s.Read(buf, 0, 4);
weights[i] = Utils.FloatFromBytes(buf);
}
}
}
//structure for saving network run-time state memory
/// <summary>
/// Neural network execution memory.
/// </summary>
public class NeuralNetworkContext
{
/// <summary>
/// Input data.
/// </summary>
public float[] inputData;
/// <summary>
/// Output data.
/// </summary>
public float[] outputData;
/// <summary>
/// Hidden state data.
/// </summary>
public float[] hiddenData;
/// <summary>
/// Hidden recurring state data.
/// </summary>
public float[][] hiddenRecurringData;
/// <summary>
/// Allocate memory arrays.
/// </summary>
/// <param name="nn">Source network.</param>
public void Setup(NeuralNetwork nn)
{
nn.SetupExecutionArrays(out inputData, out outputData, out hiddenData, out hiddenRecurringData);
Reset(true);
}
/// <summary>
/// Reset memory arrays.
/// </summary>
/// <param name="resetio">Should reset in/out arrays too?</param>
public void Reset(bool resetio)
{
if (resetio)
{
Utils.Fill(outputData, 0.0f);
Utils.Fill(inputData, 0.0f);
}
Utils.Fill(hiddenData, 0.0f);
for (int i = 0; i < hiddenRecurringData.Length; i++)
{
if (hiddenRecurringData[i] != null) Utils.Fill(hiddenRecurringData[i], 0.0f);
}
}
}
/// <summary>
/// Full execution memory(needed for training).
/// </summary>
public class NeuralNetworkFullContext
{
public float[][] hiddenBuffer, hiddenRecurringBuffer;
public void Setup(NeuralNetwork nn)
{
hiddenBuffer = new float[nn.hiddenLayers.Length][];
hiddenRecurringBuffer = new float[nn.hiddenLayers.Length][];
for (int i = 0; i < nn.hiddenLayers.Length; i++)
{
hiddenBuffer[i] = new float[nn.hiddenLayers[i].numberOfNeurons];
if (nn.hiddenLayers[i].recurring)
{
hiddenRecurringBuffer[i] = new float[nn.hiddenLayers[i].numberOfNeurons];
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RouteFiltersOperations.
/// </summary>
public static partial class RouteFiltersOperationsExtensions
{
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
public static void Delete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName)
{
operations.DeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
public static RouteFilter Get(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, routeFilterName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='expand'>
/// Expands referenced express route bgp peering resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> GetAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
public static RouteFilter CreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> CreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
public static RouteFilter Update(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters)
{
return operations.UpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> UpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteFilter> ListByResourceGroup(this IRouteFiltersOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListByResourceGroupAsync(this IRouteFiltersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteFilter> List(this IRouteFiltersOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListAsync(this IRouteFiltersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
public static void BeginDelete(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName)
{
operations.BeginDeleteAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route filter.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
public static RouteFilter BeginCreateOrUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the create or update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> BeginCreateOrUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
public static RouteFilter BeginUpdate(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters)
{
return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, routeFilterParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a route filter in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='routeFilterParameters'>
/// Parameters supplied to the update route filter operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteFilter> BeginUpdateAsync(this IRouteFiltersOperations operations, string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, routeFilterParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteFilter> ListByResourceGroupNext(this IRouteFiltersOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListByResourceGroupNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteFilter> ListNext(this IRouteFiltersOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route filters in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteFilter>> ListNextAsync(this IRouteFiltersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Management.Automation.Language;
using System.Text.RegularExpressions;
namespace System.Management.Automation
{
/// <summary>
/// Class describing a PowerShell module...
/// </summary>
[Serializable]
internal class ScriptAnalysis
{
internal static ScriptAnalysis Analyze(string path, ExecutionContext context)
{
ModuleIntrinsics.Tracer.WriteLine("Analyzing path: {0}", path);
try
{
if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null))
{
ProgressRecord analysisProgress = new ProgressRecord(0,
Modules.ScriptAnalysisPreparing,
string.Format(CultureInfo.InvariantCulture, Modules.ScriptAnalysisModule, path));
analysisProgress.RecordType = ProgressRecordType.Processing;
// Write the progress using a static source ID so that all
// analysis messages get single-threaded in the progress pane (rather than nesting).
context.CurrentCommandProcessor.CommandRuntime.WriteProgress(typeof(ScriptAnalysis).FullName.GetHashCode(), analysisProgress);
}
}
catch (InvalidOperationException)
{
// This may be called when we are not allowed to write progress,
// So eat the invalid operation
}
string scriptContent = ReadScript(path);
ParseError[] errors;
var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis);
// Don't bother analyzing if there are syntax errors (we don't do semantic analysis which would
// detect other errors that we also might choose to ignore, but it's slower.)
if (errors.Length > 0)
return null;
ExportVisitor exportVisitor = new ExportVisitor(forCompletion: false);
moduleAst.Visit(exportVisitor);
var result = new ScriptAnalysis
{
DiscoveredClasses = exportVisitor.DiscoveredClasses,
DiscoveredExports = exportVisitor.DiscoveredExports,
DiscoveredAliases = new Dictionary<string, string>(),
DiscoveredModules = exportVisitor.DiscoveredModules,
DiscoveredCommandFilters = exportVisitor.DiscoveredCommandFilters,
AddsSelfToPath = exportVisitor.AddsSelfToPath
};
if (result.DiscoveredCommandFilters.Count == 0)
{
result.DiscoveredCommandFilters.Add("*");
}
else
{
// Post-process aliases, as they are not exported by default
List<WildcardPattern> patterns = new List<WildcardPattern>();
foreach (string discoveredCommandFilter in result.DiscoveredCommandFilters)
{
patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase));
}
foreach (var pair in exportVisitor.DiscoveredAliases)
{
string discoveredAlias = pair.Key;
if (SessionStateUtilities.MatchesAnyWildcardPattern(discoveredAlias, patterns, defaultValue: false))
{
result.DiscoveredAliases[discoveredAlias] = pair.Value;
}
}
}
return result;
}
internal static string ReadScript(string path)
{
using (FileStream readerStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
Encoding defaultEncoding = ClrFacade.GetDefaultEncoding();
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle;
using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding))
{
return scriptReader.ReadToEnd();
}
}
}
internal List<string> DiscoveredExports { get; set; }
internal Dictionary<string, string> DiscoveredAliases { get; set; }
internal List<RequiredModuleInfo> DiscoveredModules { get; set; }
internal List<string> DiscoveredCommandFilters { get; set; }
internal bool AddsSelfToPath { get; set; }
internal List<TypeDefinitionAst> DiscoveredClasses { get; set; }
}
// Defines the visitor that analyzes a script to determine its exports
// and dependencies.
internal class ExportVisitor : AstVisitor2
{
internal ExportVisitor(bool forCompletion)
{
_forCompletion = forCompletion;
DiscoveredExports = new List<string>();
DiscoveredFunctions = new Dictionary<string, FunctionDefinitionAst>(StringComparer.OrdinalIgnoreCase);
DiscoveredAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DiscoveredModules = new List<RequiredModuleInfo>();
DiscoveredCommandFilters = new List<string>();
DiscoveredClasses = new List<TypeDefinitionAst>();
}
static ExportVisitor()
{
var nameParam = new ParameterInfo { name = "Name", position = 0 };
var valueParam = new ParameterInfo { name = "Value", position = 1 };
var aliasParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, valueParam } };
var functionParam = new ParameterInfo { name = "Function", position = -1 };
var cmdletParam = new ParameterInfo { name = "Cmdlet", position = -1 };
var aliasParam = new ParameterInfo { name = "Alias", position = -1 };
var ipmoParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, functionParam, cmdletParam, aliasParam } };
functionParam = new ParameterInfo { name = "Function", position = 0 };
var exportModuleMemberInfo = new ParameterBindingInfo { parameterInfo = new[] { functionParam, cmdletParam, aliasParam } };
s_parameterBindingInfoTable = new Dictionary<string, ParameterBindingInfo>(StringComparer.OrdinalIgnoreCase)
{
{"New-Alias", aliasParameterInfo},
{@"Microsoft.PowerShell.Utility\New-Alias", aliasParameterInfo},
{"Set-Alias", aliasParameterInfo},
{@"Microsoft.PowerShell.Utility\Set-Alias", aliasParameterInfo},
{"nal", aliasParameterInfo},
{"sal", aliasParameterInfo},
{"Import-Module", ipmoParameterInfo},
{@"Microsoft.PowerShell.Core\Import-Module", ipmoParameterInfo},
{"ipmo", ipmoParameterInfo},
{"Export-ModuleMember", exportModuleMemberInfo},
{@"Microsoft.PowerShell.Core\Export-ModuleMember", exportModuleMemberInfo}
};
}
private readonly bool _forCompletion;
internal List<string> DiscoveredExports { get; set; }
internal List<RequiredModuleInfo> DiscoveredModules { get; set; }
internal Dictionary<string, FunctionDefinitionAst> DiscoveredFunctions { get; set; }
internal Dictionary<string, string> DiscoveredAliases { get; set; }
internal List<string> DiscoveredCommandFilters { get; set; }
internal bool AddsSelfToPath { get; set; }
internal List<TypeDefinitionAst> DiscoveredClasses { get; set; }
public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst)
{
DiscoveredClasses.Add(typeDefinitionAst);
return _forCompletion ? AstVisitAction.Continue : AstVisitAction.SkipChildren;
}
// Capture simple function definitions
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
// Nested functions are ignored for the purposes of exports, but are still
// recorded for command/parameter completion.
// function Foo-Bar { ... }
var functionName = functionDefinitionAst.Name;
DiscoveredFunctions[functionName] = functionDefinitionAst;
ModuleIntrinsics.Tracer.WriteLine("Discovered function definition: {0}", functionName);
// Check if they've defined any aliases
// function Foo-Bar { [Alias("Alias1", "...")] param() ... }
var functionBody = functionDefinitionAst.Body;
if ((functionBody.ParamBlock != null) && (functionBody.ParamBlock.Attributes != null))
{
foreach (AttributeAst attribute in functionBody.ParamBlock.Attributes)
{
if (attribute.TypeName.GetReflectionAttributeType() == typeof(AliasAttribute))
{
foreach (ExpressionAst aliasAst in attribute.PositionalArguments)
{
var aliasExpression = aliasAst as StringConstantExpressionAst;
if (aliasExpression != null)
{
string alias = aliasExpression.Value;
DiscoveredAliases[alias] = functionName;
ModuleIntrinsics.Tracer.WriteLine("Function defines alias: {0} = {1}", alias, functionName);
}
}
}
}
}
if (_forCompletion)
{
if (Ast.GetAncestorAst<ScriptBlockAst>(functionDefinitionAst).Parent == null)
{
DiscoveredExports.Add(functionName);
}
return AstVisitAction.Continue;
}
DiscoveredExports.Add(functionName);
return AstVisitAction.SkipChildren;
}
// Capture modules that add themselves to the path (so they generally package their functionality
// as loose PS1 files)
public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
{
// $env:PATH += "";$psScriptRoot""
if (string.Equals("$env:PATH", assignmentStatementAst.Left.ToString(), StringComparison.OrdinalIgnoreCase) &&
Regex.IsMatch(assignmentStatementAst.Right.ToString(), "\\$psScriptRoot", RegexOptions.IgnoreCase))
{
ModuleIntrinsics.Tracer.WriteLine("Module adds itself to the path.");
AddsSelfToPath = true;
}
return AstVisitAction.SkipChildren;
}
// We skip a bunch of random statements because we can't really be accurate detecting functions/classes etc. that
// are conditionally defined.
public override AstVisitAction VisitIfStatement(IfStatementAst ifStmtAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitForStatement(ForStatementAst forStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitWhileStatement(WhileStatementAst whileStatementAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) { return AstVisitAction.SkipChildren; }
public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AstVisitAction.SkipChildren; }
// Visit one the other variations:
// - Dotting scripts
// - Setting aliases
// - Importing modules
// - Exporting module members
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
string commandName =
commandAst.GetCommandName() ??
GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string;
if (commandName == null)
return AstVisitAction.SkipChildren;
// They are trying to dot a script
if (commandAst.InvocationOperator == TokenKind.Dot)
{
// . Foo-Bar4.ps1
// . $psScriptRoot\Foo-Bar.ps1 -Bing Baz
// . ""$psScriptRoot\Support Files\Foo-Bar2.ps1"" -Bing Baz
// . '$psScriptRoot\Support Files\Foo-Bar3.ps1' -Bing Baz
DiscoveredModules.Add(
new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List<string>() });
ModuleIntrinsics.Tracer.WriteLine("Module dots {0}", commandName);
}
// They are setting an alias.
if (string.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Utility\\New-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Utility\\Set-Alias", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase))
{
// Set-Alias Foo-Bar5 Foo-Bar
// Set-Alias -Name Foo-Bar6 -Value Foo-Bar
// sal Foo-Bar7 Foo-Bar
// sal -Value Foo-Bar -Name Foo-Bar8
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
var name = boundParameters["Name"] as string;
if (!string.IsNullOrEmpty(name))
{
var value = boundParameters["Value"] as string;
if (!string.IsNullOrEmpty(value))
{
// These aren't stored in DiscoveredExports, as they are only
// exported after the user calls Export-ModuleMember.
DiscoveredAliases[name] = value;
ModuleIntrinsics.Tracer.WriteLine("Module defines alias: {0} = {1}", name, value);
}
}
return AstVisitAction.SkipChildren;
}
// They are importing a module
if (string.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase))
{
// Import-Module Module1
// Import-Module Module2 -Function Foo-Module2*, Foo-Module2Second* -Cmdlet Foo-Module2Cmdlet,Foo-Module2Cmdlet*
// Import-Module Module3 -Function Foo-Module3Command1, Foo-Module3Command2
// Import-Module Module4,
// Module5
// Import-Module -Name Module6,
// Module7 -Global
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
List<string> commandsToPostFilter = new List<string>();
Action<string> onEachCommand = importedCommandName =>
{
commandsToPostFilter.Add(importedCommandName);
};
// Process any exports from the module that we determine from
// the -Function, -Cmdlet, or -Alias parameters
ProcessCmdletArguments(boundParameters["Function"], onEachCommand);
ProcessCmdletArguments(boundParameters["Cmdlet"], onEachCommand);
ProcessCmdletArguments(boundParameters["Alias"], onEachCommand);
// Now, go through all of the discovered modules on Import-Module
// and register them for deeper investigation.
Action<string> onEachModule = moduleName =>
{
ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName);
DiscoveredModules.Add(
new RequiredModuleInfo
{
Name = moduleName,
CommandsToPostFilter = commandsToPostFilter
});
};
ProcessCmdletArguments(boundParameters["Name"], onEachModule);
return AstVisitAction.SkipChildren;
}
// They are exporting a module member
if (string.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "Microsoft.PowerShell.Core\\Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
string.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase))
{
// Export-ModuleMember *
// Export-ModuleMember Exported-UnNamedModuleMember
// Export-ModuleMember -Function Exported-FunctionModuleMember1, Exported-FunctionModuleMember2 -Cmdlet Exported-CmdletModuleMember `
// -Alias Exported-AliasModuleMember
// & $script:ExportModuleMember -Function (...)
var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);
Action<string> onEachFunction = exportedCommandName =>
{
DiscoveredCommandFilters.Add(exportedCommandName);
ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName);
// If the export doesn't contain wildcards, then add it to the
// discovered commands as well. It is likely that they created
// the command dynamically
if ((!WildcardPattern.ContainsWildcardCharacters(exportedCommandName)) &&
(!DiscoveredExports.Contains(exportedCommandName)))
{
DiscoveredExports.Add(exportedCommandName);
}
};
ProcessCmdletArguments(boundParameters["Function"], onEachFunction);
ProcessCmdletArguments(boundParameters["Cmdlet"], onEachFunction);
Action<string> onEachAlias = exportedAlias =>
{
DiscoveredCommandFilters.Add(exportedAlias);
// If the export doesn't contain wildcards, then add it to the
// discovered commands as well. It is likely that they created
// the command dynamically
if (!WildcardPattern.ContainsWildcardCharacters(exportedAlias))
{
DiscoveredAliases[exportedAlias] = null;
}
};
ProcessCmdletArguments(boundParameters["Alias"], onEachAlias);
return AstVisitAction.SkipChildren;
}
// They are exporting a module member using our advanced 'public' function
// that we've presented in many demos
if ((string.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase)) &&
(commandAst.CommandElements.Count > 2))
{
// public function Publicly-ExportedFunction
// public alias Publicly-ExportedAlias
string publicCommandName = commandAst.CommandElements[2].ToString().Trim();
DiscoveredExports.Add(publicCommandName);
DiscoveredCommandFilters.Add(publicCommandName);
}
return AstVisitAction.SkipChildren;
}
private void ProcessCmdletArguments(object value, Action<string> onEachArgument)
{
if (value == null) return;
var commandName = value as string;
if (commandName != null)
{
onEachArgument(commandName);
return;
}
var names = value as object[];
if (names != null)
{
foreach (var n in names)
{
// This is slightly more permissive than what would really happen with parameter binding
// in that it would allow arrays of arrays in ways that don't actually work
ProcessCmdletArguments(n, onEachArgument);
}
}
}
// This method does parameter binding for a very limited set of scenarios, specifically
// for New-Alias, Set-Alias, Import-Module, and Export-ModuleMember. It might not even
// correctly handle these cmdlets if new parameters are added.
//
// It also only populates the bound parameters for a limited set of parameters needed
// for module analysis.
private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
var parameterBindingInfo = s_parameterBindingInfoTable[commandName].parameterInfo;
int positionsBound = 0;
for (int i = 1; i < commandAst.CommandElements.Count; i++)
{
var element = commandAst.CommandElements[i];
var specifiedParameter = element as CommandParameterAst;
if (specifiedParameter != null)
{
bool boundParameter = false;
var specifiedParamName = specifiedParameter.ParameterName;
foreach (var parameterInfo in parameterBindingInfo)
{
if (parameterInfo.name.StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase))
{
if (parameterInfo.position != -1)
{
positionsBound |= 1 << parameterInfo.position;
}
var argumentAst = specifiedParameter.Argument;
if (argumentAst == null)
{
argumentAst = commandAst.CommandElements[i] as ExpressionAst;
if (argumentAst != null)
{
i += 1;
}
}
if (argumentAst != null)
{
boundParameter = true;
result[parameterInfo.name] =
GetSafeValueVisitor.GetSafeValue(argumentAst, null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis);
}
break;
}
}
if (boundParameter || specifiedParameter.Argument != null)
{
continue;
}
if (!"PassThru".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Force".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Confirm".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Global".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"AsCustomObject".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Verbose".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"Debug".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"DisableNameChecking".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) &&
!"NoClobber".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase))
{
// Named parameter, skip the argument (except for specific switch parameters
i += 1;
}
}
else
{
// Positional argument, find which position we want to bind
int pos = 0;
for (; pos < 10; pos++)
{
if ((positionsBound & (1 << pos)) == 0)
break;
}
positionsBound |= 1 << pos;
// Now see if we care (we probably do, but if the user did something odd, like specify too many, then we don't really)
foreach (var parameterInfo in parameterBindingInfo)
{
if (parameterInfo.position == pos)
{
result[parameterInfo.name] = GetSafeValueVisitor.GetSafeValue(
commandAst.CommandElements[i], null,
GetSafeValueVisitor.SafeValueContext.ModuleAnalysis);
}
}
}
}
return result;
}
private static Dictionary<string, ParameterBindingInfo> s_parameterBindingInfoTable;
private class ParameterBindingInfo
{
internal ParameterInfo[] parameterInfo;
}
private struct ParameterInfo
{
internal string name;
internal int position;
}
}
// Class to keep track of modules we need to import, and commands that should
// be filtered out of them.
[Serializable]
internal class RequiredModuleInfo
{
internal string Name { get; set; }
internal List<string> CommandsToPostFilter { get; set; }
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using OpenTK.Graphics.OpenGL;
using nzy3D.Colors;
using nzy3D.Events;
using nzy3D.Maths;
using nzy3D.Plot3D.Rendering.Canvas;
using nzy3D.Plot3D.Rendering.View;
namespace nzy3D.Plot3D.Primitives
{
/// <summary>
/// A <see cref="CompileableComposite"/> allows storage and subsequent faster execution of individual
/// contained instances drawing routines in an OpenGL display list.
///
/// Compiling the object take the time needed to render it as a standard <see cref="AbstractComposite"/>,
/// and rendering it once it is compiled seems to take roughly half the time up to now.
/// Since compilation occurs during a <see cref="CompileableComposite.Draw" />, the first call to <see cref="CompileableComposite.Draw" /> is supposed
/// to be 1.5x longer than a standard <see cref="AbstractComposite"/>, while all next cycles would be 0.5x
/// longer.
///
/// Compilation occurs when the content or the display attributes of this Composite changes
/// (then all add(), remove(), setColor(), setWireFrameDisplayed(), etc). One can also force
/// rebuilding the object by calling recompile();
///
/// IMPORTANT: for the moment, <see cref="CompileableComposite"/> should not be use in a charts using a
/// <see cref="Quality"/> superior to Intermediate, in other word, you should not desire to have alpha
/// enabled in your scene. Indeed, alpha requires ordering of polygons each time the viewpoint changes,
/// which would require to recompile the object.
///
/// @author Nils Hoffmann
/// </summary>
/// <remarks></remarks>
public class CompileableComposite : AbstractWireframeable, ISingleColorable, IMultiColorable
{
private int _dlID = -1;
private bool _resetDL = false;
internal ColorMapper _mapper;
internal Color _color;
internal bool _detailedToString = false;
internal List<AbstractDrawable> _components;
public CompileableComposite() : base()
{
_components = new List<AbstractDrawable>();
}
/// <summary>
/// Force the object to be rebuilt and stored as a display list at the next call to draw().
/// </summary>
/// <remarks>This operation does not rebuilt the object, but only marks it as "to be rebuilt" for new call to draw().</remarks>
public void Recompile()
{
_resetDL = true;
}
/// <summary>
/// Reset the object if required, compile the object if it is not compiled,
/// and execute actual rendering.
/// </summary>
/// <param name="cam">Camera to draw for.</param>
public override void Draw(Rendering.View.Camera cam)
{
if (_resetDL) {
this.Reset();
}
if (_dlID == -1) {
this.Compile(cam);
}
this.Execute(cam);
}
/// <summary>
/// If you call compile, the display list will be regenerated.
/// </summary>
internal void Compile(Rendering.View.Camera cam)
{
this.Reset();
// clear old list
this.NullifyChildrenTransforms();
_dlID = GL.GenLists(1);
GL.NewList(_dlID, ListMode.Compile);
this.DrawComponents(cam);
GL.EndList();
}
internal void Execute(Rendering.View.Camera cam)
{
if ((_transform != null)) {
_transform.Execute();
}
GL.CallList(_dlID);
}
internal void Reset()
{
if (_dlID != -1) {
if (GL.IsList(_dlID)) {
GL.DeleteLists(_dlID, 1);
}
_dlID = -1;
}
_resetDL = false;
}
/// <summary>
/// When a drawable has a null transform, no transform is applied at draw(...).
/// </summary>
internal void NullifyChildrenTransforms()
{
lock (_components) {
}
foreach (AbstractDrawable c in _components) {
if ((c != null)) {
c.Transform = null;
}
}
}
internal void DrawComponents(Camera cam)
{
lock (_components) {
foreach (AbstractDrawable s in _components) {
if ((s != null)) {
s.Draw(cam);
}
}
}
}
/// <summary>
/// Add all drawables stored by this composite.
/// </summary>
public void Add(List<AbstractDrawable> drawables)
{
this.Add(drawables);
}
/// <summary>
/// Remove all drawables stored by this composite.
/// </summary>
public void Add(IEnumerable<AbstractDrawable> drawables)
{
lock (_components) {
_components.AddRange(drawables);
Recompile();
}
}
/// <summary>
/// Clear the list of drawables stored by this composite.
/// </summary>
public void Clear()
{
lock (_components) {
_components.Clear();
Recompile();
}
}
/// <summary>
/// Add a Drawable stored by this composite.
/// </summary>
public void Add(AbstractDrawable drawable)
{
lock (_components) {
_components.Add(drawable);
Recompile();
}
}
/// <summary>
/// Remove a Drawable stored by this composite.
/// </summary>
public void Remove(AbstractDrawable drawable)
{
lock (_components) {
_components.Remove(drawable);
Recompile();
}
}
/// <summary>
/// Get a Drawable stored by this composite.
/// </summary>
public AbstractDrawable GetDrawable(int p) {
return _components[p];
}
/// <summary>
/// Get an enumerator through the list of drawabless stored by this composite.
/// </summary>
public IEnumerable<AbstractDrawable> GetDrawables {
get { return _components; }
}
/// <summary>
/// Return the number of Drawable stored by this composite.
/// </summary>
public int Size {
get { return _components.Count; }
}
public override BoundingBox3d Bounds {
get {
BoundingBox3d box = new BoundingBox3d();
lock (_components) {
foreach (AbstractDrawable c in _components) {
if ((c != null) && (c.Bounds != null)) {
box.Add(c.Bounds);
}
}
}
return box;
}
}
public override Color WireframeColor
{
get { return base.WireframeColor; }
set {
base.WireframeColor = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
AbstractWireframeable cWf = c as AbstractWireframeable;
if (cWf != null) {
cWf.WireframeColor = Color;
}
}
}
Recompile();
}
}
public override bool WireframeDisplayed
{
get { return base.WireframeDisplayed; }
set {
base.WireframeDisplayed = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
AbstractWireframeable cWf = c as AbstractWireframeable;
if (cWf != null) {
cWf.WireframeDisplayed = value;
}
}
}
Recompile();
}
}
public override float WireframeWidth
{
get { return base.WireframeWidth; }
set {
base.WireframeWidth = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
AbstractWireframeable cWf = c as AbstractWireframeable;
if (cWf != null) {
cWf.WireframeWidth = value;
}
}
}
Recompile();
}
}
public override bool FaceDisplayed
{
get { return base.FaceDisplayed; }
set {
base.FaceDisplayed = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
AbstractWireframeable cWf = c as AbstractWireframeable;
if (cWf != null)
{
cWf.FaceDisplayed = value;
}
}
}
Recompile();
}
}
public Colors.ColorMapper ColorMapper {
get { return _mapper; }
set {
_mapper = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
IMultiColorable cMC = c as IMultiColorable;
ISingleColorable cSC = c as ISingleColorable;
if (cMC != null)
{
cMC.ColorMapper = value;
} else if (cSC != null) {
cSC.Color = value.Color(c.Barycentre);
}
}
}
fireDrawableChanged(new DrawableChangedEventArgs(this, DrawableChangedEventArgs.FieldChanged.Color));
Recompile();
}
}
public Colors.Color Color {
get { return _color; }
set {
_color = value;
lock (_components) {
foreach (AbstractDrawable c in _components) {
ISingleColorable cSC = c as ISingleColorable;
if (cSC != null) {
cSC.Color = value;
}
}
}
fireDrawableChanged(new DrawableChangedEventArgs(this, DrawableChangedEventArgs.FieldChanged.Color));
Recompile();
}
}
/// <summary>
/// Returns the string representation of this composite
/// </summary>
public override string ToString()
{
return toString(0);
}
public string ToString(int depth)
{
string output = Utils.blanks(depth) + "(Composite3d) #elements:" + _components.Count + " | isDisplayed=" + this.Displayed;
if (_detailedToString) {
int k = 0;
lock (_components) {
foreach (AbstractDrawable c in _components) {
AbstractComposite cAc = c as AbstractComposite;
if (cAc != null) {
output += "\r\n" + cAc.toString(depth + 1);
} else if (c != null) {
output += "\r\n" + Utils.blanks(depth + 1) + "Composite element[" + k + "]:" + c.ToString();
} else {
output += "\r\n" + Utils.blanks(depth + 1) + "(null)";
}
k += 1;
}
}
}
return output;
}
/// <summary>
/// Get / Set the property.
/// When to true, the <see cref="CompileableComposite.toString"/> method will give the detail of each element
/// of this composite object in a tree like layout.
/// </summary>
public bool DetailedToString {
get { return _detailedToString; }
set { _detailedToString = value; }
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with redirect flow resources.
///
/// Redirect flows enable you to use GoCardless' [hosted payment
/// pages](https://pay-sandbox.gocardless.com/AL000000AKFPFF) to set up
/// mandates with your customers. These pages are fully compliant and have
/// been translated into Danish, Dutch, French, German, Italian, Norwegian,
/// Portuguese, Slovak, Spanish and Swedish.
///
/// The overall flow is:
///
/// 1. You [create](#redirect-flows-create-a-redirect-flow) a redirect flow
/// for your customer, and redirect them to the returned redirect url, e.g.
/// `https://pay.gocardless.com/flow/RE123`.
///
/// 2. Your customer supplies their name, email, address, and bank account
/// details, and submits the form. This securely stores their details, and
/// redirects them back to your `success_redirect_url` with
/// `redirect_flow_id=RE123` in the querystring.
///
/// 3. You [complete](#redirect-flows-complete-a-redirect-flow) the redirect
/// flow, which creates a [customer](#core-endpoints-customers), [customer
/// bank account](#core-endpoints-customer-bank-accounts), and
/// [mandate](#core-endpoints-mandates), and returns the ID of the mandate.
/// You may wish to create a [subscription](#core-endpoints-subscriptions)
/// or [payment](#core-endpoints-payments) at this point.
///
/// Once you have [completed](#redirect-flows-complete-a-redirect-flow) the
/// redirect flow via the API, you should display a confirmation page to
/// your customer, confirming that their Direct Debit has been set up. You
/// can build your own page, or redirect to the one we provide in the
/// `confirmation_url` attribute of the redirect flow.
///
/// Redirect flows expire 30 minutes after they are first created. You
/// cannot complete an expired redirect flow.
/// </summary>
public class RedirectFlowService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public RedirectFlowService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Creates a redirect flow object which can then be used to redirect
/// your customer to the GoCardless hosted payment pages.
/// </summary>
/// <param name="request">An optional `RedirectFlowCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single redirect flow resource</returns>
public Task<RedirectFlowResponse> CreateAsync(RedirectFlowCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new RedirectFlowCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<RedirectFlowResponse>("POST", "/redirect_flows", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "redirect_flows", customiseRequestMessage);
}
/// <summary>
/// Returns all details about a single redirect flow
/// </summary>
/// <param name="identity">Unique identifier, beginning with "RE".</param>
/// <param name="request">An optional `RedirectFlowGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single redirect flow resource</returns>
public Task<RedirectFlowResponse> GetAsync(string identity, RedirectFlowGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new RedirectFlowGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<RedirectFlowResponse>("GET", "/redirect_flows/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// This creates a [customer](#core-endpoints-customers), [customer bank
/// account](#core-endpoints-customer-bank-accounts), and
/// [mandate](#core-endpoints-mandates) using the details supplied by
/// your customer and returns the ID of the created mandate.
///
/// This will return a `redirect_flow_incomplete` error if your customer
/// has not yet been redirected back to your site, and a
/// `redirect_flow_already_completed` error if your integration has
/// already completed this flow. It will return a `bad_request` error if
/// the `session_token` differs to the one supplied when the redirect
/// flow was created.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "RE".</param>
/// <param name="request">An optional `RedirectFlowCompleteRequest` representing the body for this complete request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single redirect flow resource</returns>
public Task<RedirectFlowResponse> CompleteAsync(string identity, RedirectFlowCompleteRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new RedirectFlowCompleteRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<RedirectFlowResponse>("POST", "/redirect_flows/:identity/actions/complete", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Creates a redirect flow object which can then be used to redirect your
/// customer to the GoCardless hosted payment pages.
/// </summary>
public class RedirectFlowCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// A description of the item the customer is paying for. This will be
/// shown on the hosted payment pages.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// Linked resources.
/// </summary>
[JsonProperty("links")]
public RedirectFlowLinks Links { get; set; }
/// <summary>
/// Linked resources for a RedirectFlow.
/// </summary>
public class RedirectFlowLinks
{
/// <summary>
/// The [creditor](#core-endpoints-creditors) for whom the mandate
/// will be created. The `name` of the creditor will be displayed on
/// the payment page. Required if your account manages multiple
/// creditors.
/// </summary>
[JsonProperty("creditor")]
public string Creditor { get; set; }
}
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// Bank account information used to prefill the payment page so your
/// customer doesn't have to re-type details you already hold about
/// them. It will be stored unvalidated and the customer will be able to
/// review and amend it before completing the form.
/// </summary>
[JsonProperty("prefilled_bank_account")]
public RedirectFlowPrefilledBankAccount PrefilledBankAccount { get; set; }
/// <summary>
/// Bank account information used to prefill the payment page so your
/// customer doesn't have to re-type details you already hold about
/// them. It will be stored unvalidated and the customer will be able to
/// review and amend it before completing the form.
/// </summary>
public class RedirectFlowPrefilledBankAccount
{
/// <summary>
/// Bank account type for USD-denominated bank accounts. Must not be
/// provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more
/// information.
/// </summary>
[JsonProperty("account_type")]
public RedirectFlowAccountType? AccountType { get; set; }
/// <summary>
/// Bank account type for USD-denominated bank accounts. Must not be
/// provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum RedirectFlowAccountType
{
/// <summary>`account_type` with a value of "savings"</summary>
[EnumMember(Value = "savings")]
Savings,
/// <summary>`account_type` with a value of "checking"</summary>
[EnumMember(Value = "checking")]
Checking,
}
}
/// <summary>
/// Customer information used to prefill the payment page so your
/// customer doesn't have to re-type details you already hold about
/// them. It will be stored unvalidated and the customer will be able to
/// review and amend it before completing the form.
/// </summary>
[JsonProperty("prefilled_customer")]
public RedirectFlowPrefilledCustomer PrefilledCustomer { get; set; }
/// <summary>
/// Customer information used to prefill the payment page so your
/// customer doesn't have to re-type details you already hold about
/// them. It will be stored unvalidated and the customer will be able to
/// review and amend it before completing the form.
/// </summary>
public class RedirectFlowPrefilledCustomer
{
/// <summary>
/// The first line of the customer's address.
/// </summary>
[JsonProperty("address_line1")]
public string AddressLine1 { get; set; }
/// <summary>
/// The second line of the customer's address.
/// </summary>
[JsonProperty("address_line2")]
public string AddressLine2 { get; set; }
/// <summary>
/// The third line of the customer's address.
/// </summary>
[JsonProperty("address_line3")]
public string AddressLine3 { get; set; }
/// <summary>
/// The city of the customer's address.
/// </summary>
[JsonProperty("city")]
public string City { get; set; }
/// <summary>
/// Customer's company name. Company name should only be provided if
/// `given_name` and `family_name` are null.
/// </summary>
[JsonProperty("company_name")]
public string CompanyName { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements)
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// For Danish customers only. The civic/company number (CPR or CVR)
/// of the customer.
/// </summary>
[JsonProperty("danish_identity_number")]
public string DanishIdentityNumber { get; set; }
/// <summary>
/// Customer's email address.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Customer's surname.
/// </summary>
[JsonProperty("family_name")]
public string FamilyName { get; set; }
/// <summary>
/// Customer's first name.
/// </summary>
[JsonProperty("given_name")]
public string GivenName { get; set; }
/// <summary>
/// [ISO
/// 639-1](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
/// code.
/// </summary>
[JsonProperty("language")]
public string Language { get; set; }
/// <summary>
/// For New Zealand customers only.
/// </summary>
[JsonProperty("phone_number")]
public string PhoneNumber { get; set; }
/// <summary>
/// The customer's postal code.
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
/// <summary>
/// The customer's address region, county or department.
/// </summary>
[JsonProperty("region")]
public string Region { get; set; }
/// <summary>
/// For Swedish customers only. The civic/company number
/// (personnummer, samordningsnummer, or organisationsnummer) of the
/// customer.
/// </summary>
[JsonProperty("swedish_identity_number")]
public string SwedishIdentityNumber { get; set; }
}
/// <summary>
/// The Direct Debit scheme of the mandate. If specified, the payment
/// pages will only allow the set-up of a mandate for the specified
/// scheme. It is recommended that you leave this blank so the most
/// appropriate scheme is picked based on the customer's bank account.
/// </summary>
[JsonProperty("scheme")]
public RedirectFlowScheme? Scheme { get; set; }
/// <summary>
/// The Direct Debit scheme of the mandate. If specified, the payment
/// pages will only allow the set-up of a mandate for the specified
/// scheme. It is recommended that you leave this blank so the most
/// appropriate scheme is picked based on the customer's bank account.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum RedirectFlowScheme
{
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
/// <summary>
/// The customer's session ID must be provided when the redirect flow is
/// set up and again when it is completed. This allows integrators to
/// ensure that the user who was originally sent to the GoCardless
/// payment pages is the one who has completed them.
/// </summary>
[JsonProperty("session_token")]
public string SessionToken { get; set; }
/// <summary>
/// The URL to redirect to upon successful mandate setup. You must use a
/// URL beginning `https` in the live environment.
/// </summary>
[JsonProperty("success_redirect_url")]
public string SuccessRedirectUrl { get; set; }
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Returns all details about a single redirect flow
/// </summary>
public class RedirectFlowGetRequest
{
}
/// <summary>
/// This creates a [customer](#core-endpoints-customers), [customer bank
/// account](#core-endpoints-customer-bank-accounts), and
/// [mandate](#core-endpoints-mandates) using the details supplied by your
/// customer and returns the ID of the created mandate.
///
/// This will return a `redirect_flow_incomplete` error if your customer has
/// not yet been redirected back to your site, and a
/// `redirect_flow_already_completed` error if your integration has already
/// completed this flow. It will return a `bad_request` error if the
/// `session_token` differs to the one supplied when the redirect flow was
/// created.
/// </summary>
public class RedirectFlowCompleteRequest
{
/// <summary>
/// The customer's session ID must be provided when the redirect flow is
/// set up and again when it is completed. This allows integrators to
/// ensure that the user who was originally sent to the GoCardless
/// payment pages is the one who has completed them.
/// </summary>
[JsonProperty("session_token")]
public string SessionToken { get; set; }
}
/// <summary>
/// An API response for a request returning a single redirect flow.
/// </summary>
public class RedirectFlowResponse : ApiResponse
{
/// <summary>
/// The redirect flow from the response.
/// </summary>
[JsonProperty("redirect_flows")]
public RedirectFlow RedirectFlow { get; private set; }
}
}
| |
namespace VssSvnConverter
{
partial class SimpleUI
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.buttonBuildList = new System.Windows.Forms.Button();
this.buttonBuildVersions = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.buttonCleanupWC = new System.Windows.Forms.Button();
this.buttonImport = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.buttonStopImport = new System.Windows.Forms.Button();
this.buttonImportContinue = new System.Windows.Forms.Button();
this.buttonTryCensors = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.timerHungDetector = new System.Windows.Forms.Timer(this.components);
this.fileSystemConfigWatcher = new System.IO.FileSystemWatcher();
this.labelActiveDriver = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.fileSystemConfigWatcher)).BeginInit();
this.SuspendLayout();
//
// buttonBuildList
//
this.buttonBuildList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonBuildList.Location = new System.Drawing.Point(12, 12);
this.buttonBuildList.Name = "buttonBuildList";
this.buttonBuildList.Size = new System.Drawing.Size(185, 23);
this.buttonBuildList.TabIndex = 0;
this.buttonBuildList.Tag = "build-list";
this.buttonBuildList.Text = "1. Build List";
this.buttonBuildList.UseVisualStyleBackColor = true;
this.buttonBuildList.Click += new System.EventHandler(this.buildList_Click);
//
// buttonBuildVersions
//
this.buttonBuildVersions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonBuildVersions.Location = new System.Drawing.Point(12, 41);
this.buttonBuildVersions.Name = "buttonBuildVersions";
this.buttonBuildVersions.Size = new System.Drawing.Size(226, 23);
this.buttonBuildVersions.TabIndex = 2;
this.buttonBuildVersions.Tag = "build-versions";
this.buttonBuildVersions.Text = "2. Build versions";
this.buttonBuildVersions.UseVisualStyleBackColor = true;
this.buttonBuildVersions.Click += new System.EventHandler(this.buildList_Click);
this.buttonBuildVersions.Paint += new System.Windows.Forms.PaintEventHandler(this.buttonBuildVersions_Paint);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(12, 70);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(226, 23);
this.button2.TabIndex = 3;
this.button2.Tag = "build-links";
this.button2.Text = "3. Build links info";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.buildList_Click);
//
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button3.Location = new System.Drawing.Point(53, 99);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(144, 23);
this.button3.TabIndex = 5;
this.button3.Tag = "build-cache";
this.button3.Text = "4. Build cache";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.buildList_Click);
//
// button4
//
this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button4.Location = new System.Drawing.Point(12, 128);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(226, 23);
this.button4.TabIndex = 7;
this.button4.Tag = "build-commits";
this.button4.Text = "5. Build commits";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.buildList_Click);
//
// buttonCleanupWC
//
this.buttonCleanupWC.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonCleanupWC.Location = new System.Drawing.Point(12, 174);
this.buttonCleanupWC.Name = "buttonCleanupWC";
this.buttonCleanupWC.Size = new System.Drawing.Size(226, 23);
this.buttonCleanupWC.TabIndex = 9;
this.buttonCleanupWC.Tag = "build-wc";
this.buttonCleanupWC.Text = "6. Build/cleanup wc";
this.buttonCleanupWC.UseVisualStyleBackColor = true;
this.buttonCleanupWC.Click += new System.EventHandler(this.buildList_Click);
//
// buttonImport
//
this.buttonImport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonImport.Location = new System.Drawing.Point(12, 203);
this.buttonImport.Name = "buttonImport";
this.buttonImport.Size = new System.Drawing.Size(75, 23);
this.buttonImport.TabIndex = 10;
this.buttonImport.Tag = "import-new";
this.buttonImport.Text = "7. Import";
this.buttonImport.UseVisualStyleBackColor = true;
this.buttonImport.Click += new System.EventHandler(this.buildList_Click);
//
// button7
//
this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button7.Location = new System.Drawing.Point(12, 232);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(226, 23);
this.button7.TabIndex = 13;
this.button7.Tag = "build-scripts";
this.button7.Text = "8. Build scripts";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.buildList_Click);
//
// button8
//
this.button8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button8.Image = global::VssSvnConverter.Properties.Resources.refresh_small;
this.button8.Location = new System.Drawing.Point(203, 12);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(35, 23);
this.button8.TabIndex = 1;
this.button8.Tag = "build-list-stats";
this.toolTip1.SetToolTip(this.button8, "Refilter and reapply stats");
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.buildList_Click);
//
// button9
//
this.button9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button9.Image = global::VssSvnConverter.Properties.Resources.refresh_small;
this.button9.Location = new System.Drawing.Point(203, 99);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(35, 23);
this.button9.TabIndex = 6;
this.button9.Tag = "build-cache-stats";
this.toolTip1.SetToolTip(this.button9, "Recalc cached statistic");
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.buildList_Click);
//
// button10
//
this.button10.Location = new System.Drawing.Point(12, 99);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(35, 23);
this.button10.TabIndex = 4;
this.button10.Tag = "build-cache-clear-errors";
this.button10.Text = "CE";
this.toolTip1.SetToolTip(this.button10, "Remove errors from cache");
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.buildList_Click);
//
// buttonStopImport
//
this.buttonStopImport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonStopImport.Location = new System.Drawing.Point(209, 203);
this.buttonStopImport.Name = "buttonStopImport";
this.buttonStopImport.Size = new System.Drawing.Size(29, 23);
this.buttonStopImport.TabIndex = 12;
this.buttonStopImport.Tag = "import-stop";
this.buttonStopImport.Text = "S";
this.toolTip1.SetToolTip(this.buttonStopImport, "Stop import after next commit");
this.buttonStopImport.UseVisualStyleBackColor = true;
this.buttonStopImport.Click += new System.EventHandler(this.buttonStopImport_Click);
//
// buttonImportContinue
//
this.buttonImportContinue.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonImportContinue.Location = new System.Drawing.Point(93, 203);
this.buttonImportContinue.Name = "buttonImportContinue";
this.buttonImportContinue.Size = new System.Drawing.Size(110, 23);
this.buttonImportContinue.TabIndex = 11;
this.buttonImportContinue.Tag = "import";
this.buttonImportContinue.Text = "7. Import (continue)";
this.buttonImportContinue.UseVisualStyleBackColor = true;
this.buttonImportContinue.Click += new System.EventHandler(this.buildList_Click);
//
// buttonTryCensors
//
this.buttonTryCensors.Location = new System.Drawing.Point(12, 329);
this.buttonTryCensors.Name = "buttonTryCensors";
this.buttonTryCensors.Size = new System.Drawing.Size(226, 23);
this.buttonTryCensors.TabIndex = 17;
this.buttonTryCensors.Tag = "try-censors";
this.buttonTryCensors.Text = "Try Censore";
this.buttonTryCensors.UseVisualStyleBackColor = true;
this.buttonTryCensors.Click += new System.EventHandler(this.buildList_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 313);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(31, 13);
this.label1.TabIndex = 16;
this.label1.Text = "Test:";
//
// timerHungDetector
//
this.timerHungDetector.Interval = 1000;
this.timerHungDetector.Tick += new System.EventHandler(this.timerHungDetector_Tick);
//
// fileSystemConfigWatcher
//
this.fileSystemConfigWatcher.EnableRaisingEvents = true;
this.fileSystemConfigWatcher.SynchronizingObject = this;
this.fileSystemConfigWatcher.Changed += new System.IO.FileSystemEventHandler(this.fileSystemConfigWatcher_Changed);
this.fileSystemConfigWatcher.Created += new System.IO.FileSystemEventHandler(this.fileSystemConfigWatcher_Changed);
//
// labelActiveDriver
//
this.labelActiveDriver.AutoSize = true;
this.labelActiveDriver.Location = new System.Drawing.Point(12, 158);
this.labelActiveDriver.Name = "labelActiveDriver";
this.labelActiveDriver.Size = new System.Drawing.Size(69, 13);
this.labelActiveDriver.TabIndex = 8;
this.labelActiveDriver.Text = "Active driver:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 264);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(23, 13);
this.label2.TabIndex = 14;
this.label2.Text = "Git:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 280);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(226, 23);
this.button1.TabIndex = 15;
this.button1.Tag = "git-fast-import";
this.button1.Text = "Generate Fast Import file";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.buildList_Click);
//
// SimpleUI
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(250, 360);
this.Controls.Add(this.label2);
this.Controls.Add(this.button1);
this.Controls.Add(this.labelActiveDriver);
this.Controls.Add(this.buttonStopImport);
this.Controls.Add(this.label1);
this.Controls.Add(this.buttonTryCensors);
this.Controls.Add(this.buttonImportContinue);
this.Controls.Add(this.button10);
this.Controls.Add(this.button9);
this.Controls.Add(this.button7);
this.Controls.Add(this.buttonImport);
this.Controls.Add(this.buttonCleanupWC);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.buttonBuildVersions);
this.Controls.Add(this.button8);
this.Controls.Add(this.buttonBuildList);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "SimpleUI";
this.ShowIcon = false;
this.Text = "Converter";
this.TopMost = true;
this.Load += new System.EventHandler(this.SimpleUI_Load);
((System.ComponentModel.ISupportInitialize)(this.fileSystemConfigWatcher)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button buttonBuildList;
private System.Windows.Forms.Button buttonBuildVersions;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button buttonCleanupWC;
private System.Windows.Forms.Button buttonImport;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button buttonImportContinue;
private System.Windows.Forms.Button buttonTryCensors;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonStopImport;
private System.Windows.Forms.Timer timerHungDetector;
private System.IO.FileSystemWatcher fileSystemConfigWatcher;
private System.Windows.Forms.Label labelActiveDriver;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace GuruComponents.Netrix.UserInterface.ToolBox
{
class ToolboxItem
{
private const int _deltaDrag = 5;
private int _itemHeight = 22;
private static ContextMenu _menu = new ContextMenu();
private static StringFormat _stringFormat = new StringFormat(StringFormatFlags.NoWrap);
private static Font _font = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
private Border3DStyle _itemHoverBorder = Border3DStyle.Raised;
private Border3DStyle _itemSelectionBorder = Border3DStyle.SunkenInner;
private SolidBrush _selectionBrush = null;
private SolidBrush _itemHooverBrush = null;
private SolidBrush _textBrush = null;
private Point _startDragPos;
private bool _startDrag = false;
private int _imageIndex = -1;
private Image _image = null;
private String _caption = "";
private String _id = "";
private bool _selected = false;
private bool _highlighted = false;
private ItemPanel _panel = new ItemPanel();
private Panel _parent = null;
private bool _menuOpen = false;
public string Description = "";
public int Index = -1;
public ContextMenu ContextMenu
{
get { return _panel.ContextMenu; }
set { _panel.ContextMenu = value; }
}
public object Tag = null;
public Border3DStyle ItemHoverBorder
{
set { _itemHoverBorder = value; }
}
public Border3DStyle ItemSelectionBorder
{
set { _itemSelectionBorder = value; }
}
public Rectangle ClientRectangle
{
get { return _panel.ClientRectangle; }
}
public Rectangle Bounds
{
get { return _panel.Bounds; }
}
public bool Selected
{
get { return _selected; }
set
{
_selected = value;
_panel.Invalidate();
}
}
public bool Highlighted
{
get { return _highlighted; }
set
{
_highlighted = value;
_panel.Invalidate();
}
}
public String Caption
{
get { return _caption; }
}
public String Id
{
get { return _id; }
}
public int ImageIndex
{
get { return _imageIndex; }
}
public int Top
{
get { return _panel.Top; }
set { _panel.Top = value; }
}
public int Left
{
set { _panel.Left = value; }
}
public int Width
{
set { _panel.Width = value; _panel.Invalidate(); }
}
public int Height
{
get { return _panel.Height; }
}
public int Bottom
{
get { return _panel.Bottom; }
}
public SolidBrush BackgroundBrush
{
set { _panel.BackColor = value.Color; }
}
public SolidBrush SelectionBrush
{
set { _selectionBrush = value; }
}
public SolidBrush ItemHooverBrush
{
set { _itemHooverBrush = value; }
}
public SolidBrush TextBrush
{
set { _textBrush = value; }
}
public Image Image
{
set { _image = value; }
}
public event EventHandler ItemUnHighlighted;
public event EventHandler ItemHighlighted;
public event EventHandler ItemClick;
public event EventHandler ItemDoubleClick;
public event EventHandler ItemDrag;
static ToolboxItem()
{
_stringFormat.Alignment = StringAlignment.Near;
_stringFormat.LineAlignment = StringAlignment.Center;
_stringFormat.Trimming = StringTrimming.EllipsisCharacter;
_menu.MenuItems.Add("Delete");
}
public ToolboxItem(string caption, string id, string description,
int imageIndex, ImageList imageList, object tag, Panel parent)
{
_imageIndex = imageIndex;
_caption = caption;
_id = id;
Tag = tag;
Description = description;
_parent = parent;
if (imageList != null && _imageIndex >= 0 && _imageIndex < imageList.Images.Count)
{
_image = imageList.Images[_imageIndex];
}
_panel.Left = 0;
_panel.Height = _itemHeight;
_panel.Width = _parent.Width;
_panel.MouseMove += new MouseEventHandler(OnMouseMove);
_panel.MouseUp += new MouseEventHandler(OnMouseUp);
_panel.MouseDown += new MouseEventHandler(OnMouseDown);
_panel.MouseEnter += new EventHandler(OnMouseEnter);
_panel.MouseLeave += new EventHandler(OnMouseLeave);
_panel.Click += new EventHandler(OnMouseClick);
_panel.DoubleClick += new EventHandler(OnMouseDoubleClick);
_panel.Paint += new PaintEventHandler(OnPaint);
_parent.Controls.Add(_panel);
}
/// <summary>
/// Removes an item.
/// </summary>
/// <param name="tip"></param>
public void Remove(ToolTip tip)
{
_parent.Controls.Remove(_panel);
tip.SetToolTip(_panel, "");
}
public void ScrollUp(int offset)
{
_panel.Top += _panel.Height + offset;
}
public void ScrollDown(int offset)
{
_panel.Top -= _panel.Height + offset;
}
public void SetToolTip(ToolTip tip)
{
if (Description != "")
{
tip.SetToolTip(_panel, Caption + "\n" + Description);
}
else
{
tip.SetToolTip(_panel, Caption);
}
}
private void OnMouseEnter(object sender, EventArgs e)
{
if (ItemHighlighted != null)
{
ItemHighlighted(this, EventArgs.Empty);
}
}
private void OnMouseLeave(object sender, EventArgs e)
{
if (!_menuOpen && ItemUnHighlighted != null)
{
ItemUnHighlighted(this, EventArgs.Empty);
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (_startDrag)
{
Point p = Control.MousePosition;
if (Math.Abs(p.X - _startDragPos.X) > _deltaDrag || Math.Abs(p.X - _startDragPos.X) > _deltaDrag)
{
_startDrag = false;
if (ItemDrag != null)
{
ItemDrag(this, EventArgs.Empty);
}
}
}
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
_startDrag = true;
_startDragPos = Control.MousePosition;
ItemClick(this, EventArgs.Empty);
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_startDrag = false;
}
private void OnMouseClick(object sender, EventArgs e) { }
private void OnMouseDoubleClick(object sender, EventArgs e)
{
if (ItemDoubleClick != null)
{
ItemDoubleClick(this, EventArgs.Empty);
}
}
private void OnPaint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle rect = ClientRectangle;
if (_selected)
{
g.FillRectangle(_selectionBrush, e.ClipRectangle);
ControlPaint.DrawBorder3D(g, rect, _itemSelectionBorder);
}
if (!_selected && _highlighted)
{
g.FillRectangle(_itemHooverBrush, e.ClipRectangle);
ControlPaint.DrawBorder3D(g, rect, _itemHoverBorder);
}
if (_image != null)
{
g.DrawImage(_image, 4, (rect.Height - _image.Height) / 2);
}
rect.Width -= rect.Height + 6;
rect.X += rect.Height + 4;
g.DrawString(_caption, _font, _textBrush, rect, _stringFormat);
}
}
}
| |
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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.Runtime.CompilerServices;
using ScriptRuntime;
namespace ScriptRuntime
{
public partial class Actor : Base
{
// - internal call declare
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Bind(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Release(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetName(Actor self, String sName);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static String ICall_Actor_GetName(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static String ICall_Actor_GetTemplateName(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLayerID(Actor self, UInt32 layerID);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static UInt32 ICall_Actor_GetLayerID(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_IsLinkTemplate(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLinkTemplate(Actor self, bool bLink);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetTagID(Actor self, UInt32 tagID);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static UInt32 ICall_Actor_GetTagID(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static byte[] ICall_Actor_GetGuid(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static UInt32 ICall_Actor_GetFastId(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_IsActive(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_GetActiveControl(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Active(Actor self, bool forceActiveControlofChild);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Deactive(Actor self, bool forceActiveControlofChild);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Actor ICall_Actor_GetParent(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetParent(Actor self, Actor parent);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_Actor_GetChildCount(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Actor ICall_Actor_GetChild(Actor self, int index);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Actor ICall_Actor_FindChild(Actor self, UInt32 fastId);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_Actor_FindChildIndex(Actor self, UInt32 fastId);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_AddChild(Actor self, Actor child);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_RemoveChild(Actor self, int index);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLocalPos(Actor self, ref Vector3 pos);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLocalRotation(Actor self, ref Quaternion rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLocalScale(Actor self, ref Vector3 scale);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetLocalPos(Actor self, out Vector3 outPos);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetLocalRotation(Actor self, out Quaternion outRot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetLocalScale(Actor self, out Vector3 outScale);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Roll(Actor self, float angle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Pitch(Actor self, float angle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Yaw(Actor self, float angle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_Rotate(Actor self, float roll, float picth, float yaw);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetTransform(Actor self, ref Matrix44 matrix);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetTransform(Actor self, out Matrix44 matrix);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetWorldTransform(Actor self, ref Matrix44 matrix);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldTransform(Actor self, out Matrix44 matrix);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetInheritRotation(Actor self, bool bInherit);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_GetInheritRotation(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetInheritScale(Actor self, bool bInherit);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_GetInheritScale(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldRotation(Actor self, out Quaternion rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetWorldRotation(Actor self, ref Quaternion rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldPos(Actor self, out Vector3 rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetWorldPos(Actor self, ref Vector3 rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldScale(Actor self, out Vector3 rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetWorldScale(Actor self, ref Vector3 rot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldBoundingBox(Actor self, out BoundingBox bb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetWorldBoundingBoxWithChild(Actor self, out BoundingBox bb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_GetLocalBoundingBox(Actor self, out BoundingBox bb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetLocalBoundingBox(Actor self, ref BoundingBox bb);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Component ICall_Actor_RemoveComponent(Actor self, Component comp);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Component ICall_Actor_AddComponentByName(Actor self, String sName);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static Component ICall_Actor_GetComponentByName(Actor self, String sName);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static bool ICall_Actor_IsAllResourcePrepared(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_Actor_SetPriority(Actor self, int priority);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_Actor_GetPriority(Actor self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_Actor_GetRefCount(Actor self);
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Cinematic/Temporal Anti-aliasing")]
public class TemporalAntiAliasing : MonoBehaviour
{
public enum Sequence
{
Halton
}
[Serializable]
public struct JitterSettings
{
[Tooltip("The sequence used to generate the points used as jitter offsets.")]
public Sequence sequence;
[Tooltip("The diameter (in texels) inside which jitter samples are spread. Smaller values result in crisper but more aliased output, while larger values result in more stable but blurrier output.")]
[Range(0.1f, 3f)]
public float spread;
[Tooltip("Number of temporal samples. A larger value results in a smoother image but takes longer to converge; whereas a smaller value converges fast but allows for less subpixel information.")]
[Range(4, 64)]
public int sampleCount;
}
[Serializable]
public struct SharpenFilterSettings
{
[Tooltip("Controls the amount of sharpening applied to the color buffer.")]
[Range(0f, 3f)]
public float amount;
}
[Serializable]
public struct BlendSettings
{
[Tooltip("The blend coefficient for a stationary fragment. Controls the percentage of history sample blended into the final color.")]
[Range(0f, 0.99f)]
public float stationary;
[Tooltip("The blend coefficient for a fragment with significant motion. Controls the percentage of history sample blended into the final color.")]
[Range(0f, 0.99f)]
public float moving;
[Tooltip("Amount of motion amplification in percentage. A higher value will make the final blend more sensitive to smaller motion, but might result in more aliased output; while a smaller value might desensitivize the algorithm resulting in a blurry output.")]
[Range(30f, 100f)]
public float motionAmplification;
}
[Serializable]
public struct DebugSettings
{
[Tooltip("Forces the game view to update automatically while not in play mode.")]
public bool forceRepaint;
}
[Serializable]
public class Settings
{
[AttributeUsage(AttributeTargets.Field)]
public class LayoutAttribute : PropertyAttribute
{
}
[Layout]
public JitterSettings jitterSettings;
[Layout]
public SharpenFilterSettings sharpenFilterSettings;
[Layout]
public BlendSettings blendSettings;
[Layout]
public DebugSettings debugSettings;
public static Settings defaultSettings
{
get
{
return new Settings
{
jitterSettings = new JitterSettings
{
sequence = Sequence.Halton,
spread = 1f,
sampleCount = 8
},
sharpenFilterSettings = new SharpenFilterSettings
{
amount = 0.25f
},
blendSettings = new BlendSettings
{
stationary = 0.98f,
moving = 0.8f,
motionAmplification = 60f
},
debugSettings = new DebugSettings
{
forceRepaint = false
}
};
}
}
}
[SerializeField]
public Settings settings = Settings.defaultSettings;
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/Temporal Anti-aliasing");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
{
if (shader == null || !shader.isSupported)
return null;
m_Material = new Material(shader);
}
return m_Material;
}
}
private Camera m_Camera;
public Camera camera_
{
get
{
if (m_Camera == null)
m_Camera = GetComponent<Camera>();
return m_Camera;
}
}
private void RenderFullScreenQuad(int pass)
{
GL.PushMatrix();
GL.LoadOrtho();
material.SetPass(pass);
//Render the full screen quad manually.
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 0.1f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(1.0f, 0.0f, 0.1f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 0.1f);
GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(0.0f, 1.0f, 0.1f);
GL.End();
GL.PopMatrix();
}
private RenderTexture m_History;
private int m_SampleIndex = 0;
#if UNITY_EDITOR
private double m_NextForceRepaintTime = 0;
#endif
private float GetHaltonValue(int index, int radix)
{
float result = 0.0f;
float fraction = 1.0f / (float)radix;
while (index > 0)
{
result += (float)(index % radix) * fraction;
index /= radix;
fraction /= (float)radix;
}
return result;
}
private Vector2 GenerateRandomOffset()
{
Vector2 offset = new Vector2(
GetHaltonValue(m_SampleIndex & 1023, 2),
GetHaltonValue(m_SampleIndex & 1023, 3));
if (++m_SampleIndex >= settings.jitterSettings.sampleCount)
m_SampleIndex = 0;
return offset;
}
// Adapted heavily from PlayDead's TAA code
// https://github.com/playdeadgames/temporal/blob/master/Assets/Scripts/Extensions.cs
private Matrix4x4 GetPerspectiveProjectionMatrix(Vector2 offset)
{
float vertical = Mathf.Tan(0.5f * Mathf.Deg2Rad * camera_.fieldOfView);
float horizontal = vertical * camera_.aspect;
offset.x *= horizontal / (0.5f * camera_.pixelWidth);
offset.y *= vertical / (0.5f * camera_.pixelHeight);
float left = (offset.x - horizontal) * camera_.nearClipPlane;
float right = (offset.x + horizontal) * camera_.nearClipPlane;
float top = (offset.y + vertical) * camera_.nearClipPlane;
float bottom = (offset.y - vertical) * camera_.nearClipPlane;
Matrix4x4 matrix = new Matrix4x4();
matrix[0, 0] = (2.0f * camera_.nearClipPlane) / (right - left);
matrix[0, 1] = 0.0f;
matrix[0, 2] = (right + left) / (right - left);
matrix[0, 3] = 0.0f;
matrix[1, 0] = 0.0f;
matrix[1, 1] = (2.0f * camera_.nearClipPlane) / (top - bottom);
matrix[1, 2] = (top + bottom) / (top - bottom);
matrix[1, 3] = 0.0f;
matrix[2, 0] = 0.0f;
matrix[2, 1] = 0.0f;
matrix[2, 2] = -(camera_.farClipPlane + camera_.nearClipPlane) / (camera_.farClipPlane - camera_.nearClipPlane);
matrix[2, 3] = -(2.0f * camera_.farClipPlane * camera_.nearClipPlane) / (camera_.farClipPlane - camera_.nearClipPlane);
matrix[3, 0] = 0.0f;
matrix[3, 1] = 0.0f;
matrix[3, 2] = -1.0f;
matrix[3, 3] = 0.0f;
return matrix;
}
private Matrix4x4 GetOrthographicProjectionMatrix(Vector2 offset)
{
float vertical = camera_.orthographicSize;
float horizontal = vertical * camera_.aspect;
offset.x *= horizontal / (0.5f * camera_.pixelWidth);
offset.y *= vertical / (0.5f * camera_.pixelHeight);
float left = offset.x - horizontal;
float right = offset.x + horizontal;
float top = offset.y + vertical;
float bottom = offset.y - vertical;
return Matrix4x4.Ortho(left, right, bottom, top, camera_.nearClipPlane, camera_.farClipPlane);
}
void OnEnable()
{
#if !UNITY_5_4_OR_NEWER
enabled = false;
#endif
#if UNITY_EDITOR
UnityEditor.EditorApplication.update += ForceRepaint;
#endif
camera_.depthTextureMode = DepthTextureMode.Depth | DepthTextureMode.MotionVectors;
#if UNITY_5_5_OR_NEWER
camera_.useJitteredProjectionMatrixForTransparentRendering = true;
#endif
}
void OnDisable()
{
if (m_History != null)
{
RenderTexture.ReleaseTemporary(m_History);
m_History = null;
}
camera_.depthTextureMode &= ~(DepthTextureMode.MotionVectors);
m_SampleIndex = 0;
}
void OnPreCull()
{
Vector2 jitter = GenerateRandomOffset();
jitter *= settings.jitterSettings.spread;
#if UNITY_5_4_OR_NEWER
camera_.nonJitteredProjectionMatrix = camera_.projectionMatrix;
#endif
camera_.projectionMatrix = camera_.orthographic
? GetOrthographicProjectionMatrix(jitter)
: GetPerspectiveProjectionMatrix(jitter);
jitter.x /= camera_.pixelWidth;
jitter.y /= camera_.pixelHeight;
material.SetVector("_Jitter", jitter);
}
[ImageEffectOpaque]
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (m_History == null || (m_History.width != source.width || m_History.height != source.height))
{
if (m_History)
RenderTexture.ReleaseTemporary(m_History);
m_History = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default);
m_History.filterMode = FilterMode.Bilinear;
m_History.hideFlags = HideFlags.HideAndDontSave;
Graphics.Blit(source, m_History, material, 2);
}
material.SetVector("_SharpenParameters", new Vector4(settings.sharpenFilterSettings.amount, 0f, 0f, 0f));
material.SetVector("_FinalBlendParameters", new Vector4(settings.blendSettings.stationary, settings.blendSettings.moving, 100f * settings.blendSettings.motionAmplification, 0f));
material.SetTexture("_MainTex", source);
material.SetTexture("_HistoryTex", m_History);
RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default);
temporary.filterMode = FilterMode.Bilinear;
var effectDestination = destination;
var doesNeedExtraBlit = false;
if (destination == null)
{
effectDestination = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default);
effectDestination.filterMode = FilterMode.Bilinear;
doesNeedExtraBlit = true;
}
var renderTargets = new RenderBuffer[2];
renderTargets[0] = effectDestination.colorBuffer;
renderTargets[1] = temporary.colorBuffer;
Graphics.SetRenderTarget(renderTargets, effectDestination.depthBuffer);
RenderFullScreenQuad(camera_.orthographic ? 1 : 0);
RenderTexture.ReleaseTemporary(m_History);
m_History = temporary;
if (doesNeedExtraBlit)
{
Graphics.Blit(effectDestination, destination);
RenderTexture.ReleaseTemporary(effectDestination);
}
RenderTexture.active = destination;
}
public void OnPostRender()
{
camera_.ResetProjectionMatrix();
}
#if UNITY_EDITOR
private void ForceRepaint()
{
if (settings.debugSettings.forceRepaint && !UnityEditor.EditorApplication.isPlaying)
{
var time = UnityEditor.EditorApplication.timeSinceStartup;
if (time > m_NextForceRepaintTime)
{
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
m_NextForceRepaintTime = time + 0.033333;
}
}
}
#endif
}
}
| |
using System;
using System.Collections;
using IBatisNet.Common;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Test.Domain;
using NUnit.Framework;
namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests
{
/// <summary>
/// Summary description for ParameterMapTest.
/// </summary>
[TestFixture]
public class StatementTest : BaseTest
{
#region SetUp & TearDown
/// <summary>
/// SetUp
/// </summary>
[SetUp]
public void Init()
{
InitScript(sqlMap.DataSource, ScriptDirectory + "account-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "order-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "line-item-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "enumeration-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "other-init.sql");
}
/// <summary>
/// TearDown
/// </summary>
[TearDown]
public void Dispose()
{ /* ... */
}
#endregion
#region Object Query tests
/// <summary>
/// Test Open connection with a connection string
/// </summary>
[Test]
public void TestOpenConnection()
{
sqlMap.OpenConnection(sqlMap.DataSource.ConnectionString);
Account account = sqlMap.QueryForObject("SelectWithProperty", null) as Account;
sqlMap.CloseConnection();
AssertAccount1(account);
}
/// <summary>
/// Test use a statement with property subtitution
/// (JIRA 22)
/// </summary>
[Test]
public void TestSelectWithProperty()
{
Account account = sqlMap.QueryForObject("SelectWithProperty", null) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ColumnName
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaColumnName()
{
Account account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ColumnIndex
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaColumnIndex()
{
Account account = sqlMap.QueryForObject("GetAccountViaColumnIndex", 1) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ResultClass
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaResultClass()
{
Account account = sqlMap.QueryForObject("GetAccountViaResultClass", 1) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject With simple ResultClass : string
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithSimpleResultClass()
{
string email = sqlMap.QueryForObject("GetEmailAddressViaResultClass", 1) as string;
Assert.AreEqual("Joe.Dalton@somewhere.com", email);
}
/// <summary>
/// Test ExecuteQueryForObject With simple ResultMap : string
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithSimpleResultMap()
{
string email = sqlMap.QueryForObject("GetEmailAddressViaResultMap", 1) as string;
Assert.AreEqual("Joe.Dalton@somewhere.com", email);
}
/// <summary>
/// Test Primitive ReturnValue : System.DateTime
/// </summary>
[Test]
public void TestPrimitiveReturnValue()
{
DateTime CardExpiry = (DateTime) sqlMap.QueryForObject("GetOrderCardExpiryViaResultClass", 1);
Assert.AreEqual(new DateTime(2003, 02, 15, 8, 15, 00), CardExpiry);
}
/// <summary>
/// Test ExecuteQueryForObject with result object : Account
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithResultObject()
{
Account account = new Account();
Account testAccount = sqlMap.QueryForObject("GetAccountViaColumnName", 1, account) as Account;
AssertAccount1(account);
Assert.IsTrue(account == testAccount);
}
/// <summary>
/// Test ExecuteQueryForObject as Hashtable
/// </summary>
[Test]
public void TestExecuteQueryForObjectAsHashtable()
{
Hashtable account = (Hashtable) sqlMap.QueryForObject("GetAccountAsHashtable", 1);
AssertAccount1AsHashtable(account);
}
/// <summary>
/// Test ExecuteQueryForObject as Hashtable ResultClass
/// </summary>
[Test]
public void TestExecuteQueryForObjectAsHashtableResultClass()
{
Hashtable account = (Hashtable) sqlMap.QueryForObject("GetAccountAsHashtableResultClass", 1);
AssertAccount1AsHashtableForResultClass(account);
}
/// <summary>
/// Test ExecuteQueryForObject via Hashtable
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaHashtable()
{
Hashtable param = new Hashtable();
param.Add("LineItem_ID", 2);
param.Add("Order_ID", 9);
LineItem testItem = sqlMap.QueryForObject("GetSpecificLineItem", param) as LineItem;
Assert.IsNotNull(testItem);
Assert.AreEqual("TSM-12", testItem.Code);
}
/// <summary>
/// Test Query Dynamic Sql Element
/// </summary>
[Test]
public void TestQueryDynamicSqlElement()
{
IList list = sqlMap.QueryForList("GetDynamicOrderedEmailAddressesViaResultMap", "Account_ID");
Assert.AreEqual("Joe.Dalton@somewhere.com", (string) list[0]);
list = sqlMap.QueryForList("GetDynamicOrderedEmailAddressesViaResultMap", "Account_FirstName");
Assert.AreEqual("Averel.Dalton@somewhere.com", (string) list[0]);
}
/// <summary>
/// Test Execute QueryForList With ResultMap With Dynamic Element
/// </summary>
[Test]
public void TestExecuteQueryForListWithResultMapWithDynamicElement()
{
IList list = sqlMap.QueryForList("GetAllAccountsViaResultMapWithDynamicElement", "LIKE");
AssertAccount1((Account) list[0]);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(4, ((Account) list[2]).Id);
list = sqlMap.QueryForList("GetAllAccountsViaResultMapWithDynamicElement", "=");
Assert.AreEqual(0, list.Count);
}
/// <summary>
/// Test Simple Dynamic Substitution
/// </summary>
[Test]
[Ignore("No longer supported.")]
public void TestSimpleDynamicSubstitution()
{
string statement = "select" + " Account_ID as Id," + " Account_FirstName as FirstName," + " Account_LastName as LastName," + " Account_Email as EmailAddress" + " from Accounts" + " WHERE Account_ID = #id#";
Hashtable param = new Hashtable();
param.Add("id", 1);
param.Add("statement", statement);
IList list = sqlMap.QueryForList("SimpleDynamicSubstitution", param);
AssertAccount1((Account) list[0]);
Assert.AreEqual(1, list.Count);
}
/// <summary>
/// Test Get Account Via Inline Parameters
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaInlineParameters()
{
Account account = new Account();
account.Id = 1;
Account testAccount = sqlMap.QueryForObject("GetAccountViaInlineParameters", account) as Account;
AssertAccount1(testAccount);
}
/// <summary>
/// Test ExecuteQuery For Object With Enum property
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithEnum()
{
Enumeration enumClass = sqlMap.QueryForObject("GetEnumeration", 1) as Enumeration;
Assert.AreEqual(enumClass.Day, Days.Sat);
Assert.AreEqual(enumClass.Color, Colors.Red);
Assert.AreEqual(enumClass.Month, Months.August);
enumClass = sqlMap.QueryForObject("GetEnumeration", 3) as Enumeration;
Assert.AreEqual(enumClass.Day, Days.Mon);
Assert.AreEqual(enumClass.Color, Colors.Blue);
Assert.AreEqual(enumClass.Month, Months.September);
}
#endregion
#region List Query tests
/// <summary>
/// Test QueryForList with Hashtable ResultMap
/// </summary>
[Test]
public void TestQueryForListWithHashtableResultMap()
{
IList list = sqlMap.QueryForList("GetAllAccountsAsHashMapViaResultMap", null);
AssertAccount1AsHashtable((Hashtable) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Hashtable) list[0])["Id"]);
Assert.AreEqual(2, ((Hashtable) list[1])["Id"]);
Assert.AreEqual(3, ((Hashtable) list[2])["Id"]);
Assert.AreEqual(4, ((Hashtable) list[3])["Id"]);
Assert.AreEqual(5, ((Hashtable) list[4])["Id"]);
}
/// <summary>
/// Test QueryForList with Hashtable ResultClass
/// </summary>
[Test]
public void TestQueryForListWithHashtableResultClass()
{
IList list = sqlMap.QueryForList("GetAllAccountsAsHashtableViaResultClass", null);
AssertAccount1AsHashtableForResultClass((Hashtable) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Hashtable) list[0])[BaseTest.ConvertKey("Id")]);
Assert.AreEqual(2, ((Hashtable) list[1])[BaseTest.ConvertKey("Id")]);
Assert.AreEqual(3, ((Hashtable) list[2])[BaseTest.ConvertKey("Id")]);
Assert.AreEqual(4, ((Hashtable) list[3])[BaseTest.ConvertKey("Id")]);
Assert.AreEqual(5, ((Hashtable) list[4])[BaseTest.ConvertKey("Id")]);
}
/// <summary>
/// Test QueryForList With ResultMap, result collection as ArrayList
/// </summary>
[Test]
public void TestQueryForListWithResultMap()
{
IList list = sqlMap.QueryForList("GetAllAccountsViaResultMap", null);
AssertAccount1((Account) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(3, ((Account) list[2]).Id);
Assert.AreEqual(4, ((Account) list[3]).Id);
Assert.AreEqual(5, ((Account) list[4]).Id);
}
/// <summary>
/// Test ExecuteQueryForPaginatedList
/// </summary>
[Test]
public void TestExecuteQueryForPaginatedList()
{
// Get List of all 5
PaginatedList list = sqlMap.QueryForPaginatedList("GetAllAccountsViaResultMap", null, 2);
// Test initial state (page 0)
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
AssertAccount1((Account) list[0]);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
// Test illegal previous page (no effect, state should be same)
list.PreviousPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
AssertAccount1((Account) list[0]);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
// Test next (page 1)
list.NextPage();
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(3, ((Account) list[0]).Id);
Assert.AreEqual(4, ((Account) list[1]).Id);
// Test next (page 2 -last)
list.NextPage();
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
Assert.AreEqual(5, ((Account) list[0]).Id);
// Test previous (page 1)
list.PreviousPage();
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(3, ((Account) list[0]).Id);
Assert.AreEqual(4, ((Account) list[1]).Id);
// Test previous (page 0 -first)
list.PreviousPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
AssertAccount1((Account) list[0]);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
// Test goto (page 0)
list.GotoPage(0);
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
// Test goto (page 1)
list.GotoPage(1);
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsTrue(list.IsNextPageAvailable);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(3, ((Account) list[0]).Id);
Assert.AreEqual(4, ((Account) list[1]).Id);
// Test goto (page 2)
list.GotoPage(2);
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
Assert.AreEqual(5, ((Account) list[0]).Id);
// Test illegal goto (page 0)
list.GotoPage(3);
Assert.IsTrue(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(0, list.Count);
list = sqlMap.QueryForPaginatedList("GetNoAccountsViaResultMap", null, 2);
// Test empty list
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(0, list.Count);
// Test next
list.NextPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(0, list.Count);
// Test previous
list.PreviousPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(0, list.Count);
// Test previous
list.GotoPage(0);
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(0, list.Count);
list = sqlMap.QueryForPaginatedList("GetFewAccountsViaResultMap", null, 2);
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
// Test next
list.NextPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
// Test previous
list.PreviousPage();
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
// Test previous
list.GotoPage(0);
Assert.IsFalse(list.IsPreviousPageAvailable);
Assert.IsFalse(list.IsNextPageAvailable);
Assert.AreEqual(1, list.Count);
// Test Even - Two Pages
try
{
InitScript(sqlMap.DataSource, ScriptDirectory + "more-account-records.sql");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
list = sqlMap.QueryForPaginatedList("GetAllAccountsViaResultMap", null, 5);
Assert.AreEqual(5, list.Count);
list.NextPage();
Assert.AreEqual(5, list.Count);
bool b = list.IsPreviousPageAvailable;
list.PreviousPage();
Assert.AreEqual(5, list.Count);
}
/// <summary>
/// Test QueryForList with ResultObject :
/// AccountCollection strongly typed collection
/// </summary>
[Test]
public void TestQueryForListWithResultObject()
{
AccountCollection accounts = new AccountCollection();
sqlMap.QueryForList("GetAllAccountsViaResultMap", null, accounts);
AssertAccount1(accounts[0]);
Assert.AreEqual(5, accounts.Count);
Assert.AreEqual(1, accounts[0].Id);
Assert.AreEqual(2, accounts[1].Id);
Assert.AreEqual(3, accounts[2].Id);
Assert.AreEqual(4, accounts[3].Id);
Assert.AreEqual(5, accounts[4].Id);
}
/// <summary>
/// Test QueryForList with ListClass : LineItemCollection
/// </summary>
[Test]
public void TestQueryForListWithListClass()
{
LineItemCollection linesItem = sqlMap.QueryForList("GetLineItemsForOrderWithListClass", 10) as LineItemCollection;
Assert.IsNotNull(linesItem);
Assert.AreEqual(2, linesItem.Count);
Assert.AreEqual("ESM-34", linesItem[0].Code);
Assert.AreEqual("QSM-98", linesItem[1].Code);
}
/// <summary>
/// Test QueryForList with no result.
/// </summary>
[Test]
public void TestQueryForListWithNoResult()
{
IList list = sqlMap.QueryForList("GetNoAccountsViaResultMap", null);
Assert.AreEqual(0, list.Count);
}
/// <summary>
/// Test QueryForList with ResultClass : Account.
/// </summary>
[Test]
public void TestQueryForListResultClass()
{
IList list = sqlMap.QueryForList("GetAllAccountsViaResultClass", null);
AssertAccount1((Account) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(3, ((Account) list[2]).Id);
Assert.AreEqual(4, ((Account) list[3]).Id);
Assert.AreEqual(5, ((Account) list[4]).Id);
}
/// <summary>
/// Test QueryForList with simple resultClass : string
/// </summary>
[Test]
public void TestQueryForListWithSimpleResultClass()
{
IList list = sqlMap.QueryForList("GetAllEmailAddressesViaResultClass", null);
Assert.AreEqual("Joe.Dalton@somewhere.com", (string) list[0]);
Assert.AreEqual("Averel.Dalton@somewhere.com", (string) list[1]);
Assert.IsNull(list[2]);
Assert.AreEqual("Jack.Dalton@somewhere.com", (string) list[3]);
Assert.IsNull(list[4]);
}
/// <summary>
/// Test QueryForList with simple ResultMap : string
/// </summary>
[Test]
public void TestQueryForListWithSimpleResultMap()
{
IList list = sqlMap.QueryForList("GetAllEmailAddressesViaResultMap", null);
Assert.AreEqual("Joe.Dalton@somewhere.com", (string) list[0]);
Assert.AreEqual("Averel.Dalton@somewhere.com", (string) list[1]);
Assert.IsNull(list[2]);
Assert.AreEqual("Jack.Dalton@somewhere.com", (string) list[3]);
Assert.IsNull(list[4]);
}
/// <summary>
/// Test QueryForListWithSkipAndMax
/// </summary>
[Test]
public void TestQueryForListWithSkipAndMax()
{
IList list = sqlMap.QueryForList("GetAllAccountsViaResultMap", null, 2, 2);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(3, ((Account) list[0]).Id);
Assert.AreEqual(4, ((Account) list[1]).Id);
}
[Test]
public void TestQueryWithRowDelegate()
{
SqlMapper.RowDelegate handler = new SqlMapper.RowDelegate(this.RowHandler);
IList list = sqlMap.QueryWithRowDelegate("GetAllAccountsViaResultMap", null, handler);
Assert.AreEqual(5, _index);
Assert.AreEqual(5, list.Count);
AssertAccount1((Account) list[0]);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(3, ((Account) list[2]).Id);
Assert.AreEqual(4, ((Account) list[3]).Id);
Assert.AreEqual(5, ((Account) list[4]).Id);
}
#endregion
#region Map Tests
/// <summary>
/// Test ExecuteQueryForMap : Hashtable.
/// </summary>
[Test]
public void TestExecuteQueryForMap()
{
IDictionary map = sqlMap.QueryForMap("GetAllAccountsViaResultClass", null, "FirstName");
Assert.AreEqual(5, map.Count);
AssertAccount1(((Account) map["Joe"]));
Assert.AreEqual(1, ((Account) map["Joe"]).Id);
Assert.AreEqual(2, ((Account) map["Averel"]).Id);
Assert.AreEqual(3, ((Account) map["William"]).Id);
Assert.AreEqual(4, ((Account) map["Jack"]).Id);
Assert.AreEqual(5, ((Account) map["Gilles"]).Id);
}
/// <summary>
/// Test ExecuteQueryForMap : Hashtable.
/// </summary>
/// <remarks>
/// If the keyProperty is an integer, you must acces the map
/// by map[integer] and not by map["integer"]
/// </remarks>
[Test]
public void TestExecuteQueryForMap2()
{
IDictionary map = sqlMap.QueryForMap("GetAllOrderWithLineItems", null, "PostalCode");
Assert.AreEqual(11, map.Count);
Order order = ((Order) map["T4H 9G4"]);
Assert.AreEqual(2, order.LineItemsIList.Count);
}
/// <summary>
/// Test ExecuteQueryForMap with value property :
/// "FirstName" as key, "EmailAddress" as value
/// </summary>
[Test]
public void TestExecuteQueryForMapWithValueProperty()
{
IDictionary map = sqlMap.QueryForMap("GetAllAccountsViaResultClass", null, "FirstName", "EmailAddress");
Assert.AreEqual(5, map.Count);
Assert.AreEqual("Joe.Dalton@somewhere.com", map["Joe"]);
Assert.AreEqual("Averel.Dalton@somewhere.com", map["Averel"]);
Assert.IsNull(map["William"]);
Assert.AreEqual("Jack.Dalton@somewhere.com", map["Jack"]);
Assert.IsNull(map["Gilles"]);
}
/// <summary>
/// Test ExecuteQueryForWithJoined
/// </remarks>
[Test]
public void TestExecuteQueryForWithJoined()
{
Order order = sqlMap.QueryForObject("GetOrderJoinWithAccount",10) as Order;
Assert.IsNotNull(order.Account);
order = sqlMap.QueryForObject("GetOrderJoinWithAccount",11) as Order;
Assert.IsNull(order.Account);
}
/// <summary>
/// Test ExecuteQueryFor With Complex Joined
/// </summary>
/// <remarks>
/// A->B->C
/// ->E
/// ->F
/// </remarks>
[Test]
public void TestExecuteQueryForWithComplexJoined()
{
A a = sqlMap.QueryForObject("SelectComplexJoined",null) as A;
Assert.IsNotNull(a);
Assert.IsNotNull(a.B);
Assert.IsNotNull(a.B.C);
Assert.IsNull(a.B.D);
Assert.IsNotNull(a.E);
Assert.IsNull(a.F);
}
#endregion
#region Extends statement
/// <summary>
/// Test base Extends statement
/// </summary>
[Test]
public void TestExtendsGetAllAccounts()
{
IList list = sqlMap.QueryForList("GetAllAccounts", null);
AssertAccount1((Account) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(3, ((Account) list[2]).Id);
Assert.AreEqual(4, ((Account) list[3]).Id);
Assert.AreEqual(5, ((Account) list[4]).Id);
}
/// <summary>
/// Test Extends statement GetAllAccountsOrderByName extends GetAllAccounts
/// </summary>
[Test]
public void TestExtendsGetAllAccountsOrderByName()
{
IList list = sqlMap.QueryForList("GetAllAccountsOrderByName", null);
AssertAccount1((Account) list[3]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(2, ((Account) list[0]).Id);
Assert.AreEqual(5, ((Account) list[1]).Id);
Assert.AreEqual(4, ((Account) list[2]).Id);
Assert.AreEqual(1, ((Account) list[3]).Id);
Assert.AreEqual(3, ((Account) list[4]).Id);
}
/// <summary>
/// Test Extends statement GetOneAccount extends GetAllAccounts
/// </summary>
[Test]
public void TestExtendsGetOneAccount()
{
Account account = sqlMap.QueryForObject("GetOneAccount", 1) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test Extends statement GetSomeAccount extends GetAllAccounts
/// </summary>
[Test]
public void TestExtendsGetSomeAccount()
{
Hashtable param = new Hashtable();
param.Add("lowID", 2);
param.Add("hightID", 4);
IList list = sqlMap.QueryForList("GetSomeAccount", param);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(2, ((Account) list[0]).Id);
Assert.AreEqual(3, ((Account) list[1]).Id);
Assert.AreEqual(4, ((Account) list[2]).Id);
}
#endregion
#region Update tests
/// <summary>
/// Test Insert with post GeneratedKey
/// </summary>
[Test]
public void TestInsertPostKey()
{
LineItem item = new LineItem();
item.Id = 10;
item.Code = "blah";
item.Order = new Order();
item.Order.Id = 9;
item.Price = 44.00m;
item.Quantity = 1;
object key = sqlMap.Insert("InsertLineItemPostKey", item);
Assert.AreEqual(99, key);
Assert.AreEqual(99, item.Id);
Hashtable param = new Hashtable();
param.Add("Order_ID", 9);
param.Add("LineItem_ID", 10);
LineItem testItem = (LineItem) sqlMap.QueryForObject("GetSpecificLineItem", param);
Assert.IsNotNull(testItem);
Assert.AreEqual(10, testItem.Id);
}
/// <summary>
/// Test Insert pre GeneratedKey
/// </summary>
[Test]
public void TestInsertPreKey()
{
LineItem item = new LineItem();
item.Id = 10;
item.Code = "blah";
item.Order = new Order();
item.Order.Id = 9;
item.Price = 44.00m;
item.Quantity = 1;
object key = sqlMap.Insert("InsertLineItemPreKey", item);
Assert.AreEqual(99, key);
Assert.AreEqual(99, item.Id);
Hashtable param = new Hashtable();
param.Add("Order_ID", 9);
param.Add("LineItem_ID", 99);
LineItem testItem = (LineItem) sqlMap.QueryForObject("GetSpecificLineItem", param);
Assert.IsNotNull(testItem);
Assert.AreEqual(99, testItem.Id);
}
/// <summary>
/// Test Test Insert No Key
/// </summary>
[Test]
public void TestInsertNoKey()
{
LineItem item = new LineItem();
item.Id = 100;
item.Code = "blah";
item.Order = new Order();
item.Order.Id = 9;
item.Price = 44.00m;
item.Quantity = 1;
object key = sqlMap.Insert("InsertLineItemNoKey", item);
Assert.IsNull(key);
Assert.AreEqual(100, item.Id);
Hashtable param = new Hashtable();
param.Add("Order_ID", 9);
param.Add("LineItem_ID", 100);
LineItem testItem = (LineItem) sqlMap.QueryForObject("GetSpecificLineItem", param);
Assert.IsNotNull(testItem);
Assert.AreEqual(100, testItem.Id);
}
/// <summary>
/// Test Insert account via public fields
/// </summary>
[Ignore("No more supported")]
public void TestInsertAccountViaPublicFields()
{
AccountBis account = new AccountBis();
account.Id = 10;
account.FirstName = "Luky";
account.LastName = "Luke";
account.EmailAddress = "luly.luke@somewhere.com";
sqlMap.Insert("InsertAccountViaPublicFields", account);
Account testAccount = sqlMap.QueryForObject("GetAccountViaColumnName", 10) as Account;
Assert.IsNotNull(testAccount);
Assert.AreEqual(10, testAccount.Id);
}
public void TestInsertOrderViaProperties()
{
Account account = NewAccount6();
sqlMap.Insert("InsertAccountViaParameterMap", account);
Order order = new Order();
order.Id = 99;
order.CardExpiry = "09/11";
order.Account = account;
order.CardNumber = "154564656";
order.CardType = "Visa";
order.City = "Lyon";
order.Date = DateTime.Now;
order.PostalCode = "69004";
order.Province = "Rhone";
order.Street = "rue Durand";
sqlMap.Insert("InsertOrderViaPublicFields", order);
}
/// <summary>
/// Test Insert account via public fields
/// </summary>
public void TestInsertDynamic()
{
Account account = new Account();
account.Id = 10;
account.FirstName = "Luky";
account.LastName = "luke";
account.EmailAddress = null;
sqlMap.Insert("InsertAccountDynamic", account);
Account testAccount = sqlMap.QueryForObject("GetAccountViaColumnIndex", 10) as Account;
Assert.IsNotNull(testAccount);
Assert.AreEqual(10, testAccount.Id);
Assert.AreEqual("no_email@provided.com", testAccount.EmailAddress);
account.Id = 11;
account.FirstName = "Luky";
account.LastName = "luke";
account.EmailAddress = "luly.luke@somewhere.com";
sqlMap.Insert("InsertAccountDynamic", account);
testAccount = sqlMap.QueryForObject("GetAccountViaColumnIndex", 11) as Account;
Assert.IsNotNull(testAccount);
Assert.AreEqual(11, testAccount.Id);
Assert.AreEqual("luly.luke@somewhere.com", testAccount.EmailAddress);
}
/// <summary>
/// Test Insert account via inline parameters
/// </summary>
[Test]
public void TestInsertAccountViaInlineParameters()
{
Account account = new Account();
account.Id = 10;
account.FirstName = "Luky";
account.LastName = "Luke";
account.EmailAddress = "luly.luke@somewhere.com";
sqlMap.Insert("InsertAccountViaInlineParameters", account);
Account testAccount = sqlMap.QueryForObject("GetAccountViaColumnIndex", 10) as Account;
Assert.IsNotNull(testAccount);
Assert.AreEqual(10, testAccount.Id);
}
/// <summary>
/// Test Insert account via parameterMap
/// </summary>
[Test]
public void TestInsertAccountViaParameterMap()
{
Account account = NewAccount6();
sqlMap.Insert("InsertAccountViaParameterMap", account);
account = sqlMap.QueryForObject("GetAccountNullableEmail", 6) as Account;
AssertAccount6(account);
}
/// <summary>
/// Test Insert account via parameterMap
/// </summary>
[Test]
public void TestInsertEnumViaParameterMap()
{
Enumeration enumClass = new Enumeration();
enumClass.Id = 99;
enumClass.Day = Days.Thu;
enumClass.Color = Colors.Blue;
enumClass.Month = Months.May;
sqlMap.Insert("InsertEnumViaParameterMap", enumClass);
enumClass = null;
enumClass = sqlMap.QueryForObject("GetEnumeration", 99) as Enumeration;
Assert.AreEqual(enumClass.Day, Days.Thu);
Assert.AreEqual(enumClass.Color, Colors.Blue);
Assert.AreEqual(enumClass.Month, Months.May);
}
/// <summary>
/// Test Update via parameterMap
/// </summary>
[Test]
public void TestUpdateViaParameterMap()
{
Account account = (Account) sqlMap.QueryForObject("GetAccountViaColumnName", 1);
account.EmailAddress = "new@somewhere.com";
sqlMap.Update("UpdateAccountViaParameterMap", account);
account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
Assert.AreEqual("new@somewhere.com", account.EmailAddress);
}
/// <summary>
/// Test Update via parameterMap V2
/// </summary>
[Test]
public void TestUpdateViaParameterMap2()
{
Account account = (Account) sqlMap.QueryForObject("GetAccountViaColumnName", 1);
account.EmailAddress = "new@somewhere.com";
sqlMap.Update("UpdateAccountViaParameterMap2", account);
account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
Assert.AreEqual("new@somewhere.com", account.EmailAddress);
}
/// <summary>
/// Test Update with inline parameters
/// </summary>
[Test]
public void TestUpdateWithInlineParameters()
{
Account account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
account.EmailAddress = "new@somewhere.com";
sqlMap.Update("UpdateAccountViaInlineParameters", account);
account = (Account) sqlMap.QueryForObject("GetAccountViaColumnName", 1);
Assert.AreEqual("new@somewhere.com", account.EmailAddress);
}
/// <summary>
/// Test Execute Update With Parameter Class
/// </summary>
[Test]
public void TestExecuteUpdateWithParameterClass()
{
Account account = NewAccount6();
sqlMap.Insert("InsertAccountViaParameterMap", account);
bool checkForInvalidTypeFailedAppropriately = false;
try
{
sqlMap.Update("DeleteAccount", new object());
}
catch (IBatisNetException e)
{
Console.WriteLine("TestExecuteUpdateWithParameterClass :" + e.Message);
checkForInvalidTypeFailedAppropriately = true;
}
sqlMap.Update("DeleteAccount", account);
account = sqlMap.QueryForObject("GetAccountViaColumnName", 6) as Account;
Assert.IsNull(account);
Assert.IsTrue(checkForInvalidTypeFailedAppropriately);
}
/// <summary>
/// Test Execute Delete
/// </summary>
[Test]
public void TestExecuteDelete()
{
Account account = NewAccount6();
sqlMap.Insert("InsertAccountViaParameterMap", account);
account = null;
account = sqlMap.QueryForObject("GetAccountViaColumnName", 6) as Account;
Assert.IsTrue(account.Id == 6);
int rowNumber = sqlMap.Delete("DeleteAccount", account);
Assert.IsTrue(rowNumber == 1);
account = sqlMap.QueryForObject("GetAccountViaColumnName", 6) as Account;
Assert.IsNull(account);
}
/// <summary>
/// Test Execute Delete
/// </summary>
[Test]
public void TestDeleteWithComments()
{
int rowNumber = sqlMap.Delete("DeleteWithComments", null);
Assert.IsTrue(rowNumber == 4);
}
#endregion
#region Row delegate
private int _index = 0;
public void RowHandler(object obj, object paramterObject, IList list)
{
_index++;
Assert.AreEqual(_index, ((Account) obj).Id);
list.Add(obj);
}
#endregion
#region Tests using syntax
/// <summary>
/// Test Test Using syntax on sqlMap.OpenConnection
/// </summary>
[Test]
public void TestUsingConnection()
{
using (IDalSession session = sqlMap.OpenConnection())
{
Account account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
AssertAccount1(account);
} // compiler will call Dispose on SqlMapSession
}
/// <summary>
/// Test Using syntax on sqlMap.BeginTransaction
/// </summary>
[Test]
public void TestUsingTransaction()
{
using (IDalSession session = sqlMap.BeginTransaction())
{
Account account = (Account) sqlMap.QueryForObject("GetAccountViaColumnName", 1);
account.EmailAddress = "new@somewhere.com";
sqlMap.Update("UpdateAccountViaParameterMap", account);
account = sqlMap.QueryForObject("GetAccountViaColumnName", 1) as Account;
Assert.AreEqual("new@somewhere.com", account.EmailAddress);
session.Complete(); // Commit
} // compiler will call Dispose on SqlMapSession
}
#endregion
#region JIRA Tests
/// <summary>
/// Test JIRA 30 (repeating property)
/// </summary>
[Test]
public void TestJIRA30()
{
Account account = new Account();
account.Id = 1;
account.FirstName = "Joe";
account.LastName = "Dalton";
account.EmailAddress = "Joe.Dalton@somewhere.com";
Account result = sqlMap.QueryForObject("GetAccountWithRepeatingProperty", account) as Account;
AssertAccount1(result);
}
/// <summary>
/// Test Bit column
/// </summary>
[Test]
public void TestJIRA42()
{
Other other = new Other();
other.Int = 100;
other.Bool = true;
other.Long = 789456321;
sqlMap.Insert("InsertBool", other);
}
/// <summary>
/// Test for access a result map in a different namespace
/// </summary>
[Test]
public void TestJIRA45()
{
Account account = sqlMap.QueryForObject("GetAccountJIRA45", 1) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test : Whitespace is not maintained properly when CDATA tags are used
/// </summary>
[Test]
public void TestJIRA110()
{
Account account = sqlMap.QueryForObject("Get1Account", null) as Account;
AssertAccount1(account);
}
/// <summary>
/// Test : Whitespace is not maintained properly when CDATA tags are used
/// </summary>
[Test]
public void TestJIRA110Bis()
{
IList list = sqlMap.QueryForList("GetAccounts", null);
AssertAccount1((Account) list[0]);
Assert.AreEqual(5, list.Count);
}
/// <summary>
/// Test for cache stats only being calculated on CachingStatments
/// </summary>
[Test]
public void TestJIRA113()
{
sqlMap.FlushCaches();
// taken from TestFlushDataCache()
// first query is not cached, second query is: 50% cache hit
IList list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null);
int firstId = HashCodeProvider.GetIdentityHashCode(list);
list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null);
int secondId = HashCodeProvider.GetIdentityHashCode(list);
Assert.AreEqual(firstId, secondId);
string cacheStats = sqlMap.GetDataCacheStats();
Assert.IsNotNull(cacheStats);
}
#endregion
#region CustomTypeHandler tests
/// <summary>
/// Test CustomTypeHandler
/// </summary>
[Test]
public void TestExecuteQueryWithCustomTypeHandler()
{
IList list = sqlMap.QueryForList("GetAllAccountsViaCustomTypeHandler", null);
AssertAccount1((Account) list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, ((Account) list[0]).Id);
Assert.AreEqual(2, ((Account) list[1]).Id);
Assert.AreEqual(3, ((Account) list[2]).Id);
Assert.AreEqual(4, ((Account) list[3]).Id);
Assert.AreEqual(5, ((Account) list[4]).Id);
Assert.IsFalse(((Account) list[0]).CartOption);
Assert.IsFalse(((Account) list[1]).CartOption);
Assert.IsTrue(((Account) list[2]).CartOption);
Assert.IsTrue(((Account) list[3]).CartOption);
Assert.IsTrue(((Account) list[4]).CartOption);
Assert.IsTrue(((Account) list[0]).BannerOption);
Assert.IsTrue(((Account) list[1]).BannerOption);
Assert.IsFalse(((Account) list[2]).BannerOption);
Assert.IsFalse(((Account) list[3]).BannerOption);
Assert.IsTrue(((Account) list[4]).BannerOption);
}
/// <summary>
/// Test CustomTypeHandler Oui/Non
/// </summary>
[Test]
public void TestCustomTypeHandler()
{
Other other = new Other();
other.Int = 99;
other.Long = 1966;
other.Bool = true;
other.Bool2 = false;
sqlMap.Insert("InsertCustomTypeHandler", other);
Other anOther = sqlMap.QueryForObject("SelectByInt", 99) as Other;
Assert.IsNotNull( anOther );
Assert.AreEqual(99, anOther.Int);
Assert.AreEqual(1966, anOther.Long);
Assert.AreEqual(true, anOther.Bool);
Assert.AreEqual(false, anOther.Bool2);
}
#endregion
}
}
| |
namespace Gu.Wpf.Geometry
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
/// <summary>
/// A rectangular balloon.
/// </summary>
public class BoxBalloon : BalloonBase
{
/// <summary>Identifies the <see cref="CornerRadius"/> dependency property.</summary>
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
nameof(CornerRadius),
typeof(CornerRadius),
typeof(BoxBalloon),
new FrameworkPropertyMetadata(
default(CornerRadius),
FrameworkPropertyMetadataOptions.AffectsRender,
OnCornerRadiusChanged));
private static readonly DependencyProperty RectProperty = DependencyProperty.Register(
"Rect",
typeof(Rect),
typeof(BoxBalloon),
new PropertyMetadata(Rect.Empty));
/// <summary>
/// Gets or sets the <see cref="CornerRadius"/> that allows users to control the roundness of the corners independently by
/// setting a radius value for each corner. Radius values that are too large are scaled so that they
/// smoothly blend from corner to corner.
/// </summary>
public CornerRadius CornerRadius
{
get => (CornerRadius)this.GetValue(CornerRadiusProperty);
set => this.SetValue(CornerRadiusProperty, value);
}
/// <inheritdoc/>
protected override Geometry GetOrCreateBoxGeometry(Size renderSize)
{
var rect = new Rect(new Point(0, 0), renderSize);
this.SetCurrentValue(RectProperty, rect);
if (rect.Width <= 0 || rect.Height <= 0)
{
return Geometry.Empty;
}
if (this.CornerRadius.IsAllEqual())
{
// using TopLeft here as we have already checked that they are equal
if (this.BoxGeometry is RectangleGeometry)
{
return this.BoxGeometry;
}
var geometry = new RectangleGeometry();
_ = geometry.Bind(RectangleGeometry.RectProperty)
.OneWayTo(this, RectProperty);
_ = geometry.Bind(RectangleGeometry.RadiusXProperty)
.OneWayTo(this, CornerRadiusProperty, CornerRadiusTopLeftConverter.Default);
_ = geometry.Bind(RectangleGeometry.RadiusYProperty)
.OneWayTo(this, CornerRadiusProperty, CornerRadiusTopLeftConverter.Default);
return geometry;
}
else
{
var geometry = new StreamGeometry();
using (var context = geometry.Open())
{
var cr = this.AdjustedCornerRadius();
var p = cr.TopLeft > 0
? new Point(cr.TopLeft + (this.StrokeThickness / 2), this.StrokeThickness / 2)
: new Point(this.StrokeThickness / 2, this.StrokeThickness / 2);
context.BeginFigure(p, isFilled: true, isClosed: true);
p = p.WithOffset(rect.Width - cr.TopLeft - cr.TopRight, 0);
context.LineTo(p, isStroked: true, isSmoothJoin: true);
p = context.DrawCorner(p, cr.TopRight, cr.TopRight);
p = p.WithOffset(0, rect.Height - cr.TopRight - cr.BottomRight);
context.LineTo(p, isStroked: true, isSmoothJoin: true);
p = context.DrawCorner(p, -cr.BottomRight, cr.BottomRight);
p = p.WithOffset(-rect.Width + cr.BottomRight + cr.BottomLeft, 0);
context.LineTo(p, isStroked: true, isSmoothJoin: true);
p = context.DrawCorner(p, -cr.BottomLeft, -cr.BottomLeft);
p = p.WithOffset(0, -rect.Height + cr.TopLeft + cr.BottomLeft);
context.LineTo(p, isStroked: true, isSmoothJoin: true);
_ = context.DrawCorner(p, cr.TopLeft, -cr.TopLeft);
}
geometry.Freeze();
return geometry;
}
}
/// <inheritdoc/>
protected override Geometry GetOrCreateConnectorGeometry(Size renderSize)
{
var rectangle = new Rect(new Point(0, 0), renderSize);
if (rectangle.Width <= 0 || rectangle.Height <= 0)
{
return Geometry.Empty;
}
var fromCenter = new Ray(rectangle.CenterPoint(), this.ConnectorOffset);
var ip = fromCenter.FirstIntersectionWith(rectangle);
if (ip is null)
{
Debug.Assert(condition: false, message: $"Line {fromCenter} does not intersect rectangle {rectangle}");
// ReSharper disable once HeuristicUnreachableCode
return Geometry.Empty;
}
var cr = this.AdjustedCornerRadius();
var vertexPoint = ip.Value + this.ConnectorOffset;
var toCenter = new Ray(vertexPoint, this.ConnectorOffset.Negated());
var p1 = ConnectorPoint.Find(toCenter, this.ConnectorAngle / 2, this.StrokeThickness, rectangle, cr);
var p2 = ConnectorPoint.Find(toCenter, -this.ConnectorAngle / 2, this.StrokeThickness, rectangle, cr);
this.SetCurrentValue(ConnectorVertexPointProperty, vertexPoint);
this.SetCurrentValue(ConnectorPoint1Property, p1);
this.SetCurrentValue(ConnectorPoint2Property, p2);
if (this.ConnectorGeometry is PathGeometry)
{
return this.ConnectorGeometry;
}
var figure = this.CreatePathFigureStartingAt(ConnectorPoint1Property);
figure.Segments.Add(this.CreateLineSegmentTo(ConnectorVertexPointProperty));
figure.Segments.Add(this.CreateLineSegmentTo(ConnectorPoint2Property));
var geometry = new PathGeometry();
geometry.Figures.Add(figure);
return geometry;
}
/// <summary>
/// Calculates the adjusted corner radius.
/// </summary>
/// <returns>A <see cref="CornerRadius"/>.</returns>
protected virtual CornerRadius AdjustedCornerRadius()
{
var cr = this.CornerRadius;
var left = cr.TopLeft + cr.BottomLeft;
var right = cr.TopRight + cr.BottomRight;
var top = cr.TopLeft + cr.TopRight;
var bottom = cr.BottomLeft + cr.BottomRight;
if (left < this.ActualHeight &&
right < this.ActualHeight &&
top < this.ActualWidth &&
bottom < this.ActualWidth)
{
return cr;
}
var factor = Math.Min(
Math.Min(this.ActualWidth / top, this.ActualWidth / bottom),
Math.Min(this.ActualHeight / left, this.ActualHeight / right));
return cr.ScaleBy(factor);
}
private static void OnCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var balloon = (BoxBalloon)d;
if (balloon.IsInitialized)
{
balloon.UpdateCachedGeometries();
}
}
private PathFigure CreatePathFigureStartingAt(DependencyProperty property)
{
var figure = new PathFigure { IsClosed = true };
_ = figure.Bind(PathFigure.StartPointProperty)
.OneWayTo(this, property);
return figure;
}
private LineSegment CreateLineSegmentTo(DependencyProperty property)
{
var lineSegment = new LineSegment { IsStroked = true };
_ = lineSegment.Bind(LineSegment.PointProperty)
.OneWayTo(this, property);
return lineSegment;
}
private static class ConnectorPoint
{
internal static Point Find(Ray toCenter, double angle, double strokeThickness, Rect rectangle, CornerRadius cornerRadius)
{
var rotated = toCenter.Rotate(angle);
return FindForRotated(rotated, strokeThickness, rectangle, cornerRadius);
}
private static Point FindForRotated(Ray ray, double strokeThickness, Rect rectangle, CornerRadius cornerRadius)
{
var ip = ray.FirstIntersectionWith(rectangle);
if (ip is null)
{
return FindTangentPoint(ray, rectangle, cornerRadius);
}
if (TryGetCorner(ip.Value, rectangle, cornerRadius, out var corner))
{
ip = ray.FirstIntersectionWith(corner);
if (ip is null)
{
return FindTangentPoint(ray, rectangle, cornerRadius);
}
return ip.Value + (strokeThickness * ray.Direction);
}
return ip.Value + (strokeThickness * ray.Direction);
}
private static bool TryGetCorner(Point intersectionPoint, Rect rectangle, CornerRadius cornerRadius, out Circle corner)
{
return TryGetCorner(intersectionPoint, rectangle.TopLeft, cornerRadius.TopLeft, CreateTopLeft, out corner) ||
TryGetCorner(intersectionPoint, rectangle.TopRight, cornerRadius.TopRight, CreateTopRight, out corner) ||
TryGetCorner(intersectionPoint, rectangle.BottomRight, cornerRadius.BottomRight, CreateBottomRight, out corner) ||
TryGetCorner(intersectionPoint, rectangle.BottomLeft, cornerRadius.BottomLeft, CreateBottomLeft, out corner);
}
private static bool TryGetCorner(Point intersectionPoint, Point cornerPoint, double radius, Func<Point, double, Circle> factory, out Circle corner)
{
if (intersectionPoint.DistanceTo(cornerPoint) < radius)
{
corner = factory(cornerPoint, radius);
return true;
}
corner = default;
return false;
}
private static Point FindTangentPoint(Ray ray, Rect rectangle, CornerRadius cornerRadius)
{
var toMid = ray.PerpendicularLineTo(rectangle.CenterPoint());
Debug.Assert(toMid != null, "Cannot find tangent if line goes through center");
//// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (toMid is null)
{
// failing silently in release
return rectangle.CenterPoint();
}
// Debug.Assert(!rectangle.Contains(toMid.Value.StartPoint), "Cannot find tangent if line intersects rectangle");
if (toMid.Value.Direction.Axis() != null)
{
return ray.Point.Closest(rectangle.TopLeft, rectangle.TopRight, rectangle.BottomRight, rectangle.BottomLeft);
}
var corner = toMid.Value.Direction.Quadrant() switch
{
Quadrant.NegativeXPositiveY => CreateTopRight(rectangle.TopRight, cornerRadius.TopRight),
Quadrant.PositiveXPositiveY => CreateTopLeft(rectangle.TopLeft, cornerRadius.TopLeft),
Quadrant.PositiveXNegativeY => CreateBottomLeft(rectangle.BottomLeft, cornerRadius.BottomLeft),
Quadrant.NegativeXNegativeY => CreateBottomRight(rectangle.BottomRight, cornerRadius.BottomRight),
_ => throw new InvalidEnumArgumentException("Unhandled quadrant."),
};
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (corner.Radius == 0)
{
return corner.Center;
}
var lineToCenter = ray.PerpendicularLineTo(corner.Center);
Debug.Assert(lineToCenter != null, "Ray cannot go through center here");
//// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (lineToCenter is null)
{
// this should never happen but failing silently
// the balloons should not throw much.
return corner.Center;
}
return corner.Center - (corner.Radius * lineToCenter.Value.Direction);
}
private static Circle CreateTopLeft(Point p, double r) => new Circle(p.WithOffset(r, r), r);
private static Circle CreateTopRight(Point p, double r) => new Circle(p.WithOffset(-r, r), r);
private static Circle CreateBottomRight(Point p, double r) => new Circle(p.WithOffset(-r, -r), r);
private static Circle CreateBottomLeft(Point p, double r) => new Circle(p.WithOffset(r, -r), r);
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dataproc.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBatchControllerClientTest
{
[xunit::FactAttribute]
public void GetBatchRequestObject()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchRequestObjectAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBatch()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetBatchResourceNames()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch response = client.GetBatch(request.BatchName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetBatchResourceNamesAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetBatchRequest request = new GetBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
Batch expectedResponse = new Batch
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
Uuid = "uuid6f877cef",
CreateTime = new wkt::Timestamp(),
PysparkBatch = new PySparkBatch(),
SparkBatch = new SparkBatch(),
SparkRBatch = new SparkRBatch(),
SparkSqlBatch = new SparkSqlBatch(),
RuntimeInfo = new RuntimeInfo(),
State = Batch.Types.State.Failed,
StateMessage = "state_message46cf28c0",
StateTime = new wkt::Timestamp(),
Creator = "creator253324ee",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
RuntimeConfig = new RuntimeConfig(),
EnvironmentConfig = new EnvironmentConfig(),
Operation = "operation615a23f7",
StateHistory =
{
new Batch.Types.StateHistory(),
},
};
mockGrpcClient.Setup(x => x.GetBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Batch>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
Batch responseCallSettings = await client.GetBatchAsync(request.BatchName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Batch responseCancellationToken = await client.GetBatchAsync(request.BatchName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatchRequestObject()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchRequestObjectAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatch()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteBatchResourceNames()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteBatch(request.BatchName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteBatchResourceNamesAsync()
{
moq::Mock<BatchController.BatchControllerClient> mockGrpcClient = new moq::Mock<BatchController.BatchControllerClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteBatchRequest request = new DeleteBatchRequest
{
BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteBatchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BatchControllerClient client = new BatchControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteBatchAsync(request.BatchName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteBatchAsync(request.BatchName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
namespace Tools
{
/// <exclude/>
public abstract class LNode
{
/// <exclude/>
public int m_state;
#if (GENTIME)
/// <exclude/>
public TokensGen m_tks;
/// <exclude/>
public LNode(TokensGen tks)
{
m_tks = tks;
m_state = tks.NewState();
}
#endif
/// <exclude/>
protected LNode() {}
}
/// <exclude/>
public class TokClassDef
{
#if (GENTIME)
/// <exclude/>
public string m_refToken = "";
/// <exclude/>
public string m_initialisation = "";
/// <exclude/>
public string m_implement = "";
/// <exclude/>
public TokClassDef(GenBase gbs,string name,string bas)
{
if (gbs is TokensGen)
{
TokensGen tks = (TokensGen) gbs;
m_name = name;
tks.m_tokens.tokens[name] = this;
m_refToken = bas;
}
m_yynum = ++gbs.LastSymbol;
}
#endif
/// <exclude/>
TokClassDef() {}
/// <exclude/>
public string m_name = "";
/// <exclude/>
public int m_yynum = 0;
/// <exclude/>
public static object Serialise(object o,Serialiser s)
{
if (s==null)
return new TokClassDef();
TokClassDef t = (TokClassDef)o;
if (s.Encode)
{
s.Serialise(t.m_name);
s.Serialise(t.m_yynum);
return null;
}
t.m_name = (string)s.Deserialise();
t.m_yynum = (int)s.Deserialise();
return t;
}
}
/// <exclude/>
public class Dfa : LNode
{
/// <exclude/>
Dfa() {}
#if (GENTIME)
/// <exclude/>
public Dfa(TokensGen tks) : base(tks)
{
m_tokens = tks.m_tokens;
}
#endif
/// <exclude/>
YyLexer m_tokens = null;
/// <exclude/>
public static void SetTokens(YyLexer tks, Hashtable h) // needed after deserialisation
{
foreach (Dfa v in h.Values)
{
if (v.m_tokens!=null)
continue;
v.m_tokens = tks;
Dfa.SetTokens(tks,v.m_map);
}
}
/// <exclude/>
public Hashtable m_map = new Hashtable(); // char->Dfa: arcs leaving this node
/// <exclude/>
public class Action
{
/// <exclude/>
public int a_act;
/// <exclude/>
public Action a_next;
/// <exclude/>
public Action(int act,Action next) { a_act = act; a_next = next; }
Action() {}
/// <exclude/>
public static object Serialise(object o,Serialiser s)
{
if (s==null)
return new Action();
Action a = (Action)o;
if (s.Encode)
{
s.Serialise(a.a_act);
s.Serialise(a.a_next);
return null;
}
a.a_act = (int)s.Deserialise();
a.a_next = (Action)s.Deserialise();
return a;
}
}
/// <exclude/>
public string m_tokClass = ""; // token class name if m_actions!=null
/// <exclude/>
public Action m_actions = null; // for old-style REJECT
/// <exclude/>
public int m_reswds = -1; // 4.7 for ResWds handling
#if (GENTIME)
/// <exclude/>
void AddAction(int act)
{
Action a = new Action(act,m_actions);
m_actions = a;
}
/// <exclude/>
void MakeLastAction(int act)
{
while (m_actions!=null && m_actions.a_act>=act)
m_actions = m_actions.a_next;
AddAction(act);
}
/// <exclude/>
public Dfa(Nfa nfa):base(nfa.m_tks)
{
m_tokens = m_tks.m_tokens;
AddNfaNode(nfa); // the starting node is Closure(start)
Closure();
AddActions(); // recursively build the Dfa
}
/// <exclude/>
internal bool AddNfaNode(NfaNode nfa)
{
if (!m_nfa.Add(nfa))
return false;
if (nfa.m_sTerminal!="")
{
int qi,n=0;
string tokClass = "";
string p=nfa.m_sTerminal;
if (p[0]=='%')
{ // check for %Tokname special action
for (n=0,qi=1;qi<p.Length;qi++,n++) // extract the class name
if (p[qi]==' '||p[qi]=='\t'||p[qi]=='\n'||p[qi]=='{'||p[qi]==':')
break;
tokClass = nfa.m_sTerminal.Substring(1,n);
}
// check for ResWds machinery // 4.7
if (n>0 && n+1<p.Length)
{
string st = nfa.m_sTerminal.Substring(n+1).Trim();
if (st.Length>0) {
if (st.StartsWith("%except"))
{
m_reswds = nfa.m_state;
m_tks.m_tokens.reswds[nfa.m_state] = ResWds.New(m_tks,st.Substring(7));
}
}
}
// special action is always last in the list
if (tokClass=="")
{ //nfa has an old action
if (m_tokClass=="" // if both are old-style
|| // or we have a special action that is later
(m_actions.a_act)>nfa.m_state) // m_actions has at least one entry
AddAction(nfa.m_state);
// else we have a higher-precedence special action so we do nothing
}
else if (m_actions==null || m_actions.a_act>nfa.m_state)
{
MakeLastAction(nfa.m_state);
m_tokClass = tokClass;
} // else we have a higher-precedence special action so we do nothing
}
return true;
}
/// <exclude/>
internal NList m_nfa = new NList(); // nfa nodes in m_state order
/// <exclude/>
internal void AddActions()
{
// This routine is called for a new DFA node
m_tks.states.Add(this);
// Follow all the arcs from here
foreach (Charset cs in m_tks.m_tokens.cats.Values)
foreach (char j in cs.m_chars.Keys)
{
Dfa dfa = Target(j);
if (dfa!=null)
m_map[j] = dfa;
}
}
/// <exclude/>
internal Dfa Target(char ch)
{ // construct or lookup the target for a new arc
Dfa n = new Dfa(m_tks);
for (NList pos = m_nfa; !pos.AtEnd; pos=pos.m_next)
pos.m_node.AddTarget(ch,n);
// check we actually got something
if (n.m_nfa.AtEnd)
return null;
n.Closure();
// now check we haven't got it already
for (int pos1=0;pos1<m_tks.states.Count;pos1++)
if (((Dfa)m_tks.states[pos1]).SameAs(n))
return (Dfa)m_tks.states[pos1];
// this is a brand new Dfa node so recursively build it
n.AddActions();
return n;
}
/// <exclude/>
void Closure()
{
for (NList pos=m_nfa; !pos.AtEnd; pos=pos.m_next)
ClosureAdd(pos.m_node);
}
/// <exclude/>
void ClosureAdd(NfaNode nfa)
{
for (int pos=0;pos<nfa.m_eps.Count;pos++)
{
NfaNode p = (NfaNode)nfa.m_eps[pos];
if (AddNfaNode(p))
ClosureAdd(p);
}
}
/// <exclude/>
internal bool SameAs(Dfa dfa)
{
NList pos1 = m_nfa;
NList pos2 = dfa.m_nfa;
while (pos1.m_node==pos2.m_node && !pos1.AtEnd)
{
pos1 = pos1.m_next;
pos2 = pos2.m_next;
}
return pos1.m_node==pos2.m_node;
}
/// <exclude/>
// match a Dfa agsint a given string
public int Match(string str,int ix,ref int action)
{ // return number of chars matched
int r=0;
Dfa dfa=null;
// if there is no arc or the string is exhausted, this is okay at a terminal
if (ix>=str.Length ||
(dfa=((Dfa)m_map[m_tokens.Filter(str[ix])]))==null ||
(r=dfa.Match(str,ix+1,ref action))<0)
{
if (m_actions!=null)
{
action = m_actions.a_act;
return 0;
}
return -1;
}
return r+1;
}
/// <exclude/>
public void Print()
{
Console.Write("{0}:",m_state);
if (m_actions!=null)
{
Console.Write(" (");
for (Action a = m_actions; a!=null; a=a.a_next)
Console.Write("{0} <",a.a_act);
if (m_tokClass!="")
Console.Write(m_tokClass);
Console.Write(">)");
}
Console.WriteLine();
Hashtable amap = new Hashtable(); // char->bool
IDictionaryEnumerator idx = m_map.GetEnumerator();
for (int count=m_map.Count; count-->0;)
{
idx.MoveNext();
char j = (char)idx.Key;
Dfa pD = (Dfa)idx.Value;
if (!amap.Contains(j))
{
amap[j] = true;
Console.Write(" {0} ",pD.m_state);
int ij = (int)j;
if (ij>=32 && ij<128)
Console.Write(j);
else
Console.Write(" #{0} ",ij);
IDictionaryEnumerator idy = m_map.GetEnumerator();
for (;;)
{
idy.MoveNext();
Dfa pD1 = (Dfa)idy.Value;
if (pD1==pD)
break;
}
for (int count1=count;count1>0;count1--)
{
idy.MoveNext();
j = (char)idy.Key;
Dfa pD1 = (Dfa)idy.Value;
if (pD==pD1)
{
amap[j]=true;
ij = (int)j;
if (ij>=32 && ij<128)
Console.Write(j);
else
Console.Write(" #{0} ",ij);
}
}
Console.WriteLine();
}
}
}
#endif
/// <exclude/>
public static object Serialise(object o,Serialiser s)
{
if (s==null)
return new Dfa();
Dfa d = (Dfa)o;
if (s.Encode)
{
s.Serialise(d.m_state);
s.Serialise(d.m_map);
s.Serialise(d.m_actions);
s.Serialise(d.m_tokClass);
s.Serialise(d.m_reswds);
return null;
}
d.m_state = (int)s.Deserialise();
d.m_map = (Hashtable)s.Deserialise();
d.m_actions = (Action)s.Deserialise();
d.m_tokClass = (string)s.Deserialise();
d.m_reswds = (int)s.Deserialise();
return d;
}
}
#if (GENTIME)
/// <exclude/>
public class Regex
{
/*
Construct a Regex from a given string
1. First examine the given string.
If it is empty, there is nothing to do, so return (having cleared m_sub as a precaution).
2. Look to see if the string begins with a bracket ( . If so, find the matching ) .
This is not as simple as it might be because )s inside quotes or [] or escaped will not count.
Recursively call the constructor for the regular expression between the () s.
Mark everything up to the ) as used, and go to step 9.
3. Look to see if the string begins with a bracket [ . If so, find the matching ] , watching for escapes.
Construct a ReRange for everything between the []s.
Mark everything up to the ] as used, and go to step 9.
4. Look to see if the string begins with a ' or " . If so, build the contents interpreting
escaped special characters correctly, until the matching quote is reached.
Construct a ReStr for the contents, mark everything up to the final quote as used, and go to step 9.
4a. Look to see if the string begins with a U' or U" . If so, build the contents interpreting
escaped special characters correctly, until the matching quote is reached.
Construct a ReUStr for the contents, mark everything up to the final quote as used, and go to step 9.
5. Look to see if the string begins with a \ .
If so, build a ReStr for the next character (special action for ntr),
mark it as used, and go to step 9.
6. Look to see if the string begins with a { .
If so, find the matching }, lookup the symbolic name in the definitions table,
recursively call this constructor on the contents,
mark everything up to the } as used, and go to step 9.
7. Look to see if the string begins with a dot.
If so, construct a ReRange("^\n"), mark the . as used, and go to step 9.
8. At this point we conclude that there is a simple character at the start of the regular expression.
Construct a ReStr for it, mark it as used, and go to step 9.
9. If the string is exhausted, return.
We have a simple Regex whose m_sub contains what we can constructed.
10. If the next character is a ? , *, or +, construct a ReOpt, ReStart, or RePlus respectively
out of m_sub, and make m_sub point to this new class instead. Mark the character as used.
11. If the string is exhausted, return.
12. If the next character is a | , build a ReAlt using the m_sub we have and the rest of the string.
13. Otherwise build a ReCat using the m_sub we have and the rest of the string.
*/
/// <exclude/>
public Regex(TokensGen tks,int p,string str)
{
int n = str.Length;
int nlp = 0;
int lbrack = 0;
int quote = 0;
int j;
char ch;
//1. First examine the given string.
// If it is empty, there is nothing to do, so return (having cleared m_sub as a precaution).
m_sub = null;
if (n==0)
return;
//2. Look to see if the string begins with a bracket ( . If so, find the matching ) .
// This is not as simple as it might be because )s inside quotes or [] or escaped will not count.
// Recursively call the constructor for the regular expression between the () s.
// Mark everything up to the ) as used, and go to step 9.
else if (str[0]=='(')
{ // identify a bracketed expression
for (j=1;j<n;j++)
if (str[j]=='\\')
j++;
else if (str[j]=='[' && quote==0 && lbrack==0)
lbrack++;
else if (str[j]==']' && lbrack>0)
lbrack = 0;
else if (str[j]=='"' || str[j]=='\'')
{
if (quote==str[j])
quote = 0;
else if (quote==0)
quote = str[j];
}
else if (str[j]=='(' && quote==0 && lbrack==0)
nlp++;
else if (str[j]==')' && quote==0 && lbrack==0 && nlp--==0)
break;
if (j==n)
goto bad;
m_sub = new Regex (tks,p+1,str.Substring(1,j-1));
j++;
//3. Look to see if the string begins with a bracket [ . If so, find the matching ] , watching for escapes.
// Construct a ReRange for everything between the []s.
// Mark everything up to the ] as used, and go to step 9.
}
else if (str[0]=='[')
{ // range of characters
for (j=1;j<n && str[j]!=']';j++)
if (str[j]=='\\')
j++;
if (j==n)
goto bad;
m_sub = new ReRange(tks,str.Substring(0,j+1));
j++;
}
//4. Look to see if the string begins with a ' or " . If so, build the contents interpreting
// escaped special characters correctly, until the matching quote is reached.
// Construct a CReStr for the contents, mark everything up to the final quote as used, and go to step 9.
else if (str[0] == '\'' || str[0] == '"')
{ // quoted string needs special treatment
StringBuilder qs = new StringBuilder();
for (j=1;j<n && str[j]!=str[0];j++)
if (str[j]=='\\')
switch (str[++j])
{
case 'n': qs.Append('\n'); break;
case 'r': qs.Append('\r'); break;
case 't': qs.Append('\t'); break;
case '\\': qs.Append('\\'); break;
case '\'': qs.Append('\''); break;
case '"': qs.Append('"'); break;
case '\n': break;
default: qs.Append(str[j]); break;
}
else
qs.Append(str[j]);
if (j==n)
goto bad;
j++;
m_sub = new ReStr(tks,qs.ToString());
}
//4a. Look to see if the string begins with a U' or U" . If so, build the contents interpreting
// escaped special characters correctly, until the matching quote is reached.
// Construct a ReUStr for the contents, mark everything up to the final quote as used, and go to step 9.
else if (str.StartsWith("U\"")||str.StartsWith("U'"))
{ // quoted string needs special treatment
StringBuilder qs = new StringBuilder();
for (j=2;j<n && str[j]!=str[1];j++)
if (str[j]=='\\')
switch (str[++j])
{
case 'n': qs.Append('\n'); break;
case 'r': qs.Append('\r'); break;
case 't': qs.Append('\t'); break;
case '\\': qs.Append('\\'); break;
case '\'': qs.Append('\''); break;
case '"': qs.Append('"'); break;
case '\n': break;
default: qs.Append(str[j]); break;
}
else
qs.Append(str[j]);
if (j==n)
goto bad;
j++;
m_sub = new ReUStr(tks,qs.ToString());
}
//5. Look to see if the string begins with a \ .
// If so, build a ReStr for the next character (special action for ntr),
// mark it as used, and go to step 9.
else if (str[0]=='\\')
{
switch (ch = str[1])
{
case 'n': ch = '\n'; break;
case 't': ch = '\t'; break;
case 'r': ch = '\r'; break;
}
m_sub = new ReStr(tks,ch);
j = 2;
//6. Look to see if the string begins with a { .
// If so, find the matching }, lookup the symbolic name in the definitions table,
// recursively call this constructor on the contents,
// mark everything up to the } as used, and go to step 9.
}
else if (str[0]=='{')
{
for (j=1;j<n && str[j]!='}';j++)
;
if (j==n)
goto bad;
string ds = str.Substring(1,j-1);
string s = (string)tks.defines[ds];
if (s==null)
m_sub = new ReCategory(tks,ds);
else
m_sub = new Regex(tks,p+1,s);
j++;
}
else
{ // simple character at start of regular expression
//7. Look to see if the string begins with a dot.
// If so, construct a CReDot, mark the . as used, and go to step 9.
if (str[0]=='.')
m_sub = new ReRange(tks,"[^\n]");
//8. At this point we conclude that there is a simple character at the start of the regular expression.
// Construct a ReStr for it, mark it as used, and go to step 9.
else
m_sub = new ReStr(tks,str[0]);
j = 1;
}
//9. If the string is exhausted, return.
// We have a simple Regex whose m_sub contains what we can constructed.
if (j>=n)
return;
//10. If the next character is a ? , *, or +, construct a CReOpt, CReStart, or CRePlus respectively
// out of m_sub, and make m_sub point to this new class instead. Mark the character as used.
if (str[j]=='?')
{
m_sub = new ReOpt(m_sub);
j++;
}
else if (str[j]=='*')
{
m_sub = new ReStar(m_sub);
j++;
}
else if (str[j]=='+')
{
m_sub = new RePlus(m_sub);
j++;
}
// 11. If the string is exhausted, return.
if (j>=n)
return;
// 12. If the next character is a | , build a ReAlt using the m_sub we have and the rest of the string.
if (str[j]=='|')
m_sub = new ReAlt(tks,m_sub,p+j+1,str.Substring(j+1,n-j-1));
// 13. Otherwise build a ReCat using the m_sub we have and the rest of the string.
else if (j<n)
m_sub = new ReCat(tks,m_sub,p+j,str.Substring(j,n-j));
return;
bad:
tks.erh.Error(new CSToolsFatalException(1,tks.sourceLineInfo(p),str,"ill-formed regular expression "+str));
}
/// <exclude/>
protected Regex() {} // private
/// <exclude/>
public Regex m_sub;
/// <exclude/>
public virtual void Print(TextWriter s)
{
if (m_sub!=null)
m_sub.Print(s);
}
// Match(ch) is used only in arc handling for ReRange
/// <exclude/>
public virtual bool Match(char ch) { return false; }
// These two Match methods are only required if you want to use
// the Regex direcly for lexing. This is a very strange thing to do:
// it is non-deterministic and rather slow.
/// <exclude/>
public int Match(string str)
{
return Match(str,0,str.Length);
}
/// <exclude/>
public virtual int Match(string str,int pos,int max)
{
if (max<0)
return -1;
if (m_sub!=null)
return m_sub.Match(str,pos,max);
return 0;
}
/// <exclude/>
public virtual void Build(Nfa nfa)
{
if (m_sub!=null)
{
Nfa sub = new Nfa(nfa.m_tks,m_sub);
nfa.AddEps(sub);
sub.m_end.AddEps(nfa.m_end);
}
else
nfa.AddEps(nfa.m_end);
}
}
/// <exclude/>
internal class ReAlt : Regex
{
public ReAlt(TokensGen tks,Regex sub,int p,string str)
{
m_sub = sub;
m_alt = new Regex(tks,p,str);
}
public Regex m_alt;
public override void Print(TextWriter s)
{
s.Write("(");
if (m_sub!=null)
m_sub.Print(s);
s.Write("|");
if (m_alt!=null)
m_alt.Print(s);
s.Write(")");
}
/// <exclude/>
public override int Match(string str, int pos, int max)
{
int a= -1, b= -1;
if (m_sub!=null)
a = m_sub.Match(str, pos, max);
if (m_alt!=null)
b = m_sub.Match(str, pos, max);
return (a>b)?a:b;
}
/// <exclude/>
public override void Build(Nfa nfa)
{
if (m_alt!=null)
{
Nfa alt = new Nfa(nfa.m_tks,m_alt);
nfa.AddEps(alt);
alt.m_end.AddEps(nfa.m_end);
}
base.Build(nfa);
}
}
/// <exclude/>
internal class ReCat : Regex
{
/// <exclude/>
public ReCat(TokensGen tks,Regex sub, int p, string str)
{
m_sub = sub;
m_next = new Regex(tks,p,str);
}
/// <exclude/>
Regex m_next;
/// <exclude/>
public override void Print(TextWriter s)
{
s.Write("(");
if (m_sub!=null)
m_sub.Print(s);
s.Write(")(");
if (m_next!=null)
m_next.Print(s);
s.Write(")");
}
/// <exclude/>
public override int Match(string str, int pos, int max)
{
int first, a, b, r = -1;
if (m_next==null)
return base.Match(str,pos,max);
if (m_sub==null)
return m_next.Match(str,pos,max);
for (first = max;first>=0;first=a-1)
{
a = m_sub.Match(str,pos,first);
if (a<0)
break;
b = m_next.Match(str,pos+a,max);
if (b<0)
continue;
if (a+b>r)
r = a+b;
}
return r;
}
/// <exclude/>
public override void Build(Nfa nfa)
{
if (m_next!=null)
{
if (m_sub!=null)
{
Nfa first = new Nfa(nfa.m_tks,m_sub);
Nfa second = new Nfa(nfa.m_tks,m_next);
nfa.AddEps(first);
first.m_end.AddEps(second);
second.m_end.AddEps(nfa.m_end);
}
else
m_next.Build(nfa);
}
else
base.Build(nfa);
}
}
/// <exclude/>
internal class ReStr : Regex
{
/// <exclude/>
public ReStr() {}
/// <exclude/>
public ReStr(TokensGen tks,string str)
{
m_str = str;
for (int i=0;i<str.Length;i++)
tks.m_tokens.UsingChar(str[i]);
}
/// <exclude/>
public ReStr(TokensGen tks,char ch)
{
m_str = new string(ch,1);
tks.m_tokens.UsingChar(ch);
}
/// <exclude/>
public string m_str = "";
/// <exclude/>
public override void Print(TextWriter s)
{
s.Write(String.Format("(\"{0}\")",m_str));
}
/// <exclude/>
public override int Match(string str, int pos, int max)
{
int j,n = m_str.Length;
if (n>max)
return -1;
if (n>max-pos)
return -1;
for(j=0;j<n;j++)
if (str[j]!=m_str[j])
return -1;
return n;
}
/// <exclude/>
public override void Build(Nfa nfa)
{
int j,n = m_str.Length;
NfaNode p, pp = nfa;
for (j=0;j<n;pp = p,j++)
{
p = new NfaNode(nfa.m_tks);
pp.AddArc(m_str[j],p);
}
pp.AddEps(nfa.m_end);
}
}
/// <exclude/>
internal class ReUStr : ReStr
{
/// <exclude/>
public ReUStr(TokensGen tks,string str)
{
m_str = str;
for (int i=0;i<str.Length;i++)
{
tks.m_tokens.UsingChar(Char.ToLower(str[i]));
tks.m_tokens.UsingChar(Char.ToUpper(str[i]));
}
}
/// <exclude/>
public ReUStr(TokensGen tks,char ch)
{
m_str = new string(ch,1);
tks.m_tokens.UsingChar(Char.ToLower(ch));
tks.m_tokens.UsingChar(Char.ToUpper(ch));
}
/// <exclude/>
public override void Print(TextWriter s)
{
s.Write(String.Format("(U\"{0}\")",m_str));
}
/// <exclude/>
public override int Match(string str, int pos, int max)
{
int j,n = m_str.Length;
if (n>max)
return -1;
if (n>max-pos)
return -1;
for(j=0;j<n;j++)
if (Char.ToUpper(str[j])!=Char.ToUpper(m_str[j]))
return -1;
return n;
}
public override void Build(Nfa nfa)
{
int j,n = m_str.Length;
NfaNode p, pp = nfa;
for (j=0;j<n;pp = p,j++)
{
p = new NfaNode(nfa.m_tks);
pp.AddUArc(m_str[j],p);
}
pp.AddEps(nfa.m_end);
}
}
internal class ReCategory : Regex
{
public ReCategory(TokensGen tks,string str)
{
m_str = str;
m_test = tks.m_tokens.GetTest(str);
}
string m_str;
ChTest m_test;
public override bool Match(char ch) { return m_test(ch); }
public override void Print(TextWriter s)
{
s.WriteLine("{"+m_str+"}");
}
public override void Build(Nfa nfa)
{
nfa.AddArcEx(this,nfa.m_end);
}
}
internal class ReRange : Regex
{
public ReRange(TokensGen tks,string str)
{
StringBuilder ns = new StringBuilder();
int n = str.Length-1,v;
int p;
for (p=1;p<n;p++) // fix \ escapes
if (str[p] == '\\')
{
if (p+1<n)
p++;
if (str[p]>='0' && str[p]<='7')
{
for (v = str[p++]-'0';p<n && str[p]>='0' && str[p]<='7';p++)
v=v*8+str[p]-'0';
ns.Append((char)v);
}
else
switch(str[p])
{
case 'n' : ns.Append('\n'); break;
case 't' : ns.Append('\t'); break;
case 'r' : ns.Append('\r'); break;
default: ns.Append(str[p]); break;
}
}
else
ns.Append(str[p]);
n = ns.Length;
if (ns[0] == '^')
{// invert range
m_invert = true;
ns.Remove(0,1).Append((char)0).Append((char)0xFFFF);
}
for (p=0;p<n;p++)
if (p+1<n && ns[p+1]=='-')
{
for (v=ns[p];v<=ns[p+2];v++)
Set(tks,(char)v);
p += 2;
}
else
Set(tks,ns[p]);
}
public Hashtable m_map = new Hashtable(); // char->bool
public bool m_invert = false; // implement ^
public override void Print(TextWriter s)
{
s.Write("[");
if (m_invert)
s.Write("^");
foreach (char x in m_map.Keys)
s.Write(x);
s.Write("]");
}
void Set(TokensGen tks,char ch)
{
m_map[ch] = true;
tks.m_tokens.UsingChar(ch);
}
public override bool Match(char ch)
{
if (m_invert)
return !m_map.Contains(ch);
return m_map.Contains(ch);
}
public override int Match(string str, int pos, int max)
{
if (max<pos)
return -1;
return Match(str[pos])?1:-1;
}
public override void Build(Nfa nfa)
{
nfa.AddArcEx(this,nfa.m_end);
}
}
internal class ReOpt : Regex
{
public ReOpt(Regex sub) { m_sub = sub; }
public override void Print(TextWriter s)
{
m_sub.Print(s);
s.Write("?");
}
public override int Match(string str, int pos, int max)
{
int r;
r = m_sub.Match(str, pos, max);
if (r<0)
r = 0;
return r;
}
public override void Build(Nfa nfa)
{
nfa.AddEps(nfa.m_end);
base.Build(nfa);
}
}
internal class RePlus : Regex
{
public RePlus(Regex sub) {m_sub = sub; }
public override void Print(TextWriter s)
{
m_sub.Print(s);
s.Write("+");
}
public override int Match(string str, int pos, int max)
{
int n,r;
r = m_sub.Match(str, pos, max);
if (r<0)
return -1;
for (n=r;r>0;n+=r)
{
r = m_sub.Match(str, pos+n, max);
if (r<0)
break;
}
return n;
}
public override void Build(Nfa nfa)
{
base.Build(nfa);
nfa.m_end.AddEps(nfa);
}
}
internal class ReStar : Regex
{
public ReStar(Regex sub) {m_sub = sub; }
public override void Print(TextWriter s)
{
m_sub.Print(s);
s.Write("*");
}
public override int Match(string str, int pos, int max)
{
int n,r;
r = m_sub.Match(str,pos,max);
if (r<0)
return -1;
for (n=0;r>0;n+=r)
{
r = m_sub.Match(str, pos+n, max);
if (r<0)
break;
}
return n;
}
public override void Build(Nfa nfa)
{
Nfa sub = new Nfa(nfa.m_tks,m_sub);
nfa.AddEps(sub);
nfa.AddEps(nfa.m_end);
sub.m_end.AddEps(nfa);
}
}
/* The .NET Framework has its own Regex class which is an NFA recogniser
We don't want to use this for lexing because
it would be too slow (DFA is always faster)
programming in actions looks difficult
we want to explain the NFA->DFA algorithm to students
So in this project we are not using the Framework's Regex class but the one defined in regex.cs
*/
internal class Arc
{
public char m_ch;
public NfaNode m_next;
public Arc() {}
public Arc(char ch, NfaNode next) { m_ch=ch; m_next=next; }
public virtual bool Match(char ch)
{
return ch==m_ch;
}
public virtual void Print(TextWriter s)
{
s.WriteLine(String.Format(" {0} {1}",m_ch,m_next.m_state));
}
}
internal class ArcEx : Arc
{
public Regex m_ref;
public ArcEx(Regex re,NfaNode next) { m_ref=re; m_next=next; }
public override bool Match(char ch)
{
return m_ref.Match(ch);
}
public override void Print(TextWriter s)
{
s.Write(" ");
m_ref.Print(s);
s.WriteLine(m_next.m_state);
}
}
internal class UArc : Arc
{
public UArc() {}
public UArc(char ch,NfaNode next) : base(ch,next) {}
public override bool Match(char ch)
{
return Char.ToUpper(ch)==Char.ToUpper(m_ch);
}
public override void Print(TextWriter s)
{
s.WriteLine(String.Format(" U\'{0}\' {1}",m_ch,m_next.m_state));
}
}
/// <exclude/>
public class NfaNode : LNode
{
/// <exclude/>
public string m_sTerminal = ""; // or something for the Lexer
/// <exclude/>
public ObjectList m_arcs = new ObjectList(); // of Arc for labelled arcs
/// <exclude/>
public ObjectList m_eps = new ObjectList(); // of NfaNode for unlabelled arcs
/// <exclude/>
public NfaNode(TokensGen tks):base(tks) {}
// build helpers
/// <exclude/>
public void AddArc(char ch,NfaNode next)
{
m_arcs.Add(new Arc(ch,next));
}
/// <exclude/>
public void AddUArc(char ch,NfaNode next)
{
m_arcs.Add(new UArc(ch,next));
}
/// <exclude/>
public void AddArcEx(Regex re,NfaNode next)
{
m_arcs.Add(new ArcEx(re,next));
}
/// <exclude/>
public void AddEps(NfaNode next)
{
m_eps.Add(next);
}
// helper for building DFa
/// <exclude/>
public void AddTarget(char ch, Dfa next)
{
for (int j=0; j<m_arcs.Count; j++)
{
Arc a = (Arc)m_arcs[j];
if (a.Match(ch))
next.AddNfaNode(a.m_next);
}
}
}
// An NFA is defined by a start and end state
// Here we derive the Nfa from a NfaNode which acts as the start state
/// <exclude/>
public class Nfa : NfaNode
{
/// <exclude/>
public NfaNode m_end;
/// <exclude/>
public Nfa(TokensGen tks) : base(tks)
{
m_end = new NfaNode(m_tks);
}
// build an NFA for a given regular expression
/// <exclude/>
public Nfa(TokensGen tks,Regex re) : base(tks)
{
m_end = new NfaNode(tks);
re.Build(this);
}
}
// shame we have to do this ourselves, but SortedList doesn't allow incremental building of Dfas
internal class NList
{ // sorted List of NfaNode
public NfaNode m_node; // null for the sentinel
public NList m_next;
public NList() { m_node=null; m_next=null; } // sentinel only
NList(NfaNode nd,NList nx) { m_node=nd; m_next=nx; }
public bool Add(NfaNode n)
{
if (m_node==null)
{ // m_node==null iff m_next==null
m_next = new NList();
m_node = n;
}
else if (m_node.m_state < n.m_state)
{
m_next = new NList(m_node,m_next);
m_node = n;
}
else if (m_node.m_state == n.m_state)
return false; // Add fails, there already
else
return m_next.Add(n);
return true; // was added
}
public bool AtEnd { get { return m_node==null; } }
}
#endif
/// <exclude/>
public class ResWds
{
/// <exclude/>
public bool m_upper = false;
/// <exclude/>
public Hashtable m_wds = new Hashtable(); // string->string (token class name)
/// <exclude/>
public ResWds() {}
#if (GENTIME)
/// <exclude/>
public static ResWds New(TokensGen tks,string str)
{
ResWds r = new ResWds();
str = str.Trim();
if (str[0]=='U')
{
r.m_upper = true;
str = str.Substring(1).Trim();
}
if (str[0]!='{' || str[str.Length-1]!='}')
goto bad;
str = str.Substring(1,str.Length-2).Trim();
string[] wds = str.Split(',');
for (int j=0;j<wds.Length;j++)
{
string w = wds[j].Trim();
string a = w;
int i = w.IndexOf(' ');
if (i>0)
{
a = w.Substring(i).Trim();
w = w.Substring(0,i);
}
r.m_wds[w] = a;
if (tks.m_tokens.tokens[a]==null)
{
TokClassDef t = new TokClassDef(tks,a,"TOKEN");
tks.m_outFile.WriteLine("//%{0}+{1}",a,t.m_yynum);
tks.m_outFile.Write("public class {0} : TOKEN",a);
tks.m_outFile.WriteLine("{ public override string yyname { get { return \""+a+"\";}}");
tks.m_outFile.WriteLine("public override int yynum { get { return "+t.m_yynum+"; }}");
tks.m_outFile.WriteLine(" public "+a+"(Lexer yyl):base(yyl) {}}");
}
}
return r;
bad:
tks.m_tokens.erh.Error(new CSToolsException(47,"bad ResWds element"));
return null;
}
#endif
/// <exclude/>
public void Check(Lexer yyl,ref TOKEN tok)
{
string str = tok.yytext;
if (m_upper)
str = str.ToUpper();
object o = m_wds[str];
if (o==null)
return;
tok = (TOKEN)Tfactory.create((string)o,yyl);
}
/// <exclude/>
public static object Serialise(object o,Serialiser s)
{
if (s==null)
return new ResWds();
ResWds r = (ResWds)o;
if (s.Encode)
{
s.Serialise(r.m_upper);
s.Serialise(r.m_wds);
return null;
}
r.m_upper = (bool)s.Deserialise();
r.m_wds = (Hashtable)s.Deserialise();
return r;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2017 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Compatibility;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Used for resolving the type difference between objects.
/// </summary>
public class TypeNameDifferenceResolver
{
/// <summary>
/// Gets the shortened type name difference between <paramref name="expected"/> and <paramref name="actual"/>.
/// </summary>
/// <param name="expected">The expected object.</param>
/// <param name="actual">The actual object.</param>
/// <param name="expectedTypeShortened">Output of the unique type name for the expected object.</param>
/// <param name="actualTypeShortened">Output of the unique type name for actual object.</param>
public void ResolveTypeNameDifference(object expected, object actual, out string expectedTypeShortened, out string actualTypeShortened)
{
ResolveTypeNameDifference(expected.GetType(), actual.GetType(), out expectedTypeShortened, out actualTypeShortened);
}
/// <summary>
/// Gets the shortened type name difference between <paramref name="expected"/> and <paramref name="actual"/>.
/// </summary>
/// <param name="expected">The expected object <see cref="Type"/>.</param>
/// <param name="actual">The actual object <see cref="Type"/>.</param>
/// <param name="expectedTypeShortened">Output of the unique type name for the expected object.</param>
/// <param name="actualTypeShortened">Output of the unique type name for actual object.</param>
public void ResolveTypeNameDifference(Type expected, Type actual, out string expectedTypeShortened, out string actualTypeShortened)
{
if (IsTypeGeneric(expected) && IsTypeGeneric(actual))
{
string shortenedGenericTypeExpected, shortenedGenericTypeActual;
GetShortenedGenericTypes(expected, actual, out shortenedGenericTypeExpected, out shortenedGenericTypeActual);
List<string> shortenedParamsExpected, shortenedParamsActual;
GetShortenedGenericParams(expected, actual, out shortenedParamsExpected, out shortenedParamsActual);
expectedTypeShortened = ReconstructGenericTypeName(shortenedGenericTypeExpected, shortenedParamsExpected);
actualTypeShortened = ReconstructGenericTypeName(shortenedGenericTypeActual, shortenedParamsActual);
}
else if (IsTypeGeneric(expected) || IsTypeGeneric(actual))
{
expectedTypeShortened = FullyShortenTypeName(expected);
actualTypeShortened = FullyShortenTypeName(actual);
}
else
{
ShortenTypeNames(expected, actual, out expectedTypeShortened, out actualTypeShortened);
}
}
/// <summary>
/// Obtain the shortened generic template parameters of the given <paramref name="expectedFullType"/> and <paramref name="actualFullType"/>,
/// if they are generic.
/// </summary>
/// <param name="expectedFullType">The expected <see cref="Type"/>.</param>
/// <param name="actualFullType">The actual <see cref="Type"/>.</param>
/// <param name="shortenedParamsExpected">Shortened generic parameters of the expected <see cref="Type"/>.</param>
/// <param name="shortenedParamsActual">Shortened generic parameters of the actual <see cref="Type"/>.</param>
private void GetShortenedGenericParams(Type expectedFullType, Type actualFullType, out List<string> shortenedParamsExpected, out List<string> shortenedParamsActual)
{
List<Type> templateParamsExpected = new List<Type>(expectedFullType.GetGenericArguments());
List<Type> templateParamsActual = new List<Type>(actualFullType.GetGenericArguments());
shortenedParamsExpected = new List<string>();
shortenedParamsActual = new List<string>();
while ((templateParamsExpected.Count > 0) && (templateParamsActual.Count > 0))
{
string shortenedExpected, shortenedActual;
ResolveTypeNameDifference(templateParamsExpected[0], templateParamsActual[0], out shortenedExpected, out shortenedActual);
shortenedParamsExpected.Add(shortenedExpected);
shortenedParamsActual.Add(shortenedActual);
templateParamsExpected.RemoveAt(0);
templateParamsActual.RemoveAt(0);
}
foreach (Type genericParamRemaining in templateParamsExpected)
{
shortenedParamsExpected.Add(FullyShortenTypeName(genericParamRemaining));
}
foreach (Type genericParamRemaining in templateParamsActual)
{
shortenedParamsActual.Add(FullyShortenTypeName(genericParamRemaining));
}
}
/// <summary>
/// Obtain a shortened name of the given <see cref="Type"/>.
/// </summary>
public string FullyShortenTypeName(Type genericType)
{
if (IsTypeGeneric(genericType))
{
string genericTypeDefinition = genericType.GetGenericTypeDefinition().Name;
List<Type> genericParams = new List<Type>(genericType.GetGenericArguments());
List<string> shortenedGenericParams = new List<string>();
genericParams.ForEach(x => shortenedGenericParams.Add(FullyShortenTypeName(x)));
return ReconstructGenericTypeName(genericTypeDefinition, shortenedGenericParams);
}
else
{
return genericType.Name;
}
}
/// <summary>
/// Shorten the given <see cref="Type"/> names by only including the relevant differing namespaces/types, if they differ.
/// </summary>
/// <param name="expectedType">The expected <see cref="Type"/>.</param>
/// <param name="actualType">The actual <see cref="Type"/>.</param>
/// <param name="expectedTypeShortened">The shortened expected <see cref="Type"/> name.</param>
/// <param name="actualTypeShortened">The shortened actual <see cref="Type"/> name.</param>
public void ShortenTypeNames(Type expectedType, Type actualType, out string expectedTypeShortened, out string actualTypeShortened)
{
string[] expectedOriginalType = expectedType.FullName.Split('.');
string[] actualOriginalType = actualType.FullName.Split('.');
bool diffDetected = false;
int actualStart = 0, expectStart = 0;
for (int expectLen = expectedOriginalType.Length - 1, actualLen = actualOriginalType.Length - 1;
expectLen >= 0 && actualLen >= 0;
expectLen--, actualLen--)
{
if (expectedOriginalType[expectLen] != actualOriginalType[actualLen])
{
actualStart = actualLen;
expectStart = expectLen;
diffDetected = true;
break;
}
}
if (diffDetected)
{
expectedTypeShortened = String.Join(".", expectedOriginalType, expectStart, expectedOriginalType.Length - expectStart);
actualTypeShortened = String.Join(".", actualOriginalType, actualStart, actualOriginalType.Length - actualStart);
}
else
{
expectedTypeShortened = expectedOriginalType[expectedOriginalType.Length - 1];
actualTypeShortened = actualOriginalType[actualOriginalType.Length - 1];
}
}
/// <summary>
/// Returns whether or not the <see cref="Type"/> is generic.
/// </summary>
public bool IsTypeGeneric(Type type)
{
Guard.ArgumentNotNull(type, nameof(type));
return type.GetGenericArguments().Length > 0;
}
/// <summary>
/// Returns the fully qualified generic <see cref="Type"/> name of a given <see cref="Type"/>.
/// </summary>
public string GetGenericTypeName(Type type)
{
Guard.ArgumentNotNull(type, nameof(type));
if (IsTypeGeneric(type))
{
Type generic = type.GetGenericTypeDefinition();
return generic.FullName;
}
else
{
throw new ArgumentException($"The provided {nameof(type)} was not generic");
}
}
/// <summary>
/// Reconstruct a generic type name using the provided generic type name, and a
/// <see cref="List"/> of the template parameters.
/// </summary>
/// <param name="genericTypeName">The name of the generic type, including the number of template parameters expected.</param>
/// <param name="templateParamNames">A <see cref="List"/> of names of the template parameters of the provided generic type.</param>
public string ReconstructGenericTypeName(string genericTypeName, List<string> templateParamNames)
{
return genericTypeName + "[" + string.Join(",", templateParamNames.ToArray()) + "]";
}
/// <summary>
/// Obtain the shortened generic <see cref="Type"/> names of the given expected and actual <see cref="Type"/>s.
/// </summary>
/// <param name="expected">The expected <see cref="Type"/>.</param>
/// <param name="actual">The actual <see cref="Type"/>.</param>
/// <param name="shortenedGenericNameExpected">The shortened expected generic name.</param>
/// <param name="shortenedGenericNameActual">The shortened actual generic name.</param>
public void GetShortenedGenericTypes(Type expected, Type actual, out string shortenedGenericNameExpected, out string shortenedGenericNameActual)
{
Type toplevelGenericExpected = expected.GetGenericTypeDefinition();
Type toplevelGenericActual = actual.GetGenericTypeDefinition();
ShortenTypeNames(
toplevelGenericExpected,
toplevelGenericActual,
out shortenedGenericNameExpected,
out shortenedGenericNameActual);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LicenseSpot.Framework;
namespace ActivationExample
{
public partial class MainForm : Form
{
private Calculator calculator;
private ExtendedLicense license;
public MainForm()
{
InitializeComponent();
this.license = ExtendedLicenseManager.GetLicense(typeof(MainForm), this, "your public key");
this.calculator = new Calculator();
this.calculator.CalculatorValueChanged += new Calculator.CalculatorValueChangedEventHandler(calculator_CalculatorValueChanged);
}
#region Calculator
void calculator_CalculatorValueChanged(object sender, CalculatorChangedEventArgs e)
{
if (e.HasError)
ValueLabel.Text = "err";
else if (e.OperationType == OperationType.Calculation)
{
UpdateValueLabel(e.Result, false);
ValueLabel.Tag = null;
}
else if (e.OperationType == OperationType.Accumulation)
{
ValueLabel.Tag = null;
}
}
private void AppendValue(string valueText)
{
string textValue = ValueLabel.Tag as string;
if (textValue == null)
{
textValue = "0";
}
bool hasPoint = false;
if (valueText == ".")
{
if (textValue.IndexOf(".") < 0)
{
textValue += ".";
hasPoint = true;
}
}
else
{
textValue += valueText;
}
decimal value;
if (decimal.TryParse(textValue, out value))
{
UpdateValueLabel(value, hasPoint);
}
}
private void UpdateValueLabel(decimal value, bool hasPoint)
{
if (value > 999999999m)
{
ValueLabel.Text = value.ToString("e");
ValueLabel.Tag = value.ToString();
}
else if (hasPoint)
{
ValueLabel.Text += ".";
ValueLabel.Tag += ".";
}
else
{
ValueLabel.Text = value.ToString();
ValueLabel.Tag = value.ToString();
}
}
private decimal? GetCurrentValue()
{
decimal value;
if (decimal.TryParse(ValueLabel.Tag as string ?? ValueLabel.Text, out value))
{
return value;
}
return null;
}
private void EqualButton_Click(object sender, EventArgs e)
{
calculator.Calculate(this.GetCurrentValue());
ValueLabel.Tag = null;
}
private void NumberButton_Click(object sender, EventArgs e)
{
this.AppendValue(((Button)sender).Text);
}
private void PlusButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new Sum());
}
private void MinusButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new Subtract());
}
private void MultiplyButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new Multiply());
}
private void DivisionButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new Divide());
}
private void Clear()
{
ValueLabel.Text = "0";
ValueLabel.Tag = null;
calculator.Clear();
}
private void ClearButton_Click(object sender, EventArgs e)
{
Clear();
}
private void AllClearButton_Click(object sender, EventArgs e)
{
Clear();
MemoryLabel.Visible = false;
calculator.AllClear();
}
private void MemorySubstractButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new MemorySubtract());
MemoryLabel.Visible = true;
}
private void MemoryAddButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new MemoryAdd());
MemoryLabel.Visible = true;
}
private void MemoryRecallButton_Click(object sender, EventArgs e)
{
Clear();
UpdateValueLabel(calculator.Memory ?? 0,false);
}
private void InvertSignButton_Click(object sender, EventArgs e)
{
calculator.ApplyOperation(this.GetCurrentValue(), new InvertSign());
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetDataObject(ValueLabel.Text, true);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text))
{
string value = (string)data.GetData(DataFormats.Text);
decimal res = 0;
if (decimal.TryParse(value, out res))
{
this.AppendValue(value);
}
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutForm dialog = new AboutForm();
dialog.ShowDialog();
}
#endregion
private void registerToolStripMenuItem_Click(object sender, EventArgs e)
{
ActivationForm dialog = new ActivationForm();
dialog.ShowDialog();
if (dialog.DialogResult == DialogResult.OK)
{
try
{
Cursor.Current = Cursors.WaitCursor;
license.Activate(dialog.SerialNumber);
license = ExtendedLicenseManager.GetLicense(typeof(MainForm), this, "your public key");
MessageBox.Show("The application has been activated.");
toolStripStatusLabel.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
private void MainForm_Load(object sender, EventArgs e)
{
if (license.Validate())
{
//MessageBox.Show("License is valid");
}
else
{
DialogResult activateResult = MessageBox.Show(this, "The calculator was unable to find a valid license", "Calculator", MessageBoxButtons.OK);
toolStripStatusLabel.Text = "License is invalid";
}
licenseGenuineTimer.Start();
}
private void licenseGenuineTimer_Tick(object sender, EventArgs e)
{
//Timer is checking if the license is geunine every 5 seconds just for demo purposes. The default value is 90 days.
try
{
if (license.IsGenuineEx() == GenuineResult.Genuine)
{
toolStripStatusLabel.Text = "License is genuine. It was validated against the server.";
}
else
{
toolStripStatusLabel.Text = "Geunine validation failed.";
}
}
catch (Exception ex)
{
toolStripStatusLabel.Text = ex.Message;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Text;
using DotNetty.Common.Utilities;
/// <summary>
/// Description of algorithm for PageRun/PoolSubpage allocation from PoolChunk
/// Notation: The following terms are important to understand the code
/// > page - a page is the smallest unit of memory chunk that can be allocated
/// > chunk - a chunk is a collection of pages
/// > in this code chunkSize = 2^{maxOrder} /// pageSize
/// To begin we allocate a byte array of size = chunkSize
/// Whenever a ByteBuf of given size needs to be created we search for the first position
/// in the byte array that has enough empty space to accommodate the requested size and
/// return a (long) handle that encodes this offset information, (this memory segment is then
/// marked as reserved so it is always used by exactly one ByteBuf and no more)
/// For simplicity all sizes are normalized according to PoolArena#normalizeCapacity method
/// This ensures that when we request for memory segments of size >= pageSize the normalizedCapacity
/// equals the next nearest power of 2
/// To search for the first offset in chunk that has at least requested size available we construct a
/// complete balanced binary tree and store it in an array (just like heaps) - memoryMap
/// The tree looks like this (the size of each node being mentioned in the parenthesis)
/// depth=0 1 node (chunkSize)
/// depth=1 2 nodes (chunkSize/2)
/// ..
/// ..
/// depth=d 2^d nodes (chunkSize/2^d)
/// ..
/// depth=maxOrder 2^maxOrder nodes (chunkSize/2^{maxOrder} = pageSize)
/// depth=maxOrder is the last level and the leafs consist of pages
/// With this tree available searching in chunkArray translates like this:
/// To allocate a memory segment of size chunkSize/2^k we search for the first node (from left) at height k
/// which is unused
/// Algorithm:
/// ----------
/// Encode the tree in memoryMap with the notation
/// memoryMap[id] = x => in the subtree rooted at id, the first node that is free to be allocated
/// is at depth x (counted from depth=0) i.e., at depths [depth_of_id, x), there is no node that is free
/// As we allocate & free nodes, we update values stored in memoryMap so that the property is maintained
/// Initialization -
/// In the beginning we construct the memoryMap array by storing the depth of a node at each node
/// i.e., memoryMap[id] = depth_of_id
/// Observations:
/// -------------
/// 1) memoryMap[id] = depth_of_id => it is free / unallocated
/// 2) memoryMap[id] > depth_of_id => at least one of its child nodes is allocated, so we cannot allocate it, but
/// some of its children can still be allocated based on their availability
/// 3) memoryMap[id] = maxOrder + 1 => the node is fully allocated & thus none of its children can be allocated, it
/// is thus marked as unusable
/// Algorithm: [allocateNode(d) => we want to find the first node (from left) at height h that can be allocated]
/// ----------
/// 1) start at root (i.e., depth = 0 or id = 1)
/// 2) if memoryMap[1] > d => cannot be allocated from this chunk
/// 3) if left node value <= h; we can allocate from left subtree so move to left and repeat until found
/// 4) else try in right subtree
/// Algorithm: [allocateRun(size)]
/// ----------
/// 1) Compute d = log_2(chunkSize/size)
/// 2) Return allocateNode(d)
/// Algorithm: [allocateSubpage(size)]
/// ----------
/// 1) use allocateNode(maxOrder) to find an empty (i.e., unused) leaf (i.e., page)
/// 2) use this handle to construct the PoolSubpage object or if it already exists just call init(normCapacity)
/// note that this PoolSubpage object is added to subpagesPool in the PoolArena when we init() it
/// Note:
/// -----
/// In the implementation for improving cache coherence,
/// we store 2 pieces of information (i.e, 2 byte vals) as a short value in memoryMap
/// memoryMap[id]= (depth_of_id, x)
/// where as per convention defined above
/// the second value (i.e, x) indicates that the first node which is free to be allocated is at depth x (from root)
/// </summary>
sealed class PoolChunk<T> : IPoolChunkMetric
{
internal readonly PoolArena<T> Arena;
internal readonly T Memory;
internal readonly bool Unpooled;
readonly sbyte[] memoryMap;
readonly sbyte[] depthMap;
readonly PoolSubpage<T>[] subpages;
/** Used to determine if the requested capacity is equal to or greater than pageSize. */
readonly int subpageOverflowMask;
readonly int pageSize;
readonly int pageShifts;
readonly int maxOrder;
readonly int chunkSize;
readonly int log2ChunkSize;
readonly int maxSubpageAllocs;
/** Used to mark memory as unusable */
readonly sbyte unusable;
int freeBytes;
internal PoolChunkList<T> Parent;
internal PoolChunk<T> Prev;
internal PoolChunk<T> Next;
// TODO: Test if adding padding helps under contention
//private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
internal PoolChunk(PoolArena<T> arena, T memory, int pageSize, int maxOrder, int pageShifts, int chunkSize)
{
Contract.Requires(maxOrder < 30, "maxOrder should be < 30, but is: " + maxOrder);
this.Unpooled = false;
this.Arena = arena;
this.Memory = memory;
this.pageSize = pageSize;
this.pageShifts = pageShifts;
this.maxOrder = maxOrder;
this.chunkSize = chunkSize;
this.unusable = (sbyte)(maxOrder + 1);
this.log2ChunkSize = IntegerExtensions.Log2(chunkSize);
this.subpageOverflowMask = ~(pageSize - 1);
this.freeBytes = chunkSize;
Contract.Assert(maxOrder < 30, "maxOrder should be < 30, but is: " + maxOrder);
this.maxSubpageAllocs = 1 << maxOrder;
// Generate the memory map.
this.memoryMap = new sbyte[this.maxSubpageAllocs << 1];
this.depthMap = new sbyte[this.memoryMap.Length];
int memoryMapIndex = 1;
for (int d = 0; d <= maxOrder; ++d)
{
// move down the tree one level at a time
int depth = 1 << d;
for (int p = 0; p < depth; ++p)
{
// in each level traverse left to right and set value to the depth of subtree
this.memoryMap[memoryMapIndex] = (sbyte)d;
this.depthMap[memoryMapIndex] = (sbyte)d;
memoryMapIndex++;
}
}
this.subpages = this.NewSubpageArray(this.maxSubpageAllocs);
}
/** Creates a special chunk that is not pooled. */
internal PoolChunk(PoolArena<T> arena, T memory, int size)
{
this.Unpooled = true;
this.Arena = arena;
this.Memory = memory;
this.memoryMap = null;
this.depthMap = null;
this.subpages = null;
this.subpageOverflowMask = 0;
this.pageSize = 0;
this.pageShifts = 0;
this.maxOrder = 0;
this.unusable = (sbyte)(this.maxOrder + 1);
this.chunkSize = size;
this.log2ChunkSize = IntegerExtensions.Log2(this.chunkSize);
this.maxSubpageAllocs = 0;
}
PoolSubpage<T>[] NewSubpageArray(int size) => new PoolSubpage<T>[size];
public int Usage
{
get
{
int freeBytes = this.freeBytes;
if (freeBytes == 0)
{
return 100;
}
int freePercentage = (int)(freeBytes * 100L / this.chunkSize);
if (freePercentage == 0)
{
return 99;
}
return 100 - freePercentage;
}
}
internal long Allocate(int normCapacity)
{
if ((normCapacity & this.subpageOverflowMask) != 0)
{
// >= pageSize
return this.AllocateRun(normCapacity);
}
else
{
return this.AllocateSubpage(normCapacity);
}
}
/**
* Update method used by allocate
* This is triggered only when a successor is allocated and all its predecessors
* need to update their state
* The minimal depth at which subtree rooted at id has some free space
*
* @param id id
*/
void UpdateParentsAlloc(int id)
{
while (id > 1)
{
int parentId = id.RightUShift(1);
sbyte val1 = this.Value(id);
sbyte val2 = this.Value(id ^ 1);
sbyte val = val1 < val2 ? val1 : val2;
this.SetValue(parentId, val);
id = parentId;
}
}
/**
* Update method used by free
* This needs to handle the special case when both children are completely free
* in which case parent be directly allocated on request of size = child-size * 2
*
* @param id id
*/
void UpdateParentsFree(int id)
{
int logChild = this.Depth(id) + 1;
while (id > 1)
{
int parentId = id.RightUShift(1);
sbyte val1 = this.Value(id);
sbyte val2 = this.Value(id ^ 1);
logChild -= 1; // in first iteration equals log, subsequently reduce 1 from logChild as we traverse up
if (val1 == logChild && val2 == logChild)
{
this.SetValue(parentId, (sbyte)(logChild - 1));
}
else
{
sbyte val = val1 < val2 ? val1 : val2;
this.SetValue(parentId, val);
}
id = parentId;
}
}
/**
* Algorithm to allocate an index in memoryMap when we query for a free node
* at depth d
*
* @param d depth
* @return index in memoryMap
*/
int AllocateNode(int d)
{
int id = 1;
int initial = -(1 << d); // has last d bits = 0 and rest all = 1
sbyte val = this.Value(id);
if (val > d)
{
// unusable
return -1;
}
while (val < d || (id & initial) == 0)
{
// id & initial == 1 << d for all ids at depth d, for < d it is 0
id <<= 1;
val = this.Value(id);
if (val > d)
{
id ^= 1;
val = this.Value(id);
}
}
sbyte value = this.Value(id);
Contract.Assert(value == d && (id & initial) == 1 << d, $"val = {value}, id & initial = {id & initial}, d = {d}");
this.SetValue(id, this.unusable); // mark as unusable
this.UpdateParentsAlloc(id);
return id;
}
/**
* Allocate a run of pages (>=1)
*
* @param normCapacity normalized capacity
* @return index in memoryMap
*/
long AllocateRun(int normCapacity)
{
int d = this.maxOrder - (IntegerExtensions.Log2(normCapacity) - this.pageShifts);
int id = this.AllocateNode(d);
if (id < 0)
{
return id;
}
this.freeBytes -= this.RunLength(id);
return id;
}
/**
* Create/ initialize a new PoolSubpage of normCapacity
* Any PoolSubpage created/ initialized here is added to subpage pool in the PoolArena that owns this PoolChunk
*
* @param normCapacity normalized capacity
* @return index in memoryMap
*/
long AllocateSubpage(int normCapacity)
{
int d = this.maxOrder; // subpages are only be allocated from pages i.e., leaves
int id = this.AllocateNode(d);
if (id < 0)
{
return id;
}
PoolSubpage<T>[] subpages = this.subpages;
int pageSize = this.pageSize;
this.freeBytes -= pageSize;
int subpageIdx = this.SubpageIdx(id);
PoolSubpage<T> subpage = subpages[subpageIdx];
if (subpage == null)
{
subpage = new PoolSubpage<T>(this, id, this.RunOffset(id), pageSize, normCapacity);
subpages[subpageIdx] = subpage;
}
else
{
subpage.Init(normCapacity);
}
return subpage.Allocate();
}
/**
* Free a subpage or a run of pages
* When a subpage is freed from PoolSubpage, it might be added back to subpage pool of the owning PoolArena
* If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, we can
* completely free the owning Page so it is available for subsequent allocations
*
* @param handle handle to free
*/
internal void Free(long handle)
{
int memoryMapIdx = MemoryMapIdx(handle);
int bitmapIdx = BitmapIdx(handle);
if (bitmapIdx != 0)
{
// free a subpage
PoolSubpage<T> subpage = this.subpages[this.SubpageIdx(memoryMapIdx)];
Contract.Assert(subpage != null && subpage.DoNotDestroy);
// Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it.
// This is need as we may add it back and so alter the linked-list structure.
PoolSubpage<T> head = this.Arena.FindSubpagePoolHead(subpage.ElemSize);
lock (head)
{
if (subpage.Free(bitmapIdx & 0x3FFFFFFF))
{
return;
}
}
}
this.freeBytes += this.RunLength(memoryMapIdx);
this.SetValue(memoryMapIdx, this.Depth(memoryMapIdx));
this.UpdateParentsFree(memoryMapIdx);
}
internal void InitBuf(PooledByteBuffer<T> buf, long handle, int reqCapacity)
{
int memoryMapIdx = MemoryMapIdx(handle);
int bitmapIdx = BitmapIdx(handle);
if (bitmapIdx == 0)
{
sbyte val = this.Value(memoryMapIdx);
Contract.Assert(val == this.unusable, val.ToString());
buf.Init(this, handle, this.RunOffset(memoryMapIdx), reqCapacity, this.RunLength(memoryMapIdx),
this.Arena.Parent.ThreadCache<T>());
}
else
{
this.InitBufWithSubpage(buf, handle, bitmapIdx, reqCapacity);
}
}
internal void InitBufWithSubpage(PooledByteBuffer<T> buf, long handle, int reqCapacity) => this.InitBufWithSubpage(buf, handle, BitmapIdx(handle), reqCapacity);
void InitBufWithSubpage(PooledByteBuffer<T> buf, long handle, int bitmapIdx, int reqCapacity)
{
Contract.Assert(bitmapIdx != 0);
int memoryMapIdx = MemoryMapIdx(handle);
PoolSubpage<T> subpage = this.subpages[this.SubpageIdx(memoryMapIdx)];
Contract.Assert(subpage.DoNotDestroy);
Contract.Assert(reqCapacity <= subpage.ElemSize);
buf.Init(
this, handle,
this.RunOffset(memoryMapIdx) + (bitmapIdx & 0x3FFFFFFF) * subpage.ElemSize, reqCapacity, subpage.ElemSize,
this.Arena.Parent.ThreadCache<T>());
}
sbyte Value(int id) => this.memoryMap[id];
void SetValue(int id, sbyte val) => this.memoryMap[id] = val;
sbyte Depth(int id) => this.depthMap[id];
/// represents the size in #bytes supported by node 'id' in the tree
int RunLength(int id) => 1 << this.log2ChunkSize - this.Depth(id);
int RunOffset(int id)
{
// represents the 0-based offset in #bytes from start of the byte-array chunk
int shift = id ^ 1 << this.Depth(id);
return shift * this.RunLength(id);
}
int SubpageIdx(int memoryMapIdx) => memoryMapIdx ^ this.maxSubpageAllocs; // remove highest set bit, to get offset
static int MemoryMapIdx(long handle) => (int)handle;
static int BitmapIdx(long handle) => (int)handle.RightUShift(IntegerExtensions.SizeInBits);
public int ChunkSize => this.chunkSize;
public int FreeBytes => this.freeBytes;
public override string ToString()
{
return new StringBuilder()
.Append("Chunk(")
.Append(RuntimeHelpers.GetHashCode(this).ToString("X"))
.Append(": ")
.Append(this.Usage)
.Append("%, ")
.Append(this.chunkSize - this.freeBytes)
.Append('/')
.Append(this.chunkSize)
.Append(')')
.ToString();
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Globalization;
using System.Linq;
using NLog.Layouts;
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Keeps logging configuration and provides simple API
/// to modify it.
/// </summary>
public class LoggingConfiguration
{
private readonly IDictionary<string, Target> targets =
new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase);
private object[] configItems;
/// <summary>
/// Variables defined in xml or in API. name is case case insensitive.
/// </summary>
private readonly Dictionary<string, SimpleLayout> variables = new Dictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Initializes a new instance of the <see cref="LoggingConfiguration" /> class.
/// </summary>
public LoggingConfiguration()
{
this.LoggingRules = new List<LoggingRule>();
}
/// <summary>
/// Use the old exception log handling of NLog 3.0?
/// </summary>
[Obsolete("This option will be removed in NLog 5")]
public bool ExceptionLoggingOldStyle { get; set; }
/// <summary>
/// Gets the variables defined in the configuration.
/// </summary>
public IDictionary<string, SimpleLayout> Variables
{
get
{
return variables;
}
}
/// <summary>
/// Gets a collection of named targets specified in the configuration.
/// </summary>
/// <returns>
/// A list of named targets.
/// </returns>
/// <remarks>
/// Unnamed targets (such as those wrapped by other targets) are not returned.
/// </remarks>
public ReadOnlyCollection<Target> ConfiguredNamedTargets
{
get { return new List<Target>(this.targets.Values).AsReadOnly(); }
}
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// </summary>
public virtual IEnumerable<string> FileNamesToWatch
{
get { return new string[0]; }
}
/// <summary>
/// Gets the collection of logging rules.
/// </summary>
public IList<LoggingRule> LoggingRules { get; private set; }
/// <summary>
/// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo { get; set; }
/// <summary>
/// Gets all targets.
/// </summary>
public ReadOnlyCollection<Target> AllTargets
{
get { return this.configItems.OfType<Target>().ToList().AsReadOnly(); }
}
/// <summary>
/// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>.
/// </summary>
/// <param name="target">
/// The target object with a non <see langword="null"/> <see cref="Target.Name"/>
/// </param>
/// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception>
public void AddTarget([NotNull] Target target)
{
if (target == null) throw new ArgumentNullException("target");
AddTarget(target.Name, target);
}
/// <summary>
/// Registers the specified target object under a given name.
/// </summary>
/// <param name="name">
/// Name of the target.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
public void AddTarget(string name, Target target)
{
if (name == null)
{
throw new ArgumentException("Target name cannot be null", "name");
}
InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName);
this.targets[name] = target;
}
/// <summary>
/// Finds the target with the specified name.
/// </summary>
/// <param name="name">
/// The name of the target to be found.
/// </param>
/// <returns>
/// Found target or <see langword="null"/> when the target is not found.
/// </returns>
public Target FindTargetByName(string name)
{
Target value;
if (!this.targets.TryGetValue(name, out value))
{
return null;
}
return value;
}
/// <summary>
/// Finds the target with the specified name and specified type.
/// </summary>
/// <param name="name">
/// The name of the target to be found.
/// </param>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <returns>
/// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/>
/// </returns>
public TTarget FindTargetByName<TTarget>(string name)
where TTarget : Target
{
return FindTargetByName(name) as TTarget;
}
/// <summary>
/// Called by LogManager when one of the log configuration files changes.
/// </summary>
/// <returns>
/// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration.
/// </returns>
public virtual LoggingConfiguration Reload()
{
return this;
}
/// <summary>
/// Removes the specified named target.
/// </summary>
/// <param name="name">
/// Name of the target.
/// </param>
public void RemoveTarget(string name)
{
this.targets.Remove(name);
}
/// <summary>
/// Installs target-specific objects on current system.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <remarks>
/// Installation typically runs with administrative permissions.
/// </remarks>
public void Install(InstallationContext installationContext)
{
if (installationContext == null)
{
throw new ArgumentNullException("installationContext");
}
this.InitializeAll();
foreach (IInstallable installable in this.configItems.OfType<IInstallable>())
{
installationContext.Info("Installing '{0}'", installable);
try
{
installable.Install(installationContext);
installationContext.Info("Finished installing '{0}'.", installable);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
installationContext.Error("'{0}' installation failed: {1}.", installable, exception);
}
}
}
/// <summary>
/// Uninstalls target-specific objects from current system.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <remarks>
/// Uninstallation typically runs with administrative permissions.
/// </remarks>
public void Uninstall(InstallationContext installationContext)
{
if (installationContext == null)
{
throw new ArgumentNullException("installationContext");
}
this.InitializeAll();
foreach (IInstallable installable in this.configItems.OfType<IInstallable>())
{
installationContext.Info("Uninstalling '{0}'", installable);
try
{
installable.Uninstall(installationContext);
installationContext.Info("Finished uninstalling '{0}'.", installable);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
installationContext.Error("Uninstallation of '{0}' failed: {1}.", installable, exception);
}
}
}
/// <summary>
/// Closes all targets and releases any unmanaged resources.
/// </summary>
internal void Close()
{
InternalLogger.Debug("Closing logging configuration...");
foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>())
{
InternalLogger.Trace("Closing {0}", initialize);
try
{
initialize.Close();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception while closing {0}", exception);
}
}
InternalLogger.Debug("Finished closing logging configuration.");
}
internal void Dump()
{
if (!InternalLogger.IsDebugEnabled)
{
return;
}
InternalLogger.Debug("--- NLog configuration dump. ---");
InternalLogger.Debug("Targets:");
foreach (Target target in this.targets.Values)
{
InternalLogger.Info("{0}", target);
}
InternalLogger.Debug("Rules:");
foreach (LoggingRule rule in this.LoggingRules)
{
InternalLogger.Info("{0}", rule);
}
InternalLogger.Debug("--- End of NLog configuration dump ---");
}
/// <summary>
/// Flushes any pending log messages on all appenders.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
internal void FlushAllTargets(AsyncContinuation asyncContinuation)
{
var uniqueTargets = new List<Target>();
foreach (var rule in this.LoggingRules)
{
foreach (var t in rule.Targets)
{
if (!uniqueTargets.Contains(t))
{
uniqueTargets.Add(t);
}
}
}
AsyncHelpers.ForEachItemInParallel(uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont));
}
/// <summary>
/// Validates the configuration.
/// </summary>
internal void ValidateConfig()
{
var roots = new List<object>();
foreach (LoggingRule r in this.LoggingRules)
{
roots.Add(r);
}
foreach (Target target in this.targets.Values)
{
roots.Add(target);
}
this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray());
// initialize all config items starting from most nested first
// so that whenever the container is initialized its children have already been
InternalLogger.Info("Found {0} configuration items", this.configItems.Length);
foreach (object o in this.configItems)
{
PropertyHelper.CheckRequiredParameters(o);
}
}
internal void InitializeAll()
{
this.ValidateConfig();
foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>().Reverse())
{
InternalLogger.Trace("Initializing {0}", initialize);
try
{
initialize.Initialize(this);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error during initialization of " + initialize, exception);
}
}
}
}
internal void EnsureInitialized()
{
this.InitializeAll();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ManifestBasedResourceGroveler
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Searches for resources in Assembly manifest, used
** for assembly-based resource lookup.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
#if !FEATURE_CORECLR
using System.Diagnostics.Tracing;
#endif
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
internal class ManifestBasedResourceGroveler : IResourceGroveler
{
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
// here and below: convert asserts to preconditions where appropriate when we get
// contracts story in place.
Contract.Requires(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Contract.Assert(culture != null, "culture shouldn't be null; check caller");
Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
RuntimeAssembly satellite = null;
// 1. Fixups for ultimate fallbacks
CultureInfo lookForCulture = UltimateFallbackFixup(culture);
// 2. Look for satellite assembly or main assembly, as appropriate
if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
// don't bother looking in satellites in this case
satellite = _mediator.MainAssembly;
}
#if RESOURCE_SATELLITE_CONFIG
// If our config file says the satellite isn't here, don't ask for it.
else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture))
{
satellite = null;
}
#endif
else
{
satellite = GetSatelliteAssembly(lookForCulture, ref stackMark);
if (satellite == null)
{
bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
// didn't find satellite, give error if necessary
if (raiseException)
{
HandleSatelliteMissing();
}
}
}
// get resource file name we'll search for. Note, be careful if you're moving this statement
// around because lookForCulture may be modified from originally requested culture above.
String fileName = _mediator.GetResourceFileName(lookForCulture);
// 3. If we identified an assembly to search; look in manifest resource stream for resource file
if (satellite != null)
{
// Handle case in here where someone added a callback for assembly load events.
// While no other threads have called into GetResourceSet, our own thread can!
// At that point, we could already have an RS in our hash table, and we don't
// want to add it twice.
lock (localResourceSets)
{
if (localResourceSets.TryGetValue(culture.Name, out rs))
{
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
}
#endif
}
}
stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
}
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
if (stream != null)
{
FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
}
else
{
FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
}
}
#endif
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName);
}
#endif
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
{
// 4b. Didn't find stream; give error if necessary
bool raiseException = culture.HasInvariantCultureName;
if (raiseException)
{
HandleResourceStreamMissing(fileName);
}
}
#if !FEATURE_CORECLR && !MONO
if (!createIfNotExists && stream != null && rs == null)
{
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
}
}
#endif
return rs;
}
#if !FEATURE_CORECLR
// Returns whether or not the main assembly contains a particular resource
// file in it's assembly manifest. Used to verify that the neutral
// Culture's .resources file is present in the main assembly
public bool HasNeutralResources(CultureInfo culture, String defaultResName)
{
String resName = defaultResName;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName;
String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames();
foreach(String s in resourceFiles)
if (s.Equals(resName))
return true;
return false;
}
#endif
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
// does NOT contain neutral resources, don't probe for this satellite.
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name);
}
#endif
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
{
returnCulture = _mediator.NeutralResourcesCulture;
}
return returnCulture;
}
[System.Security.SecurityCritical]
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
#if FEATURE_LEGACYNETCF
// Windows Phone 7.0/7.1 ignore NeutralResourceLanguage attribute and
// defaults fallbackLocation to MainAssembly
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
{
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
#endif
Contract.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
#if MONO
if (GetNeutralResourcesLanguageAttribute(a, ref cultureName, ref fallback)) {
#else
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref cultureName),
out fallback)) {
#endif
if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
else {
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized) {
FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a);
}
#endif
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
try
{
CultureInfo c = CultureInfo.GetCultureInfo(cultureName);
return c;
}
catch (ArgumentException e)
{ // we should catch ArgumentException only.
// Note we could go into infinite loops if mscorlib's
// NeutralResourcesLanguageAttribute is mangled. If this assert
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
Contract.Assert(false, "mscorlib's NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e);
}
}
// Constructs a new ResourceSet for a given file name. The logic in
// here avoids a ReflectionPermission check for our RuntimeResourceSet
// for perf and working set reasons.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
[System.Security.SecurityCritical]
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
Contract.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
// Look for our magic number as a little endian Int32.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
{
int resMgrHeaderVersion = br.ReadInt32();
String readerTypeName = null, resSetTypeName = null;
if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
{
br.ReadInt32(); // We don't want the number of bytes to skip.
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
}
else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
{
// Assume that the future ResourceManager headers will
// have two strings for us - the reader type name and
// resource set type name. Read those, then use the num
// bytes to skip field to correct our position.
int numBytesToSkip = br.ReadInt32();
long endPosition = br.BaseStream.Position + numBytesToSkip;
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
}
else
{
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName()));
}
store.Position = startPos;
// Perf optimization - Don't use Reflection for our defaults.
// Note there are two different sets of strings here - the
// assembly qualified strings emitted by ResourceWriter, and
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
RuntimeResourceSet rs;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs = new RuntimeResourceSet(store, assembly);
#else
rs = new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
else
{
// we do not want to use partial binding here.
Type readerType = Type.GetType(readerTypeName, true);
Object[] args = new Object[1];
args[0] = store;
IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);
Object[] resourceSetArgs =
#if LOOSELY_LINKED_RESOURCE_REFERENCE
new Object[2];
#else
new Object[1];
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[0] = reader;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[1] = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
Type resSetType;
if (_mediator.UserResourceSet == null)
{
Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
resSetType = _mediator.UserResourceSet;
ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null,
resourceSetArgs,
null,
null);
return rs;
}
}
else
{
store.Position = startPos;
}
}
if (_mediator.UserResourceSet == null)
{
// Explicitly avoid CreateInstance if possible, because it
// requires ReflectionPermission to call private & protected
// constructors.
#if LOOSELY_LINKED_RESOURCE_REFERENCE
return new RuntimeResourceSet(store, assembly);
#else
return new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
}
else
{
Object[] args = new Object[2];
args[0] = store;
args[1] = assembly;
try
{
ResourceSet rs = null;
// Add in a check for a constructor taking in an assembly first.
try
{
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
return rs;
}
catch (MissingMethodException) { }
args = new Object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs.Assembly = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
catch (MissingMethodException e)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
[System.Security.SecurityCritical]
private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(fileName != null, "fileName shouldn't be null; check caller");
// If we're looking in the main assembly AND if the main assembly was the person who
// created the ResourceManager, skip a security check for private manifest resources.
bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite)
&& (_mediator.CallingAssembly == _mediator.MainAssembly);
Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark);
if (stream == null)
{
stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName);
}
return stream;
}
// Looks up a .resources file in the assembly manifest using
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(name != null, "name shouldn't be null; check caller");
StringBuilder sb = new StringBuilder();
if (_mediator.LocationInfo != null)
{
String nameSpace = _mediator.LocationInfo.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
sb.Append(Type.Delimiter);
}
}
sb.Append(name);
String givenName = sb.ToString();
CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
String canonicalName = null;
foreach (String existingName in satellite.GetManifestResourceNames())
{
if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0)
{
if (canonicalName == null)
{
canonicalName = existingName;
}
else
{
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString()));
}
}
}
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
if (canonicalName != null)
{
FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
}
else
{
FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
}
}
#endif
if (canonicalName == null)
{
return null;
}
// If we're looking in the main assembly AND if the main
// assembly was the person who created the ResourceManager,
// skip a security check for private manifest resources.
bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
// GetManifestResourceStream will return null if we don't have
// permission to read this stream from the assembly. For example,
// if the stream is private and we're trying to access it from another
// assembly (ie, ResMgr in mscorlib accessing anything else), we
// require Reflection TypeInformation permission to be able to read
// this. <
#if !FEATURE_CORECLR && !MONO
if (s!=null) {
if (FrameworkEventSource.IsInitialized)
{
FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName);
}
}
#endif
return s;
}
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
if (!_mediator.LookedForSatelliteContractVersion)
{
_mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly);
_mediator.LookedForSatelliteContractVersion = true;
}
RuntimeAssembly satellite = null;
String satAssemblyName = GetSatelliteAssemblyName();
// Look up the satellite assembly, but don't let problems
// like a partially signed satellite assembly stop us from
// doing fallback and displaying something to the user.
// Yet also somehow log this error for a developer.
try
{
satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark);
}
// Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback.
//
catch (FileLoadException fle)
{
#if !MONO
// Ignore cases where the loader gets an access
// denied back from the OS. This showed up for
// href-run exe's at one point.
int hr = fle._HResult;
if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
#endif
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
#if !FEATURE_CORECLR && !MONO
if (FrameworkEventSource.IsInitialized)
{
if (satellite != null)
{
FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
}
else
{
FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
}
}
#endif
return satellite;
}
// Perf optimization - Don't use Reflection for most cases with
// our .resources files. This makes our code run faster and we can
// creating a ResourceReader via Reflection. This would incur
// a security check (since the link-time check on the constructor that
// takes a String is turned into a full demand with a stack walk)
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
// Ignore the actual version of the ResourceReader and
// RuntimeResourceSet classes. Let those classes deal with
// versioning themselves.
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (readerTypeName != null)
{
if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib))
return false;
}
if (resSetTypeName != null)
{
if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib))
return false;
}
return true;
}
[System.Security.SecurityCritical]
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
satAssemblyName += ".resources";
return satAssemblyName;
}
[System.Security.SecurityCritical]
private void HandleSatelliteMissing()
{
String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString();
}
AssemblyName an = new AssemblyName();
an.SetPublicKey(_mediator.MainAssembly.GetPublicKey());
byte[] token = an.GetPublicKeyToken();
int iLen = token.Length;
StringBuilder publicKeyTok = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++)
{
publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture));
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
String missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
missingCultureName = "<invariant>";
}
throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
[System.Security.SecurityCritical] // auto-generated
private void HandleResourceStreamMissing(String fileName)
{
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals("mscorlib"))
{
// This would break CultureInfo & all our exceptions.
Contract.Assert(false, "Couldn't get mscorlib" + ResourceManager.ResFileExtension + " from mscorlib's assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = "mscorlib" + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
}
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
String resName = String.Empty;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName()));
}
#if MONO
static bool GetNeutralResourcesLanguageAttribute (Assembly assembly, ref string cultureName, ref short fallbackLocation)
{
var ca = assembly.GetCustomAttribute<NeutralResourcesLanguageAttribute> ();
if (ca == null)
return false;
cultureName = ca.CultureName;
fallbackLocation = (short) ca.Location;
return true;
}
#else
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods.
[ResourceExposure(ResourceScope.None)]
[System.Security.SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
#endif
}
}
| |
namespace Humidifier.Greengrass
{
using System.Collections.Generic;
using FunctionDefinitionTypes;
public class FunctionDefinition : Humidifier.Resource
{
public static class Attributes
{
public static string LatestVersionArn = "LatestVersionArn" ;
public static string Id = "Id" ;
public static string Arn = "Arn" ;
public static string Name = "Name" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::Greengrass::FunctionDefinition";
}
}
/// <summary>
/// InitialVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-functiondefinition.html#cfn-greengrass-functiondefinition-initialversion
/// Required: False
/// UpdateType: Immutable
/// Type: FunctionDefinitionVersion
/// </summary>
public FunctionDefinitionVersion InitialVersion
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-functiondefinition.html#cfn-greengrass-functiondefinition-tags
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic Tags
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-functiondefinition.html#cfn-greengrass-functiondefinition-name
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
namespace FunctionDefinitionTypes
{
public class Execution
{
/// <summary>
/// IsolationMode
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-execution.html#cfn-greengrass-functiondefinition-execution-isolationmode
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic IsolationMode
{
get;
set;
}
/// <summary>
/// RunAs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-execution.html#cfn-greengrass-functiondefinition-execution-runas
/// Required: False
/// UpdateType: Immutable
/// Type: RunAs
/// </summary>
public RunAs RunAs
{
get;
set;
}
}
public class FunctionConfiguration
{
/// <summary>
/// MemorySize
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-memorysize
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Integer
/// </summary>
public dynamic MemorySize
{
get;
set;
}
/// <summary>
/// Pinned
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-pinned
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Pinned
{
get;
set;
}
/// <summary>
/// ExecArgs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-execargs
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ExecArgs
{
get;
set;
}
/// <summary>
/// Timeout
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-timeout
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Timeout
{
get;
set;
}
/// <summary>
/// EncodingType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-encodingtype
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic EncodingType
{
get;
set;
}
/// <summary>
/// Environment
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-environment
/// Required: False
/// UpdateType: Immutable
/// Type: Environment
/// </summary>
public Environment Environment
{
get;
set;
}
/// <summary>
/// Executable
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functionconfiguration.html#cfn-greengrass-functiondefinition-functionconfiguration-executable
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Executable
{
get;
set;
}
}
public class Environment
{
/// <summary>
/// Variables
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-environment.html#cfn-greengrass-functiondefinition-environment-variables
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Json
/// </summary>
public dynamic Variables
{
get;
set;
}
/// <summary>
/// Execution
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-environment.html#cfn-greengrass-functiondefinition-environment-execution
/// Required: False
/// UpdateType: Immutable
/// Type: Execution
/// </summary>
public Execution Execution
{
get;
set;
}
/// <summary>
/// ResourceAccessPolicies
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-environment.html#cfn-greengrass-functiondefinition-environment-resourceaccesspolicies
/// Required: False
/// UpdateType: Immutable
/// Type: List
/// ItemType: ResourceAccessPolicy
/// </summary>
public List<ResourceAccessPolicy> ResourceAccessPolicies
{
get;
set;
}
/// <summary>
/// AccessSysfs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-environment.html#cfn-greengrass-functiondefinition-environment-accesssysfs
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AccessSysfs
{
get;
set;
}
}
public class FunctionDefinitionVersion
{
/// <summary>
/// DefaultConfig
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functiondefinitionversion.html#cfn-greengrass-functiondefinition-functiondefinitionversion-defaultconfig
/// Required: False
/// UpdateType: Immutable
/// Type: DefaultConfig
/// </summary>
public DefaultConfig DefaultConfig
{
get;
set;
}
/// <summary>
/// Functions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-functiondefinitionversion.html#cfn-greengrass-functiondefinition-functiondefinitionversion-functions
/// Required: True
/// UpdateType: Immutable
/// Type: List
/// ItemType: Function
/// </summary>
public List<Function> Functions
{
get;
set;
}
}
public class RunAs
{
/// <summary>
/// Uid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-runas.html#cfn-greengrass-functiondefinition-runas-uid
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Uid
{
get;
set;
}
/// <summary>
/// Gid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-runas.html#cfn-greengrass-functiondefinition-runas-gid
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Gid
{
get;
set;
}
}
public class DefaultConfig
{
/// <summary>
/// Execution
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-defaultconfig.html#cfn-greengrass-functiondefinition-defaultconfig-execution
/// Required: True
/// UpdateType: Mutable
/// Type: Execution
/// </summary>
public Execution Execution
{
get;
set;
}
}
public class Function
{
/// <summary>
/// FunctionArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-function.html#cfn-greengrass-functiondefinition-function-functionarn
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic FunctionArn
{
get;
set;
}
/// <summary>
/// FunctionConfiguration
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-function.html#cfn-greengrass-functiondefinition-function-functionconfiguration
/// Required: True
/// UpdateType: Immutable
/// Type: FunctionConfiguration
/// </summary>
public FunctionConfiguration FunctionConfiguration
{
get;
set;
}
/// <summary>
/// Id
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-function.html#cfn-greengrass-functiondefinition-function-id
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Id
{
get;
set;
}
}
public class ResourceAccessPolicy
{
/// <summary>
/// ResourceId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-resourceaccesspolicy.html#cfn-greengrass-functiondefinition-resourceaccesspolicy-resourceid
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic ResourceId
{
get;
set;
}
/// <summary>
/// Permission
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-functiondefinition-resourceaccesspolicy.html#cfn-greengrass-functiondefinition-resourceaccesspolicy-permission
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Permission
{
get;
set;
}
}
}
}
| |
// BZip2InputStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-July-31 11:57:32>
//
// ------------------------------------------------------------------
//
// This module defines the BZip2InputStream class, which is a decompressing
// stream that handles BZIP2. This code is derived from Apache commons source code.
// The license below applies to the original Apache code.
//
// ------------------------------------------------------------------
/*
* 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.
*/
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* <keiron@aftexsw.com> to whom the Ant project is very grateful for his
* great code.
*/
// compile: msbuild
// not: csc.exe /t:library /debug+ /out:Ionic.BZip2.dll BZip2InputStream.cs BCRC32.cs Rand.cs
using System;
using System.IO;
namespace Ionic.BZip2
{
/// <summary>
/// A read-only decorator stream that performs BZip2 decompression on Read.
/// </summary>
public class BZip2InputStream : System.IO.Stream
{
bool _disposed;
bool _leaveOpen;
Int64 totalBytesRead;
private int last;
/* for undoing the Burrows-Wheeler transform */
private int origPtr;
// blockSize100k: 0 .. 9.
//
// This var name is a misnomer. The actual block size is 100000
// * blockSize100k. (not 100k * blocksize100k)
private int blockSize100k;
private bool blockRandomised;
private int bsBuff;
private int bsLive;
private readonly Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32(true);
private int nInUse;
private Stream input;
private int currentChar = -1;
/// <summary>
/// Compressor State
/// </summary>
enum CState
{
EOF = 0,
START_BLOCK = 1,
RAND_PART_A = 2,
RAND_PART_B = 3,
RAND_PART_C = 4,
NO_RAND_PART_A = 5,
NO_RAND_PART_B = 6,
NO_RAND_PART_C = 7,
}
private CState currentState = CState.START_BLOCK;
private uint storedBlockCRC, storedCombinedCRC;
private uint computedBlockCRC, computedCombinedCRC;
// Variables used by setup* methods exclusively
private int su_count;
private int su_ch2;
private int su_chPrev;
private int su_i2;
private int su_j2;
private int su_rNToGo;
private int su_rTPos;
private int su_tPos;
private char su_z;
private BZip2InputStream.DecompressionState data;
/// <summary>
/// Create a BZip2InputStream, wrapping it around the given input Stream.
/// </summary>
/// <remarks>
/// <para>
/// The input stream will be closed when the BZip2InputStream is closed.
/// </para>
/// </remarks>
/// <param name='input'>The stream from which to read compressed data</param>
public BZip2InputStream(Stream input)
: this(input, false)
{}
/// <summary>
/// Create a BZip2InputStream with the given stream, and
/// specifying whether to leave the wrapped stream open when
/// the BZip2InputStream is closed.
/// </summary>
/// <param name='input'>The stream from which to read compressed data</param>
/// <param name='leaveOpen'>
/// Whether to leave the input stream open, when the BZip2InputStream closes.
/// </param>
///
/// <example>
///
/// This example reads a bzip2-compressed file, decompresses it,
/// and writes the decompressed data into a newly created file.
///
/// <code>
/// var fname = "logfile.log.bz2";
/// using (var fs = File.OpenRead(fname))
/// {
/// using (var decompressor = new Ionic.BZip2.BZip2InputStream(fs))
/// {
/// var outFname = fname + ".decompressed";
/// using (var output = File.Create(outFname))
/// {
/// byte[] buffer = new byte[2048];
/// int n;
/// while ((n = decompressor.Read(buffer, 0, buffer.Length)) > 0)
/// {
/// output.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public BZip2InputStream(Stream input, bool leaveOpen)
: base()
{
this.input = input;
this._leaveOpen = leaveOpen;
init();
}
/// <summary>
/// Read data from the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// To decompress a BZip2 data stream, create a <c>BZip2InputStream</c>,
/// providing a stream that reads compressed data. Then call Read() on
/// that <c>BZip2InputStream</c>, and the data read will be decompressed
/// as you read.
/// </para>
///
/// <para>
/// A <c>BZip2InputStream</c> can be used only for <c>Read()</c>, not for <c>Write()</c>.
/// </para>
/// </remarks>
///
/// <param name="buffer">The buffer into which the read 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 (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
if (count < 0)
throw new IndexOutOfRangeException(String.Format("count ({0}) must be > 0", count));
if (offset + count > buffer.Length)
throw new IndexOutOfRangeException(String.Format("offset({0}) count({1}) bLength({2})",
offset, count, buffer.Length));
if (this.input == null)
throw new IOException("the stream is not open");
int hi = offset + count;
int destOffset = offset;
for (int b; (destOffset < hi) && ((b = ReadByte()) >= 0);)
{
buffer[destOffset++] = (byte) b;
}
return (destOffset == offset) ? -1 : (destOffset - offset);
}
private void MakeMaps()
{
bool[] inUse = this.data.inUse;
byte[] seqToUnseq = this.data.seqToUnseq;
int n = 0;
for (int i = 0; i < 256; i++)
{
if (inUse[i])
seqToUnseq[n++] = (byte) i;
}
this.nInUse = n;
}
/// <summary>
/// Read a single byte from the stream.
/// </summary>
/// <returns>the byte read from the stream, or -1 if EOF</returns>
public override int ReadByte()
{
int retChar = this.currentChar;
totalBytesRead++;
switch (this.currentState)
{
case CState.EOF:
return -1;
case CState.START_BLOCK:
throw new IOException("bad state");
case CState.RAND_PART_A:
throw new IOException("bad state");
case CState.RAND_PART_B:
SetupRandPartB();
break;
case CState.RAND_PART_C:
SetupRandPartC();
break;
case CState.NO_RAND_PART_A:
throw new IOException("bad state");
case CState.NO_RAND_PART_B:
SetupNoRandPartB();
break;
case CState.NO_RAND_PART_C:
SetupNoRandPartC();
break;
default:
throw new IOException("bad state");
}
return retChar;
}
/// <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("BZip2Stream");
return this.input.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("BZip2Stream");
return input.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
input.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 number of uncompressed bytes read in.
/// </remarks>
public override long Position
{
get
{
return this.totalBytesRead;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name='buffer'>this parameter is never used</param>
/// <param name='offset'>this parameter is never used</param>
/// <param name='count'>this parameter is never used</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <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 && (this.input != null))
this.input.Close();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
void init()
{
if (null == this.input)
throw new IOException("No input Stream");
if (!this.input.CanRead)
throw new IOException("Unreadable input Stream");
CheckMagicChar('B', 0);
CheckMagicChar('Z', 1);
CheckMagicChar('h', 2);
int blockSize = this.input.ReadByte();
if ((blockSize < '1') || (blockSize > '9'))
throw new IOException("Stream is not BZip2 formatted: illegal "
+ "blocksize " + (char) blockSize);
this.blockSize100k = blockSize - '0';
InitBlock();
SetupBlock();
}
void CheckMagicChar(char expected, int position)
{
int magic = this.input.ReadByte();
if (magic != (int)expected)
{
var msg = String.Format("Not a valid BZip2 stream. byte {0}, expected '{1}', got '{2}'",
position, (int)expected, magic);
throw new IOException(msg);
}
}
void InitBlock()
{
char magic0 = bsGetUByte();
char magic1 = bsGetUByte();
char magic2 = bsGetUByte();
char magic3 = bsGetUByte();
char magic4 = bsGetUByte();
char magic5 = bsGetUByte();
if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45
&& magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90)
{
complete(); // end of file
}
else if (magic0 != 0x31 ||
magic1 != 0x41 ||
magic2 != 0x59 ||
magic3 != 0x26 ||
magic4 != 0x53 ||
magic5 != 0x59)
{
this.currentState = CState.EOF;
var msg = String.Format("bad block header at offset 0x{0:X}",
this.input.Position);
throw new IOException(msg);
}
else
{
this.storedBlockCRC = bsGetInt();
// Console.WriteLine(" stored block CRC : {0:X8}", this.storedBlockCRC);
this.blockRandomised = (GetBits(1) == 1);
// Lazily allocate data
if (this.data == null)
this.data = new DecompressionState(this.blockSize100k);
// currBlockNo++;
getAndMoveToFrontDecode();
this.crc.Reset();
this.currentState = CState.START_BLOCK;
}
}
private void EndBlock()
{
this.computedBlockCRC = (uint)this.crc.Crc32Result;
// A bad CRC is considered a fatal error.
if (this.storedBlockCRC != this.computedBlockCRC)
{
// make next blocks readable without error
// (repair feature, not yet documented, not tested)
// this.computedCombinedCRC = (this.storedCombinedCRC << 1)
// | (this.storedCombinedCRC >> 31);
// this.computedCombinedCRC ^= this.storedBlockCRC;
var msg = String.Format("BZip2 CRC error (expected {0:X8}, computed {1:X8})",
this.storedBlockCRC, this.computedBlockCRC);
throw new IOException(msg);
}
// Console.WriteLine(" combined CRC (before): {0:X8}", this.computedCombinedCRC);
this.computedCombinedCRC = (this.computedCombinedCRC << 1)
| (this.computedCombinedCRC >> 31);
this.computedCombinedCRC ^= this.computedBlockCRC;
// Console.WriteLine(" computed block CRC : {0:X8}", this.computedBlockCRC);
// Console.WriteLine(" combined CRC (after) : {0:X8}", this.computedCombinedCRC);
// Console.WriteLine();
}
private void complete()
{
this.storedCombinedCRC = bsGetInt();
this.currentState = CState.EOF;
this.data = null;
if (this.storedCombinedCRC != this.computedCombinedCRC)
{
var msg = String.Format("BZip2 CRC error (expected {0:X8}, computed {1:X8})",
this.storedCombinedCRC, this.computedCombinedCRC);
throw new IOException(msg);
}
}
/// <summary>
/// Close the stream.
/// </summary>
public override void Close()
{
Stream inShadow = this.input;
if (inShadow != null)
{
try
{
if (!this._leaveOpen)
inShadow.Close();
}
finally
{
this.data = null;
this.input = null;
}
}
}
/// <summary>
/// Read n bits from input, right justifying the result.
/// </summary>
/// <remarks>
/// <para>
/// For example, if you read 1 bit, the result is either 0
/// or 1.
/// </para>
/// </remarks>
/// <param name ="n">
/// The number of bits to read, always between 1 and 32.
/// </param>
private int GetBits(int n)
{
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
if (bsLiveShadow < n)
{
do
{
int thech = this.input.ReadByte();
if (thech < 0)
throw new IOException("unexpected end of stream");
// Console.WriteLine("R {0:X2}", thech);
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
} while (bsLiveShadow < n);
this.bsBuff = bsBuffShadow;
}
this.bsLive = bsLiveShadow - n;
return (bsBuffShadow >> (bsLiveShadow - n)) & ((1 << n) - 1);
}
// private bool bsGetBit()
// {
// int bsLiveShadow = this.bsLive;
// int bsBuffShadow = this.bsBuff;
//
// if (bsLiveShadow < 1)
// {
// int thech = this.input.ReadByte();
//
// if (thech < 0)
// {
// throw new IOException("unexpected end of stream");
// }
//
// bsBuffShadow = (bsBuffShadow << 8) | thech;
// bsLiveShadow += 8;
// this.bsBuff = bsBuffShadow;
// }
//
// this.bsLive = bsLiveShadow - 1;
// return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0;
// }
private bool bsGetBit()
{
int bit = GetBits(1);
return bit != 0;
}
private char bsGetUByte()
{
return (char) GetBits(8);
}
private uint bsGetInt()
{
return (uint)((((((GetBits(8) << 8) | GetBits(8)) << 8) | GetBits(8)) << 8) | GetBits(8));
}
/**
* Called by createHuffmanDecodingTables() exclusively.
*/
private static void hbCreateDecodeTables(int[] limit,
int[] bbase, int[] perm, char[] length,
int minLen, int maxLen, int alphaSize)
{
for (int i = minLen, pp = 0; i <= maxLen; i++)
{
for (int j = 0; j < alphaSize; j++)
{
if (length[j] == i)
{
perm[pp++] = j;
}
}
}
for (int i = BZip2.MaxCodeLength; --i > 0;)
{
bbase[i] = 0;
limit[i] = 0;
}
for (int i = 0; i < alphaSize; i++)
{
bbase[length[i] + 1]++;
}
for (int i = 1, b = bbase[0]; i < BZip2.MaxCodeLength; i++)
{
b += bbase[i];
bbase[i] = b;
}
for (int i = minLen, vec = 0, b = bbase[i]; i <= maxLen; i++)
{
int nb = bbase[i + 1];
vec += nb - b;
b = nb;
limit[i] = vec - 1;
vec <<= 1;
}
for (int i = minLen + 1; i <= maxLen; i++)
{
bbase[i] = ((limit[i - 1] + 1) << 1) - bbase[i];
}
}
private void recvDecodingTables()
{
var s = this.data;
bool[] inUse = s.inUse;
byte[] pos = s.recvDecodingTables_pos;
//byte[] selector = s.selector;
int inUse16 = 0;
/* Receive the mapping table */
for (int i = 0; i < 16; i++)
{
if (bsGetBit())
{
inUse16 |= 1 << i;
}
}
for (int i = 256; --i >= 0;)
{
inUse[i] = false;
}
for (int i = 0; i < 16; i++)
{
if ((inUse16 & (1 << i)) != 0)
{
int i16 = i << 4;
for (int j = 0; j < 16; j++)
{
if (bsGetBit())
{
inUse[i16 + j] = true;
}
}
}
}
MakeMaps();
int alphaSize = this.nInUse + 2;
/* Now the selectors */
int nGroups = GetBits(3);
int nSelectors = GetBits(15);
for (int i = 0; i < nSelectors; i++)
{
int j = 0;
while (bsGetBit())
{
j++;
}
s.selectorMtf[i] = (byte) j;
}
/* Undo the MTF values for the selectors. */
for (int v = nGroups; --v >= 0;)
{
pos[v] = (byte) v;
}
for (int i = 0; i < nSelectors; i++)
{
int v = s.selectorMtf[i];
byte tmp = pos[v];
while (v > 0)
{
// nearly all times v is zero, 4 in most other cases
pos[v] = pos[v - 1];
v--;
}
pos[0] = tmp;
s.selector[i] = tmp;
}
char[][] len = s.temp_charArray2d;
/* Now the coding tables */
for (int t = 0; t < nGroups; t++)
{
int curr = GetBits(5);
char[] len_t = len[t];
for (int i = 0; i < alphaSize; i++)
{
while (bsGetBit())
{
curr += bsGetBit() ? -1 : 1;
}
len_t[i] = (char) curr;
}
}
// finally create the Huffman tables
createHuffmanDecodingTables(alphaSize, nGroups);
}
/**
* Called by recvDecodingTables() exclusively.
*/
private void createHuffmanDecodingTables(int alphaSize,
int nGroups)
{
var s = this.data;
char[][] len = s.temp_charArray2d;
for (int t = 0; t < nGroups; t++)
{
int minLen = 32;
int maxLen = 0;
char[] len_t = len[t];
for (int i = alphaSize; --i >= 0;)
{
char lent = len_t[i];
if (lent > maxLen)
maxLen = lent;
if (lent < minLen)
minLen = lent;
}
hbCreateDecodeTables(s.gLimit[t], s.gBase[t], s.gPerm[t], len[t], minLen,
maxLen, alphaSize);
s.gMinlen[t] = minLen;
}
}
private void getAndMoveToFrontDecode()
{
var s = this.data;
this.origPtr = GetBits(24);
if (this.origPtr < 0)
throw new IOException("BZ_DATA_ERROR");
if (this.origPtr > 10 + BZip2.BlockSizeMultiple * this.blockSize100k)
throw new IOException("BZ_DATA_ERROR");
recvDecodingTables();
byte[] yy = s.getAndMoveToFrontDecode_yy;
int limitLast = this.blockSize100k * BZip2.BlockSizeMultiple;
/*
* Setting up the unzftab entries here is not strictly necessary, but it
* does save having to do it later in a separate pass, and so saves a
* block's worth of cache misses.
*/
for (int i = 256; --i >= 0;)
{
yy[i] = (byte) i;
s.unzftab[i] = 0;
}
int groupNo = 0;
int groupPos = BZip2.G_SIZE - 1;
int eob = this.nInUse + 1;
int nextSym = getAndMoveToFrontDecode0(0);
int bsBuffShadow = this.bsBuff;
int bsLiveShadow = this.bsLive;
int lastShadow = -1;
int zt = s.selector[groupNo] & 0xff;
int[] base_zt = s.gBase[zt];
int[] limit_zt = s.gLimit[zt];
int[] perm_zt = s.gPerm[zt];
int minLens_zt = s.gMinlen[zt];
while (nextSym != eob)
{
if ((nextSym == BZip2.RUNA) || (nextSym == BZip2.RUNB))
{
int es = -1;
for (int n = 1; true; n <<= 1)
{
if (nextSym == BZip2.RUNA)
{
es += n;
}
else if (nextSym == BZip2.RUNB)
{
es += n << 1;
}
else
{
break;
}
if (groupPos == 0)
{
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
}
else
{
groupPos--;
}
int zn = minLens_zt;
// Inlined:
// int zvec = GetBits(zn);
while (bsLiveShadow < zn)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
int zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1)
| ((bsBuffShadow >> bsLiveShadow) & 1);
}
nextSym = perm_zt[zvec - base_zt[zn]];
}
byte ch = s.seqToUnseq[yy[0]];
s.unzftab[ch & 0xff] += es + 1;
while (es-- >= 0)
{
s.ll8[++lastShadow] = ch;
}
if (lastShadow >= limitLast)
throw new IOException("block overrun");
}
else
{
if (++lastShadow >= limitLast)
throw new IOException("block overrun");
byte tmp = yy[nextSym - 1];
s.unzftab[s.seqToUnseq[tmp] & 0xff]++;
s.ll8[lastShadow] = s.seqToUnseq[tmp];
/*
* This loop is hammered during decompression, hence avoid
* native method call overhead of System.Buffer.BlockCopy for very
* small ranges to copy.
*/
if (nextSym <= 16)
{
for (int j = nextSym - 1; j > 0;)
{
yy[j] = yy[--j];
}
}
else
{
System.Buffer.BlockCopy(yy, 0, yy, 1, nextSym - 1);
}
yy[0] = tmp;
if (groupPos == 0)
{
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
}
else
{
groupPos--;
}
int zn = minLens_zt;
// Inlined:
// int zvec = GetBits(zn);
while (bsLiveShadow < zn)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
int zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1);
}
nextSym = perm_zt[zvec - base_zt[zn]];
}
}
this.last = lastShadow;
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
}
private int getAndMoveToFrontDecode0(int groupNo)
{
var s = this.data;
int zt = s.selector[groupNo] & 0xff;
int[] limit_zt = s.gLimit[zt];
int zn = s.gMinlen[zt];
int zvec = GetBits(zn);
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
while (zvec > limit_zt[zn])
{
zn++;
while (bsLiveShadow < 1)
{
int thech = this.input.ReadByte();
if (thech >= 0)
{
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
}
else
{
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1);
}
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
return s.gPerm[zt][zvec - s.gBase[zt][zn]];
}
private void SetupBlock()
{
if (this.data == null)
return;
int i;
var s = this.data;
int[] tt = s.initTT(this.last + 1);
// xxxx
/* Check: unzftab entries in range. */
for (i = 0; i <= 255; i++)
{
if (s.unzftab[i] < 0 || s.unzftab[i] > this.last)
throw new Exception("BZ_DATA_ERROR");
}
/* Actually generate cftab. */
s.cftab[0] = 0;
for (i = 1; i <= 256; i++) s.cftab[i] = s.unzftab[i-1];
for (i = 1; i <= 256; i++) s.cftab[i] += s.cftab[i-1];
/* Check: cftab entries in range. */
for (i = 0; i <= 256; i++)
{
if (s.cftab[i] < 0 || s.cftab[i] > this.last+1)
{
var msg = String.Format("BZ_DATA_ERROR: cftab[{0}]={1} last={2}",
i, s.cftab[i], this.last);
throw new Exception(msg);
}
}
/* Check: cftab entries non-descending. */
for (i = 1; i <= 256; i++)
{
if (s.cftab[i-1] > s.cftab[i])
throw new Exception("BZ_DATA_ERROR");
}
int lastShadow;
for (i = 0, lastShadow = this.last; i <= lastShadow; i++)
{
tt[s.cftab[s.ll8[i] & 0xff]++] = i;
}
if ((this.origPtr < 0) || (this.origPtr >= tt.Length))
throw new IOException("stream corrupted");
this.su_tPos = tt[this.origPtr];
this.su_count = 0;
this.su_i2 = 0;
this.su_ch2 = 256; /* not a valid 8-bit byte value?, and not EOF */
if (this.blockRandomised)
{
this.su_rNToGo = 0;
this.su_rTPos = 0;
SetupRandPartA();
}
else
{
SetupNoRandPartA();
}
}
private void SetupRandPartA()
{
if (this.su_i2 <= this.last)
{
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0)
{
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
if (++this.su_rTPos == 512)
{
this.su_rTPos = 0;
}
}
else
{
this.su_rNToGo--;
}
this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0;
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = CState.RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
}
else
{
EndBlock();
InitBlock();
SetupBlock();
}
}
private void SetupNoRandPartA()
{
if (this.su_i2 <= this.last)
{
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_ch2 = su_ch2Shadow;
this.su_tPos = this.data.tt[this.su_tPos];
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = CState.NO_RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
}
else
{
this.currentState = CState.NO_RAND_PART_A;
EndBlock();
InitBlock();
SetupBlock();
}
}
private void SetupRandPartB()
{
if (this.su_ch2 != this.su_chPrev)
{
this.currentState = CState.RAND_PART_A;
this.su_count = 1;
SetupRandPartA();
}
else if (++this.su_count >= 4)
{
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0)
{
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
if (++this.su_rTPos == 512)
{
this.su_rTPos = 0;
}
}
else
{
this.su_rNToGo--;
}
this.su_j2 = 0;
this.currentState = CState.RAND_PART_C;
if (this.su_rNToGo == 1)
{
this.su_z ^= (char)1;
}
SetupRandPartC();
}
else
{
this.currentState = CState.RAND_PART_A;
SetupRandPartA();
}
}
private void SetupRandPartC()
{
if (this.su_j2 < this.su_z)
{
this.currentChar = this.su_ch2;
this.crc.UpdateCRC((byte)this.su_ch2);
this.su_j2++;
}
else
{
this.currentState = CState.RAND_PART_A;
this.su_i2++;
this.su_count = 0;
SetupRandPartA();
}
}
private void SetupNoRandPartB()
{
if (this.su_ch2 != this.su_chPrev)
{
this.su_count = 1;
SetupNoRandPartA();
}
else if (++this.su_count >= 4)
{
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
this.su_j2 = 0;
SetupNoRandPartC();
}
else
{
SetupNoRandPartA();
}
}
private void SetupNoRandPartC()
{
if (this.su_j2 < this.su_z)
{
int su_ch2Shadow = this.su_ch2;
this.currentChar = su_ch2Shadow;
this.crc.UpdateCRC((byte)su_ch2Shadow);
this.su_j2++;
this.currentState = CState.NO_RAND_PART_C;
}
else
{
this.su_i2++;
this.su_count = 0;
SetupNoRandPartA();
}
}
private sealed class DecompressionState
{
// (with blockSize 900k)
readonly public bool[] inUse = new bool[256];
readonly public byte[] seqToUnseq = new byte[256]; // 256 byte
readonly public byte[] selector = new byte[BZip2.MaxSelectors]; // 18002 byte
readonly public byte[] selectorMtf = new byte[BZip2.MaxSelectors]; // 18002 byte
/**
* Freq table collected to save a pass over the data during
* decompression.
*/
public readonly int[] unzftab;
public readonly int[][] gLimit;
public readonly int[][] gBase;
public readonly int[][] gPerm;
public readonly int[] gMinlen;
public readonly int[] cftab;
public readonly byte[] getAndMoveToFrontDecode_yy;
public readonly char[][] temp_charArray2d;
public readonly byte[] recvDecodingTables_pos;
// ---------------
// 60798 byte
public int[] tt; // 3600000 byte
public byte[] ll8; // 900000 byte
// ---------------
// 4560782 byte
// ===============
public DecompressionState(int blockSize100k)
{
this.unzftab = new int[256]; // 1024 byte
this.gLimit = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gBase = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gPerm = BZip2.InitRectangularArray<int>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.gMinlen = new int[BZip2.NGroups]; // 24 byte
this.cftab = new int[257]; // 1028 byte
this.getAndMoveToFrontDecode_yy = new byte[256]; // 512 byte
this.temp_charArray2d = BZip2.InitRectangularArray<char>(BZip2.NGroups,BZip2.MaxAlphaSize);
this.recvDecodingTables_pos = new byte[BZip2.NGroups]; // 6 byte
this.ll8 = new byte[blockSize100k * BZip2.BlockSizeMultiple];
}
/**
* Initializes the tt array.
*
* This method is called when the required length of the array is known.
* I don't initialize it at construction time to avoid unneccessary
* memory allocation when compressing small files.
*/
public int[] initTT(int length)
{
int[] ttShadow = this.tt;
// tt.length should always be >= length, but theoretically
// it can happen, if the compressor mixed small and large
// blocks. Normally only the last block will be smaller
// than others.
if ((ttShadow == null) || (ttShadow.Length < length))
{
this.tt = ttShadow = new int[length];
}
return ttShadow;
}
}
}
// /**
// * Checks if the signature matches what is expected for a bzip2 file.
// *
// * @param signature
// * the bytes to check
// * @param length
// * the number of bytes to check
// * @return true, if this stream is a bzip2 compressed stream, false otherwise
// *
// * @since Apache Commons Compress 1.1
// */
// public static boolean MatchesSig(byte[] signature)
// {
// if ((signature.Length < 3) ||
// (signature[0] != 'B') ||
// (signature[1] != 'Z') ||
// (signature[2] != 'h'))
// return false;
//
// return true;
// }
internal static class BZip2
{
internal static T[][] InitRectangularArray<T>(int d1, int d2)
{
var x = new T[d1][];
for (int i=0; i < d1; i++)
{
x[i] = new T[d2];
}
return x;
}
public static readonly int BlockSizeMultiple = 100000;
public static readonly int MinBlockSize = 1;
public static readonly int MaxBlockSize = 9;
public static readonly int MaxAlphaSize = 258;
public static readonly int MaxCodeLength = 23;
public static readonly char RUNA = (char) 0;
public static readonly char RUNB = (char) 1;
public static readonly int NGroups = 6;
public static readonly int G_SIZE = 50;
public static readonly int N_ITERS = 4;
public static readonly int MaxSelectors = (2 + (900000 / G_SIZE));
public static readonly int NUM_OVERSHOOT_BYTES = 20;
/*
* <p> If you are ever unlucky/improbable enough to get a stack
* overflow whilst sorting, increase the following constant and
* try again. In practice I have never seen the stack go above 27
* elems, so the following limit seems very generous. </p>
*/
internal static readonly int QSORT_STACK_SIZE = 1000;
}
}
| |
// 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.Contracts;
using System.Runtime.Serialization;
namespace System
{
public sealed partial class TimeZoneInfo
{
[Serializable]
public sealed class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
{
private readonly DateTime _dateStart;
private readonly DateTime _dateEnd;
private readonly TimeSpan _daylightDelta;
private readonly TransitionTime _daylightTransitionStart;
private readonly TransitionTime _daylightTransitionEnd;
private readonly TimeSpan _baseUtcOffsetDelta; // delta from the default Utc offset (utcOffset = defaultUtcOffset + _baseUtcOffsetDelta)
private readonly bool _noDaylightTransitions;
public DateTime DateStart => _dateStart;
public DateTime DateEnd => _dateEnd;
public TimeSpan DaylightDelta => _daylightDelta;
public TransitionTime DaylightTransitionStart => _daylightTransitionStart;
public TransitionTime DaylightTransitionEnd => _daylightTransitionEnd;
internal TimeSpan BaseUtcOffsetDelta => _baseUtcOffsetDelta;
/// <summary>
/// Gets a value indicating that this AdjustmentRule fixes the time zone offset
/// from DateStart to DateEnd without any daylight transitions in between.
/// </summary>
internal bool NoDaylightTransitions => _noDaylightTransitions;
internal bool HasDaylightSaving =>
DaylightDelta != TimeSpan.Zero ||
(DaylightTransitionStart != default(TransitionTime) && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) ||
(DaylightTransitionEnd != default(TransitionTime) && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1));
public bool Equals(AdjustmentRule other) =>
other != null &&
_dateStart == other._dateStart &&
_dateEnd == other._dateEnd &&
_daylightDelta == other._daylightDelta &&
_baseUtcOffsetDelta == other._baseUtcOffsetDelta &&
_daylightTransitionEnd.Equals(other._daylightTransitionEnd) &&
_daylightTransitionStart.Equals(other._daylightTransitionStart);
public override int GetHashCode() => _dateStart.GetHashCode();
private AdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
TimeSpan baseUtcOffsetDelta,
bool noDaylightTransitions)
{
ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
_dateStart = dateStart;
_dateEnd = dateEnd;
_daylightDelta = daylightDelta;
_daylightTransitionStart = daylightTransitionStart;
_daylightTransitionEnd = daylightTransitionEnd;
_baseUtcOffsetDelta = baseUtcOffsetDelta;
_noDaylightTransitions = noDaylightTransitions;
}
public static AdjustmentRule CreateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd)
{
return new AdjustmentRule(
dateStart,
dateEnd,
daylightDelta,
daylightTransitionStart,
daylightTransitionEnd,
baseUtcOffsetDelta: TimeSpan.Zero,
noDaylightTransitions: false);
}
internal static AdjustmentRule CreateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
TimeSpan baseUtcOffsetDelta,
bool noDaylightTransitions)
{
return new AdjustmentRule(
dateStart,
dateEnd,
daylightDelta,
daylightTransitionStart,
daylightTransitionEnd,
baseUtcOffsetDelta,
noDaylightTransitions);
}
//
// When Windows sets the daylight transition start Jan 1st at 12:00 AM, it means the year starts with the daylight saving on.
// We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
//
internal bool IsStartDateMarkerForBeginningOfYear() =>
!NoDaylightTransitions &&
DaylightTransitionStart.Month == 1 && DaylightTransitionStart.Day == 1 && DaylightTransitionStart.TimeOfDay.Hour == 0 &&
DaylightTransitionStart.TimeOfDay.Minute == 0 && DaylightTransitionStart.TimeOfDay.Second == 0 &&
_dateStart.Year == _dateEnd.Year;
//
// When Windows sets the daylight transition end Jan 1st at 12:00 AM, it means the year ends with the daylight saving on.
// We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
//
internal bool IsEndDateMarkerForEndOfYear() =>
!NoDaylightTransitions &&
DaylightTransitionEnd.Month == 1 && DaylightTransitionEnd.Day == 1 && DaylightTransitionEnd.TimeOfDay.Hour == 0 &&
DaylightTransitionEnd.TimeOfDay.Minute == 0 && DaylightTransitionEnd.TimeOfDay.Second == 0 &&
_dateStart.Year == _dateEnd.Year;
/// <summary>
/// Helper function that performs all of the validation checks for the actory methods and deserialization callback.
/// </summary>
private static void ValidateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
bool noDaylightTransitions)
{
if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateStart));
}
if (dateEnd.Kind != DateTimeKind.Unspecified && dateEnd.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateEnd));
}
if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions)
{
throw new ArgumentException(SR.Argument_TransitionTimesAreIdentical, nameof(daylightTransitionEnd));
}
if (dateStart > dateEnd)
{
throw new ArgumentException(SR.Argument_OutOfOrderDateTimes, nameof(dateStart));
}
// This cannot use UtcOffsetOutOfRange to account for the scenario where Samoa moved across the International Date Line,
// which caused their current BaseUtcOffset to be +13. But on the other side of the line it was UTC-11 (+1 for daylight).
// So when trying to describe DaylightDeltas for those times, the DaylightDelta needs
// to be -23 (what it takes to go from UTC+13 to UTC-10)
if (daylightDelta.TotalHours < -23.0 || daylightDelta.TotalHours > 14.0)
{
throw new ArgumentOutOfRangeException(nameof(daylightDelta), daylightDelta, SR.ArgumentOutOfRange_UtcOffset);
}
if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0)
{
throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(daylightDelta));
}
if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero)
{
throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateStart));
}
if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero)
{
throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateEnd));
}
Contract.EndContractBlock();
}
void IDeserializationCallback.OnDeserialization(object sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs AdjustmentRule validation after being deserialized.
try
{
ValidateAdjustmentRule(_dateStart, _dateEnd, _daylightDelta,
_daylightTransitionStart, _daylightTransitionEnd, _noDaylightTransitions);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
info.AddValue("DateStart", _dateStart);
info.AddValue("DateEnd", _dateEnd);
info.AddValue("DaylightDelta", _daylightDelta);
info.AddValue("DaylightTransitionStart", _daylightTransitionStart);
info.AddValue("DaylightTransitionEnd", _daylightTransitionEnd);
info.AddValue("BaseUtcOffsetDelta", _baseUtcOffsetDelta);
info.AddValue("NoDaylightTransitions", _noDaylightTransitions);
}
private AdjustmentRule(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
_dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime));
_dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime));
_daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan));
_daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime));
_daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime));
object o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan));
if (o != null)
{
_baseUtcOffsetDelta = (TimeSpan)o;
}
o = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool));
if (o != null)
{
_noDaylightTransitions = (bool)o;
}
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace OmniSharp.Intellisense
{
static class StringExtensions
{
public static int? GetFirstNonWhitespaceOffset(this string line)
{
// Contract.ThrowIfNull(line);
for (int i = 0; i < line.Length; i++)
{
if (!char.IsWhiteSpace(line[i]))
{
return i;
}
}
return null;
}
public static string GetLeadingWhitespace(this string lineText)
{
// Contract.ThrowIfNull(lineText);
var firstOffset = lineText.GetFirstNonWhitespaceOffset();
return firstOffset.HasValue
? lineText.Substring(0, firstOffset.Value)
: lineText;
}
public static int GetTextColumn(this string text, int tabSize, int initialColumn)
{
var lineText = text.GetLastLineText();
if (text != lineText)
{
return lineText.GetColumnFromLineOffset(lineText.Length, tabSize);
}
return text.ConvertTabToSpace(tabSize, initialColumn, text.Length) + initialColumn;
}
public static int ConvertTabToSpace(this string textSnippet, int tabSize, int initialColumn, int endPosition)
{
// Contract.Requires(tabSize > 0);
// Contract.Requires(endPosition >= 0 && endPosition <= textSnippet.Length);
int column = initialColumn;
// now this will calculate indentation regardless of actual content on the buffer except TAB
for (int i = 0; i < endPosition; i++)
{
if (textSnippet[i] == '\t')
{
column += tabSize - column % tabSize;
}
else
{
column++;
}
}
return column - initialColumn;
}
public static int IndexOf(this string text, Func<char, bool> predicate)
{
if (text == null)
{
return -1;
}
for (int i = 0; i < text.Length; i++)
{
if (predicate(text[i]))
{
return i;
}
}
return -1;
}
public static string GetFirstLineText(this string text)
{
var lineBreak = text.IndexOf('\n');
if (lineBreak < 0)
{
return text;
}
return text.Substring(0, lineBreak + 1);
}
public static string GetLastLineText(this string text)
{
var lineBreak = text.LastIndexOf('\n');
if (lineBreak < 0)
{
return text;
}
return text.Substring(lineBreak + 1);
}
public static bool ContainsLineBreak(this string text)
{
foreach (char ch in text)
{
if (ch == '\n' || ch == '\r')
{
return true;
}
}
return false;
}
public static int GetNumberOfLineBreaks(this string text)
{
int lineBreaks = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
lineBreaks++;
}
else if (text[i] == '\r')
{
if (i + 1 == text.Length || text[i + 1] != '\n')
{
lineBreaks++;
}
}
}
return lineBreaks;
}
public static bool ContainsTab(this string text)
{
// PERF: Tried replacing this with "text.IndexOf('\t')>=0", but that was actually slightly slower
foreach (char ch in text)
{
if (ch == '\t')
{
return true;
}
}
return false;
}
public static ImmutableArray<SymbolDisplayPart> ToSymbolDisplayParts(this string text)
{
return ImmutableArray.Create<SymbolDisplayPart>(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text));
}
public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this string line, int tabSize)
{
var firstNonWhitespaceChar = line.GetFirstNonWhitespaceOffset();
if (firstNonWhitespaceChar.HasValue)
{
return line.GetColumnFromLineOffset(firstNonWhitespaceChar.Value, tabSize);
}
else
{
// It's all whitespace, so go to the end
return line.GetColumnFromLineOffset(line.Length, tabSize);
}
}
public static int GetColumnFromLineOffset(this string line, int endPosition, int tabSize)
{
// Contract.ThrowIfNull(line);
// Contract.ThrowIfFalse(0 <= endPosition && endPosition <= line.Length);
// Contract.ThrowIfFalse(tabSize > 0);
return ConvertTabToSpace(line, tabSize, 0, endPosition);
}
public static int GetLineOffsetFromColumn(this string line, int column, int tabSize)
{
// Contract.ThrowIfNull(line);
// Contract.ThrowIfFalse(column >= 0);
// Contract.ThrowIfFalse(tabSize > 0);
var currentColumn = 0;
for (int i = 0; i < line.Length; i++)
{
if (currentColumn >= column)
{
return i;
}
if (line[i] == '\t')
{
currentColumn += tabSize - (currentColumn % tabSize);
}
else
{
currentColumn++;
}
}
// We're asking for a column past the end of the line, so just go to the end.
return line.Length;
}
// public static void AppendToAliasNameSet(this string alias, ImmutableHashSet<string>.Builder builder)
// {
// if (string.IsNullOrWhiteSpace(alias))
// {
// return;
// }
//
// builder.Add(alias);
//
// var caseSensitive = builder.KeyComparer == StringComparer.Ordinal;
// // Contract.Requires(builder.KeyComparer == StringComparer.Ordinal || builder.KeyComparer == StringComparer.OrdinalIgnoreCase);
//
// string aliasWithoutAttribute;
// if (alias.TryGetWithoutAttributeSuffix(caseSensitive, out aliasWithoutAttribute))
// {
// builder.Add(aliasWithoutAttribute);
// return;
// }
//
// builder.Add(alias.GetWithSingleAttributeSuffix(caseSensitive));
// }
private static ImmutableArray<string> s_lazyNumerals;
internal static string GetNumeral(int number)
{
var numerals = s_lazyNumerals;
if (numerals.IsDefault)
{
numerals = ImmutableArray.Create("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
ImmutableInterlocked.InterlockedInitialize(ref s_lazyNumerals, numerals);
}
Debug.Assert(number >= 0);
return (number < numerals.Length) ? numerals[number] : number.ToString();
}
public static string Join(this IEnumerable<string> source, string separator)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (separator == null)
{
throw new ArgumentNullException("separator");
}
return string.Join(separator, source);
}
public static bool LooksLikeInterfaceName(this string name)
{
return name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2]);
}
public static bool LooksLikeTypeParameterName(this string name)
{
return name.Length >= 3 && name[0] == 'T' && char.IsUpper(name[1]) && char.IsLower(name[2]);
}
private static readonly Func<char, char> s_toLower = char.ToLower;
private static readonly Func<char, char> s_toUpper = char.ToUpper;
public static string ToPascalCase(
this string shortName,
bool trimLeadingTypePrefix = true)
{
return ConvertCase(shortName, trimLeadingTypePrefix, s_toUpper);
}
public static string ToCamelCase(
this string shortName,
bool trimLeadingTypePrefix = true)
{
return ConvertCase(shortName, trimLeadingTypePrefix, s_toLower);
}
private static string ConvertCase(
this string shortName,
bool trimLeadingTypePrefix,
Func<char, char> convert)
{
// Special case the common .net pattern of "IFoo" as a type name. In this case we
// want to generate "foo" as the parameter name.
if (!string.IsNullOrEmpty(shortName))
{
if (trimLeadingTypePrefix && (shortName.LooksLikeInterfaceName() || shortName.LooksLikeTypeParameterName()))
{
return convert(shortName[1]) + shortName.Substring(2);
}
if (convert(shortName[0]) != shortName[0])
{
return convert(shortName[0]) + shortName.Substring(1);
}
}
return shortName;
}
internal static bool IsValidClrTypeName(this string name)
{
return !string.IsNullOrEmpty(name) && name.IndexOf('\0') == -1;
}
/// <summary>
/// Checks if the given name is a sequence of valid CLR names separated by a dot.
/// </summary>
internal static bool IsValidClrNamespaceName(this string name)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
char lastChar = '.';
foreach (char c in name)
{
if (c == '\0' || (c == '.' && lastChar == '.'))
{
return false;
}
lastChar = c;
}
return lastChar != '.';
}
internal static string GetWithSingleAttributeSuffix(
this string name,
bool isCaseSensitive)
{
string cleaned = name;
while ((cleaned = GetWithoutAttributeSuffix(cleaned, isCaseSensitive)) != null)
{
name = cleaned;
}
return name + "Attribute";
}
internal static bool TryGetWithoutAttributeSuffix(
this string name,
out string result)
{
return TryGetWithoutAttributeSuffix(name, isCaseSensitive: true, result: out result);
}
internal static string GetWithoutAttributeSuffix(
this string name,
bool isCaseSensitive)
{
string result;
return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out result) ? result : null;
}
internal static bool TryGetWithoutAttributeSuffix(
this string name,
bool isCaseSensitive,
out string result)
{
const string AttributeSuffix = "Attribute";
var comparison = isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
if (name.Length > AttributeSuffix.Length && name.EndsWith(AttributeSuffix, comparison))
{
result = name.Substring(0, name.Length - AttributeSuffix.Length);
return true;
}
result = null;
return false;
}
internal static bool IsValidUnicodeString(this string str)
{
int i = 0;
while (i < str.Length)
{
char c = str[i++];
// (high surrogate, low surrogate) makes a valid pair, anything else is invalid:
if (char.IsHighSurrogate(c))
{
if (i < str.Length && char.IsLowSurrogate(str[i]))
{
i++;
}
else
{
// high surrogate not followed by low surrogate
return false;
}
}
else if (char.IsLowSurrogate(c))
{
// previous character wasn't a high surrogate
return false;
}
}
return true;
}
/// <summary>
/// Remove one set of leading and trailing double quote characters, if both are present.
/// </summary>
internal static string Unquote(this string arg)
{
bool quoted;
return Unquote(arg, out quoted);
}
internal static string Unquote(this string arg, out bool quoted)
{
if (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"')
{
quoted = true;
return arg.Substring(1, arg.Length - 2);
}
else
{
quoted = false;
return arg;
}
}
internal static int IndexOfBalancedParenthesis(this string str, int openingOffset, char closing)
{
char opening = str[openingOffset];
int depth = 1;
for (int i = openingOffset + 1; i < str.Length; i++)
{
var c = str[i];
if (c == opening)
{
depth++;
}
else if (c == closing)
{
depth--;
if (depth == 0)
{
return i;
}
}
}
return -1;
}
// String isn't IEnumerable<char> in the current Portable profile.
internal static char First(this string arg)
{
return arg[0];
}
// String isn't IEnumerable<char> in the current Portable profile.
internal static char Last(this string arg)
{
return arg[arg.Length - 1];
}
// String isn't IEnumerable<char> in the current Portable profile.
internal static bool All(this string arg, Predicate<char> predicate)
{
foreach (char c in arg)
{
if (!predicate(c))
{
return false;
}
}
return true;
}
public static string EscapeIdentifier(
this string identifier,
bool isQueryContext = false)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
// Check if we need to escape this contextual keyword
needsEscaping = needsEscaping || (isQueryContext && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(identifier)));
return needsEscaping ? "@" + identifier : identifier;
}
public static SyntaxToken ToIdentifierToken(
this string identifier,
bool isQueryContext = false)
{
var escaped = identifier.EscapeIdentifier(isQueryContext);
if (escaped.Length == 0 || escaped[0] != '@')
{
return SyntaxFactory.Identifier(escaped);
}
var unescaped = identifier.StartsWith("@", StringComparison.Ordinal)
? identifier.Substring(1)
: identifier;
var token = SyntaxFactory.Identifier(
default(SyntaxTriviaList), SyntaxKind.None, "@" + unescaped, unescaped, default(SyntaxTriviaList));
if (!identifier.StartsWith("@", StringComparison.Ordinal))
{
token = token.WithAdditionalAnnotations(Simplifier.Annotation);
}
return token;
}
public static IdentifierNameSyntax ToIdentifierName(this string identifier)
{
return SyntaxFactory.IdentifierName(identifier.ToIdentifierToken());
}
}
}
| |
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
using PriorityQueue = Lucene.Net.Util.PriorityQueue;
using System.Collections.Generic;
namespace Lucene.Net.Search.Spans
{
internal class NearSpansUnordered : PayloadSpans
{
private SpanNearQuery query;
private System.Collections.IList ordered = new System.Collections.ArrayList(); // spans in query order
private int slop; // from query
private SpansCell first; // linked list of spans
private SpansCell last; // sorted by doc only
private int totalLength; // sum of current lengths
private CellQueue queue; // sorted queue of spans
private SpansCell max; // max element in queue
private bool more = true; // true iff not done
private bool firstTime = true; // true before first next()
private class CellQueue : PriorityQueue
{
private void InitBlock(NearSpansUnordered enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private NearSpansUnordered enclosingInstance;
public NearSpansUnordered Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public CellQueue(NearSpansUnordered enclosingInstance, int size)
{
InitBlock(enclosingInstance);
Initialize(size);
}
public override bool LessThan(object o1, object o2)
{
SpansCell spans1 = (SpansCell) o1;
SpansCell spans2 = (SpansCell) o2;
if (spans1.Doc() == spans2.Doc())
{
return NearSpansOrdered.DocSpansOrdered(spans1, spans2);
}
else
{
return spans1.Doc() < spans2.Doc();
}
}
}
/// <summary>Wraps a Spans, and can be used to form a linked list. </summary>
private class SpansCell : PayloadSpans
{
private void InitBlock(NearSpansUnordered enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private NearSpansUnordered enclosingInstance;
public NearSpansUnordered Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private PayloadSpans spans;
internal SpansCell next;
private int length = - 1;
private int index;
public SpansCell(NearSpansUnordered enclosingInstance, PayloadSpans spans, int index)
{
InitBlock(enclosingInstance);
this.spans = spans;
this.index = index;
}
public virtual bool Next()
{
return Adjust(spans.Next());
}
public virtual bool SkipTo(int target)
{
return Adjust(spans.SkipTo(target));
}
private bool Adjust(bool condition)
{
if (length != - 1)
{
Enclosing_Instance.totalLength -= length; // subtract old length
}
if (condition)
{
length = End() - Start();
Enclosing_Instance.totalLength += length; // add new length
if (Enclosing_Instance.max == null || Doc() > Enclosing_Instance.max.Doc() || (Doc() == Enclosing_Instance.max.Doc()) && (End() > Enclosing_Instance.max.End()))
{
Enclosing_Instance.max = this;
}
}
Enclosing_Instance.more = condition;
return condition;
}
public virtual int Doc()
{
return spans.Doc();
}
public virtual int Start()
{
return spans.Start();
}
public virtual int End()
{
return spans.End();
}
public ICollection<byte[]> GetPayload()
{
return new List<byte[]>(spans.GetPayload());
}
public bool IsPayloadAvailable()
{
return spans.IsPayloadAvailable();
}
public override System.String ToString()
{
return spans.ToString() + "#" + index;
}
}
public NearSpansUnordered(SpanNearQuery query, IndexReader reader)
{
this.query = query;
this.slop = query.GetSlop();
SpanQuery[] clauses = query.GetClauses();
queue = new CellQueue(this, clauses.Length);
for (int i = 0; i < clauses.Length; i++)
{
SpansCell cell = new SpansCell(this, clauses[i].GetPayloadSpans(reader), i);
ordered.Add(cell);
}
}
public virtual bool Next()
{
if (firstTime)
{
InitList(true);
ListToQueue(); // initialize queue
firstTime = false;
}
else if (more)
{
if (Min().Next())
{
// trigger further scanning
queue.AdjustTop(); // maintain queue
}
else
{
more = false;
}
}
while (more)
{
bool queueStale = false;
if (Min().Doc() != max.Doc())
{
// maintain list
QueueToList();
queueStale = true;
}
// skip to doc w/ all clauses
while (more && first.Doc() < last.Doc())
{
more = first.SkipTo(last.Doc()); // skip first upto last
FirstToLast(); // and move it to the end
queueStale = true;
}
if (!more)
return false;
// found doc w/ all clauses
if (queueStale)
{
// maintain the queue
ListToQueue();
queueStale = false;
}
if (AtMatch())
{
return true;
}
more = Min().Next();
if (more)
{
queue.AdjustTop(); // maintain queue
}
}
return false; // no more matches
}
public virtual bool SkipTo(int target)
{
if (firstTime)
{
// initialize
InitList(false);
for (SpansCell cell = first; more && cell != null; cell = cell.next)
{
more = cell.SkipTo(target); // skip all
}
if (more)
{
ListToQueue();
}
firstTime = false;
}
else
{
// normal case
while (more && Min().Doc() < target)
{
// skip as needed
if (Min().SkipTo(target))
{
queue.AdjustTop();
}
else
{
more = false;
}
}
}
return more && (AtMatch() || Next());
}
private SpansCell Min()
{
return (SpansCell) queue.Top();
}
public virtual int Doc()
{
return Min().Doc();
}
public virtual int Start()
{
return Min().Start();
}
public virtual int End()
{
return max.End();
}
public ICollection<byte[]> GetPayload()
{
Dictionary<byte[], byte[]> matchPayload = new Dictionary<byte[], byte[]>();
for (SpansCell cell = first; cell != null; cell = cell.next)
if (cell.IsPayloadAvailable())
for (IEnumerator<byte[]> e = cell.GetPayload().GetEnumerator(); e.MoveNext(); )
matchPayload[e.Current] = e.Current;
return matchPayload.Keys;
}
public bool IsPayloadAvailable()
{
SpansCell pointer = Min();
while (pointer != null)
{
if (pointer.IsPayloadAvailable())
return true;
pointer = pointer.next;
}
return false;
}
public override System.String ToString()
{
return GetType().FullName + "(" + query.ToString() + ")@" + (firstTime ? "START" : (more ? (Doc() + ":" + Start() + "-" + End()) : "END"));
}
private void InitList(bool next)
{
for (int i = 0; more && i < ordered.Count; i++)
{
SpansCell cell = (SpansCell) ordered[i];
if (next)
more = cell.Next(); // move to first entry
if (more)
{
AddToList(cell); // add to list
}
}
}
private void AddToList(SpansCell cell)
{
if (last != null)
{
// add next to end of list
last.next = cell;
}
else
first = cell;
last = cell;
cell.next = null;
}
private void FirstToLast()
{
last.next = first; // move first to end of list
last = first;
first = first.next;
last.next = null;
}
private void QueueToList()
{
last = first = null;
while (queue.Top() != null)
{
AddToList((SpansCell) queue.Pop());
}
}
private void ListToQueue()
{
queue.Clear(); // rebuild queue
for (SpansCell cell = first; cell != null; cell = cell.next)
{
queue.Put(cell); // add to queue from list
}
}
private bool AtMatch()
{
return (Min().Doc() == max.Doc()) && ((max.End() - Min().Start() - totalLength) <= slop);
}
}
}
| |
//
// This code was created by Jeff Molofee '99
//
// If you've found this code useful, please let me know.
//
// Visit me at www.demonews.com/hosted/nehe
//
//=====================================================================
// Converted to C# and MonoMac by Kenneth J. Pouncey
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;
namespace NeHeLesson5
{
public partial class MyOpenGLView : MonoMac.AppKit.NSView
{
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
MainWindowController controller;
CVDisplayLink displayLink;
NSObject notificationProxy;
[Export("initWithFrame:")]
public MyOpenGLView (RectangleF frame) : this(frame, null)
{
}
public MyOpenGLView (RectangleF frame, NSOpenGLContext context) : base(frame)
{
var attribs = new object[] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = true;
// Initialize our newly created view.
InitGL ();
SetupDisplayLink ();
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape);
}
public override void DrawRect (RectangleF dirtyRect)
{
// Ignore if the display link is still running
if (!displayLink.IsRunning && controller != null)
DrawView ();
}
public override bool AcceptsFirstResponder ()
{
// We want this view to be able to receive key events
return true;
}
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public override void KeyDown (NSEvent theEvent)
{
controller.KeyDown (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
controller.MouseDown (theEvent);
}
// All Setup For OpenGL Goes Here
public bool InitGL ()
{
// Enables Smooth Shading
GL.ShadeModel (ShadingModel.Smooth);
// Set background color to black
GL.ClearColor (Color.Black);
// Setup Depth Testing
// Depth Buffer setup
GL.ClearDepth (1.0);
// Enables Depth testing
GL.Enable (EnableCap.DepthTest);
// The type of depth testing to do
GL.DepthFunc (DepthFunction.Lequal);
// Really Nice Perspective Calculations
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
return true;
}
private void DrawView ()
{
var previous = NSApplication.CheckForIllegalCrossThreadCalls;
NSApplication.CheckForIllegalCrossThreadCalls = false;
// This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
// Delegate to the scene object for rendering
controller.Scene.DrawGLScene ();
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
NSApplication.CheckForIllegalCrossThreadCalls = previous;
}
private void SetupDisplayLink ()
{
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
CVReturn result = GetFrameForTime (inOutputTime);
return result;
}
private CVReturn GetFrameForTime (CVTimeStamp outputTime)
{
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
DrawView ();
}
return CVReturn.Success;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
public MainWindowController MainController {
set { controller = value; }
}
public void UpdateView ()
{
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
controller.Scene.ResizeGLScene (Bounds);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
public void StartAnimation ()
{
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
}
public void StopAnimation ()
{
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
}
// Clean up the notifications
public void DeAllocate ()
{
displayLink.Stop ();
displayLink.SetOutputCallback (null);
NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy);
}
[Export("toggleFullScreen:")]
public void toggleFullScreen (NSObject sender)
{
controller.toggleFullScreen (sender);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public partial class GetEnvironmentVariable
{
[Fact]
public void InvalidArguments_ThrowsExceptions()
{
AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null));
AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test"));
AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test"));
AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test", EnvironmentVariableTarget.Machine));
AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test", EnvironmentVariableTarget.User));
AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null, EnvironmentVariableTarget.Process));
AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariable("test", (EnvironmentVariableTarget)42));
AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.SetEnvironmentVariable("test", "test", (EnvironmentVariableTarget)(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariables((EnvironmentVariableTarget)(3)));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && System.Tests.SetEnvironmentVariable.IsSupportedTarget(EnvironmentVariableTarget.User))
{
AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable(new string('s', 256), "value", EnvironmentVariableTarget.User));
}
}
[Fact]
public void EmptyVariableReturnsNull()
{
Assert.Null(Environment.GetEnvironmentVariable(string.Empty));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // GetEnvironmentVariable by design doesn't respect changes via setenv
public void RandomLongVariableNameCanRoundTrip()
{
// NOTE: The limit of 32766 characters enforced by desktop
// SetEnvironmentVariable is antiquated. I was
// able to create ~1GB names and values on my Windows 8.1 box. On
// desktop, GetEnvironmentVariable throws OOM during its attempt to
// demand huge EnvironmentPermission well before that. Also, the old
// test for long name case wasn't very good: it just checked that an
// arbitrary long name > 32766 characters returned null (not found), but
// that had nothing to do with the limit, the variable was simply not
// found!
string variable = "LongVariable_" + new string('@', 33000);
const string value = "TestValue";
try
{
SetEnvironmentVariableWithPInvoke(variable, value);
Assert.Equal(value, Environment.GetEnvironmentVariable(variable));
}
finally
{
SetEnvironmentVariableWithPInvoke(variable, null);
}
}
[Fact]
public void RandomVariableThatDoesNotExistReturnsNull()
{
string variable = "TestVariable_SurelyThisDoesNotExist";
Assert.Null(Environment.GetEnvironmentVariable(variable));
}
[Fact]
public void VariableNamesAreCaseInsensitiveAsAppropriate()
{
string value = "TestValue";
try
{
Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", value);
Assert.Equal(value, Environment.GetEnvironmentVariable("ThisIsATestEnvironmentVariable"));
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
value = null;
}
Assert.Equal(value, Environment.GetEnvironmentVariable("thisisatestenvironmentvariable"));
Assert.Equal(value, Environment.GetEnvironmentVariable("THISISATESTENVIRONMENTVARIABLE"));
Assert.Equal(value, Environment.GetEnvironmentVariable("ThISISATeSTENVIRoNMEnTVaRIABLE"));
}
finally
{
Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", null);
}
}
[Fact]
public void CanGetAllVariablesIndividually()
{
Random r = new Random();
string envVar1 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString();
string envVar2 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString();
try
{
Environment.SetEnvironmentVariable(envVar1, envVar1);
Environment.SetEnvironmentVariable(envVar2, envVar2);
IDictionary envBlock = Environment.GetEnvironmentVariables();
// Make sure the environment variables we set are part of the dictionary returned.
Assert.True(envBlock.Contains(envVar1));
Assert.True(envBlock.Contains(envVar1));
// Make sure the values match the expected ones.
Assert.Equal(envVar1, envBlock[envVar1]);
Assert.Equal(envVar2, envBlock[envVar2]);
// Make sure we can read the individual variables as well
Assert.Equal(envVar1, Environment.GetEnvironmentVariable(envVar1));
Assert.Equal(envVar2, Environment.GetEnvironmentVariable(envVar2));
}
finally
{
// Clear the variables we just set
Environment.SetEnvironmentVariable(envVar1, null);
Environment.SetEnvironmentVariable(envVar2, null);
}
}
[Fact]
public void EnumerateYieldsDictionaryEntryFromIEnumerable()
{
// GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable
IDictionary vars = Environment.GetEnvironmentVariables();
IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator();
if (enumerator.MoveNext())
{
Assert.IsType<DictionaryEntry>(enumerator.Current);
}
else
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
[Fact]
public void GetEnumerator_IDictionaryEnumerator_YieldsDictionaryEntries()
{
// GetEnvironmentVariables has always yielded DictionaryEntry from IDictionaryEnumerator
IDictionary vars = Environment.GetEnvironmentVariables();
IDictionaryEnumerator enumerator = vars.GetEnumerator();
if (enumerator.MoveNext())
{
Assert.IsType<DictionaryEntry>(enumerator.Current);
}
else
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
[Theory]
[InlineData(null)]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
[ActiveIssue("https://github.com/dotnet/corefx/issues/23003", TargetFrameworkMonikers.NetFramework)]
public void GetEnumerator_LinqOverDictionaryEntries_Success(EnvironmentVariableTarget? target)
{
IDictionary envVars = target != null ?
Environment.GetEnvironmentVariables(target.Value) :
Environment.GetEnvironmentVariables();
Assert.IsType<Hashtable>(envVars);
foreach (KeyValuePair<string, string> envVar in envVars.Cast<DictionaryEntry>().Select(de => new KeyValuePair<string, string>((string)de.Key, (string)de.Value)))
{
Assert.NotNull(envVar.Key);
}
}
public void EnvironmentVariablesAreHashtable()
{
// On NetFX, the type returned was always Hashtable
Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables());
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target)
{
// On NetFX, the type returned was always Hashtable
Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target));
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target)
{
// GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable
IDictionary vars = Environment.GetEnvironmentVariables(target);
IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator();
if (enumerator.MoveNext())
{
Assert.IsType<DictionaryEntry>(enumerator.Current);
}
else
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
{
bool lookForSetValue = (target == EnvironmentVariableTarget.Process) ||
// On the Project N corelib, it doesn't attempt to set machine/user environment variables;
// it just returns silently. So don't try.
(PlatformDetection.IsWindowsAndElevated && !PlatformDetection.IsNetNative);
string key = $"EnumerateEnvironmentVariables ({target})";
string value = Path.GetRandomFileName();
try
{
if (lookForSetValue)
{
Environment.SetEnvironmentVariable(key, value, target);
Assert.Equal(value, Environment.GetEnvironmentVariable(key, target));
}
IDictionary results = Environment.GetEnvironmentVariables(target);
// Ensure we can walk through the results
IDictionaryEnumerator enumerator = results.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotNull(enumerator.Entry);
}
if (lookForSetValue)
{
// Ensure that we got our flagged value out
Assert.Equal(value, results[key]);
}
}
finally
{
if (lookForSetValue)
{
Environment.SetEnvironmentVariable(key, null, target);
Assert.Null(Environment.GetEnvironmentVariable(key, target));
}
}
}
private static void SetEnvironmentVariableWithPInvoke(string name, string value)
{
bool success =
#if !Unix
SetEnvironmentVariable(name, value);
#else
(value != null ? setenv(name, value, 1) : unsetenv(name)) == 0;
#endif
Assert.True(success);
}
[DllImport("kernel32.dll", EntryPoint = "SetEnvironmentVariableW" , CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetEnvironmentVariable(string lpName, string lpValue);
#if Unix
[DllImport("libc")]
private static extern int setenv(string name, string value, int overwrite);
[DllImport("libc")]
private static extern int unsetenv(string name);
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Capture synchronization semantics for asynchronous callbacks
**
**
===========================================================*/
namespace System.Threading
{
using Microsoft.Win32.SafeHandles;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime;
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
using System.Reflection;
using System.Security;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
[Flags]
enum SynchronizationContextProperties
{
None = 0,
RequireWaitNotification = 0x1
};
#endif
#if FEATURE_COMINTEROP && FEATURE_APPX
//
// This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx.
// I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed.
//
[FriendAccessAllowed]
[SecurityCritical]
internal class WinRTSynchronizationContextFactoryBase
{
[SecurityCritical]
public virtual SynchronizationContext Create(object coreDispatcher) {return null;}
}
#endif //FEATURE_COMINTEROP
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)]
#endif
public class SynchronizationContext
{
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
SynchronizationContextProperties _props = SynchronizationContextProperties.None;
#endif
public SynchronizationContext()
{
}
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
// helper delegate to statically bind to Wait method
private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
static Type s_cachedPreparedType1;
static Type s_cachedPreparedType2;
static Type s_cachedPreparedType3;
static Type s_cachedPreparedType4;
static Type s_cachedPreparedType5;
// protected so that only the derived sync context class can enable these flags
[System.Security.SecuritySafeCritical] // auto-generated
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")]
protected void SetWaitNotificationRequired()
{
//
// Prepare the method so that it can be called in a reliable fashion when a wait is needed.
// This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing
// preparing the method here does is to ensure there is no failure point before the method execution begins.
//
// Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain.
// So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than
// a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets
// our cache be much faster than a more general cache might be. This is important, because this
// is a *very* hot code path for many WPF and WinForms apps.
//
Type type = this.GetType();
if (s_cachedPreparedType1 != type &&
s_cachedPreparedType2 != type &&
s_cachedPreparedType3 != type &&
s_cachedPreparedType4 != type &&
s_cachedPreparedType5 != type)
{
RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));
if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type;
else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type;
else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type;
else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type;
else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type;
}
_props |= SynchronizationContextProperties.RequireWaitNotification;
}
public bool IsWaitNotificationRequired()
{
return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0);
}
#endif
public virtual void Send(SendOrPostCallback d, Object state)
{
d(state);
}
public virtual void Post(SendOrPostCallback d, Object state)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(d), state);
}
/// <summary>
/// Optional override for subclasses, for responding to notification that operation is starting.
/// </summary>
public virtual void OperationStarted()
{
}
/// <summary>
/// Optional override for subclasses, for responding to notification that operation has completed.
/// </summary>
public virtual void OperationCompleted()
{
}
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
// Method called when the CLR does a wait operation
[System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[PrePrepareMethod]
public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
if (waitHandles == null)
{
throw new ArgumentNullException("waitHandles");
}
Contract.EndContractBlock();
return WaitHelper(waitHandles, waitAll, millisecondsTimeout);
}
// Static helper to which the above method can delegate to in order to get the default
// COM behavior.
[System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[PrePrepareMethod]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
#endif
#if FEATURE_CORECLR
[ThreadStatic]
private static SynchronizationContext s_threadStaticContext;
//
// Maintain legacy NetCF Behavior where setting the value for one thread impacts all threads.
//
private static SynchronizationContext s_appDomainStaticContext;
[System.Security.SecurityCritical]
public static void SetSynchronizationContext(SynchronizationContext syncContext)
{
s_threadStaticContext = syncContext;
}
[System.Security.SecurityCritical]
public static void SetThreadStaticContext(SynchronizationContext syncContext)
{
//
// If this is a pre-Mango Windows Phone app, we need to set the SC for *all* threads to match the old NetCF behavior.
//
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango)
s_appDomainStaticContext = syncContext;
else
s_threadStaticContext = syncContext;
}
public static SynchronizationContext Current
{
get
{
SynchronizationContext context = null;
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango)
context = s_appDomainStaticContext;
else
context = s_threadStaticContext;
#if FEATURE_APPX
if (context == null && Environment.IsWinRTSupported)
context = GetWinRTContext();
#endif
return context;
}
}
// Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run)
internal static SynchronizationContext CurrentNoFlow
{
[FriendAccessAllowed]
get
{
return Current; // SC never flows
}
}
#else //FEATURE_CORECLR
// set SynchronizationContext on the current thread
[System.Security.SecurityCritical] // auto-generated_required
public static void SetSynchronizationContext(SynchronizationContext syncContext)
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
ec.SynchronizationContext = syncContext;
ec.SynchronizationContextNoFlow = syncContext;
}
// Get the current SynchronizationContext on the current thread
public static SynchronizationContext Current
{
get
{
return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext();
}
}
// Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run)
internal static SynchronizationContext CurrentNoFlow
{
[FriendAccessAllowed]
get
{
return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext();
}
}
private static SynchronizationContext GetThreadLocalContext()
{
SynchronizationContext context = null;
#if FEATURE_APPX
if (context == null && Environment.IsWinRTSupported)
context = GetWinRTContext();
#endif
return context;
}
#endif //FEATURE_CORECLR
#if FEATURE_APPX
[SecuritySafeCritical]
private static SynchronizationContext GetWinRTContext()
{
Contract.Assert(Environment.IsWinRTSupported);
// Temporary workaround to avoid loading a bunch of DLLs in every managed process.
// This disables this feature for non-AppX processes that happen to use CoreWindow/CoreDispatcher,
// which is not what we want.
if (!AppDomain.IsAppXModel())
return null;
//
// We call into the VM to get the dispatcher. This is because:
//
// a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here.
// b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly
// into processes that don't need it (for performance reasons).
//
// So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to
// System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext.
//
object dispatcher = GetWinRTDispatcherForCurrentThread();
if (dispatcher != null)
return GetWinRTSynchronizationContextFactory().Create(dispatcher);
return null;
}
[SecurityCritical]
static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
[SecurityCritical]
private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory()
{
//
// Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection.
// It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because
// we can do very little with WinRT stuff in mscorlib.
//
WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory;
if (factory == null)
{
Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true);
s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true);
}
return factory;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object GetWinRTDispatcherForCurrentThread();
#endif //FEATURE_APPX
// helper to Clone this SynchronizationContext,
public virtual SynchronizationContext CreateCopy()
{
// the CLR dummy has an empty clone function - no member data
return new SynchronizationContext();
}
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
[System.Security.SecurityCritical] // auto-generated
private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout);
}
#endif
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductSupplierItem (editable child object).<br/>
/// This is a generated <see cref="ProductSupplierItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductSupplierColl"/> collection.
/// </remarks>
[Serializable]
public partial class ProductSupplierItem : BusinessBase<ProductSupplierItem>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductSupplierId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductSupplierIdProperty = RegisterProperty<int>(p => p.ProductSupplierId, "Product Supplier Id");
/// <summary>
/// Gets the Product Supplier Id.
/// </summary>
/// <value>The Product Supplier Id.</value>
public int ProductSupplierId
{
get { return GetProperty(ProductSupplierIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SupplierId"/> property.
/// </summary>
public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id");
/// <summary>
/// Gets or sets the Supplier Id.
/// </summary>
/// <value>The Supplier Id.</value>
public int SupplierId
{
get { return GetProperty(SupplierIdProperty); }
set { SetProperty(SupplierIdProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductSupplierItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductSupplierItem()
{
// 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="ProductSupplierItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(ProductSupplierIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="ProductSupplierItem"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductSupplierIdProperty, dr.GetInt32("ProductSupplierId"));
LoadProperty(SupplierIdProperty, dr.GetInt32("SupplierId"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="ProductSupplierItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(ProductEdit parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.AddProductSupplierItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductId", parent.ProductId).DbType = DbType.Guid;
cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@SupplierId", ReadProperty(SupplierIdProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(ProductSupplierIdProperty, (int) cmd.Parameters["@ProductSupplierId"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductSupplierItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.UpdateProductSupplierItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SupplierId", ReadProperty(SupplierIdProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="ProductSupplierItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.DeleteProductSupplierItem", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductSupplierId", ReadProperty(ProductSupplierIdProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
namespace fyiReporting.RdlReader
{
/// <summary>
/// Summary description for DialogAbout.
/// </summary>
public class DialogAbout : System.Windows.Forms.Form
{
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.LinkLabel linkLabel2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.TextBox tbLicense;
private System.Windows.Forms.Label lVersion;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DialogAbout()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
tbLicense.Text = @"RDL Reader displays reports defined using the Report Definition Language Specification.
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the ""License"");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an ""AS IS"" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.";
lVersion.Text = "Version " + Assembly.GetExecutingAssembly().GetName().Version.ToString();
return;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DialogAbout));
this.bOK = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.lVersion = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.linkLabel2 = new System.Windows.Forms.LinkLabel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.tbLicense = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// bOK
//
this.bOK.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bOK.Location = new System.Drawing.Point(200, 272);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 0;
this.bOK.Text = "OK";
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(240, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(176, 24);
this.label1.TabIndex = 1;
this.label1.Text = "fyiReporting Reader";
//
// lVersion
//
this.lVersion.Location = new System.Drawing.Point(288, 48);
this.lVersion.Name = "lVersion";
this.lVersion.Size = new System.Drawing.Size(104, 24);
this.lVersion.TabIndex = 2;
this.lVersion.Text = "Version 1.9.6";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 23);
this.label3.TabIndex = 3;
this.label3.Text = "Website:";
//
// label4
//
this.label4.Location = new System.Drawing.Point(240, 88);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 23);
this.label4.TabIndex = 4;
this.label4.Text = "E-mail:";
//
// linkLabel1
//
this.linkLabel1.Location = new System.Drawing.Point(72, 88);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(144, 16);
this.linkLabel1.TabIndex = 6;
this.linkLabel1.TabStop = true;
this.linkLabel1.Tag = "http://www.fyireporting.com";
this.linkLabel1.Text = "http://www.fyireporting.com";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnk_LinkClicked);
//
// linkLabel2
//
this.linkLabel2.Location = new System.Drawing.Point(280, 88);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new System.Drawing.Size(152, 16);
this.linkLabel2.TabIndex = 7;
this.linkLabel2.TabStop = true;
this.linkLabel2.Tag = "mailto:comments@fyireporting.com";
this.linkLabel2.Text = "comments@fyireporting.com";
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnk_LinkClicked);
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(8, 8);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(212, 72);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 8;
this.pictureBox1.TabStop = false;
//
// tbLicense
//
this.tbLicense.Location = new System.Drawing.Point(16, 120);
this.tbLicense.Multiline = true;
this.tbLicense.Name = "tbLicense";
this.tbLicense.ReadOnly = true;
this.tbLicense.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbLicense.Size = new System.Drawing.Size(448, 136);
this.tbLicense.TabIndex = 9;
this.tbLicense.Text = "";
//
// DialogAbout
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bOK;
this.ClientSize = new System.Drawing.Size(482, 304);
this.Controls.Add(this.tbLicense);
this.Controls.Add(this.linkLabel2);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.lVersion);
this.Controls.Add(this.label1);
this.Controls.Add(this.bOK);
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogAbout";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About";
this.ResumeLayout(false);
}
#endregion
private void lnk_LinkClicked(object sender, LinkLabelLinkClickedEventArgs ea)
{
LinkLabel lnk = (LinkLabel) sender;
lnk.Links[lnk.Links.IndexOf(ea.Link)].Visited = true;
System.Diagnostics.Process.Start(lnk.Tag.ToString());
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.F1Help
{
public class F1HelpTests
{
private void Test(string markup, string expectedText)
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(markup))
{
var caret = workspace.Documents.First().CursorPosition;
var service = new CSharpHelpContextService();
var actualText = service.GetHelpTermAsync(workspace.CurrentSolution.Projects.First().Documents.First(), workspace.Documents.First().SelectedSpans.First(), CancellationToken.None).WaitAndGetResult(CancellationToken.None);
Assert.Equal(expectedText, actualText);
}
}
private void Test_Keyword(string markup, string expectedText)
{
Test(markup, expectedText + "_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestVoid()
{
Test_Keyword(@"
class C
{
vo[||]id foo() { }
}", "void");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestReturn()
{
Test_Keyword(@"
class C
{
void foo()
{
ret[||]urn;
}
}", "return");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestPartialType()
{
Test_Keyword(@"
part[||]ial class C
{
partial void foo();
}", "partialtype");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestPartialMethod()
{
Test_Keyword(@"
partial class C
{
par[||]tial void foo();
}", "partialmethod");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestWhereClause()
{
Test_Keyword(@"
using System.Linq;
class Program<T> where T : class {
void foo(string[] args)
{
var x = from a in args whe[||]re a.Length > 0 select a;
}
}", "whereclause");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestWhereConstraint()
{
Test_Keyword(@"
using System.Linq;
class Program<T> wh[||]ere T : class {
void foo(string[] args)
{
var x = from a in args where a.Length > 0 select a;
}
}", "whereconstraint");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestPreprocessor()
{
Test(@"
#regi[||]on
#endregion", "#region");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestConstructor()
{
Test(@"
namespace N
{
class C
{
void foo()
{
var x = new [|C|]();
}
}
}", "N.C.#ctor");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestGenericClass()
{
Test(@"
namespace N
{
class C<T>
{
void foo()
{
[|C|]<int> c;
}
}
}", "N.C`1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestGenericMethod()
{
Test(@"
namespace N
{
class C<T>
{
void foo<T, U, V>(T t, U u, V v)
{
C<int> c;
c.f[|oo|](1, 1, 1);
}
}
}", "N.C`1.foo``3");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestOperator()
{
Test(@"
namespace N
{
class C
{
void foo()
{
var two = 1 [|+|] 1;
}
}", "+_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestVar()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var[||] x = 3;
}
}", "var_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestEquals()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x =[||] 3;
}
}", "=_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestFromIn()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var x = from n i[||]n { 1} select n
}
}", "from_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestProperty()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
new UriBuilder().Fragm[||]ent;
}
}", "System.UriBuilder.Fragment");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestForeachIn()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (var x in[||] { 1} )
{
}
}
}", "in_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestRegionDescription()
{
Test(@"
class Program
{
static void Main(string[] args)
{
#region Begin MyR[||]egion for testing
#endregion End
}
}", "#region");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestGenericAngle()
{
Test(@"class Program
{
static void generic<T>(T t)
{
generic[||]<int>(0);
}
}", "Program.generic``1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestLocalReferenceIsType()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int x;
x[||];
}
}", "System.Int32");
}
[WorkItem(864266)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestConstantField()
{
Test(@"class Program
{
static void Main(string[] args)
{
var i = int.Ma[||]xValue;
}
}", "System.Int32.MaxValue");
}
[WorkItem(862420)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestParameter()
{
Test(@"class Class2
{
void M1(int par[||]ameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}
", "System.Int32");
}
[WorkItem(862420)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestArgumentType()
{
Test(@"class Class2
{
void M1(int pa[||]rameter) // 1
{
}
void M2()
{
int argument = 1;
M1(parameter: argument); // 2
}
}
", "System.Int32");
}
[WorkItem(862396)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestNoToken()
{
Test(@"class Program
{
static void Main(string[] args)
{
[||]
}
}", "");
}
[WorkItem(862328)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestLiteral()
{
Test(@"class Program
{
static void Main(string[] args)
{
Main(new string[] { ""fo[||]o"" });
}
}", "System.String");
}
[WorkItem(862478)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestColonColon()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
global:[||]:System.Console.Write("");
}
}", "::_CSharpKeyword");
}
[WorkItem(864658)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestNullable()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int?[||] a = int.MaxValue;
a.Value.GetHashCode();
}
}", "System.Nullable`1");
}
[WorkItem(863517)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestAfterLastToken()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
foreach (char var in ""!!!"")$$[||]
{
}
}
}", "");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestConditional()
{
Test(@"class Program
{
static void Main(string[] args)
{
var x = true [|?|] true : false;
}
}", "?_CSharpKeyword");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestLocalVar()
{
Test(@"class C
{
void M()
{
var a = 0;
int v[||]ar = 1;
}
}", "System.Int32");
}
[WorkItem(867574)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestFatArrow()
{
Test(@"class C
{
void M()
{
var a = new System.Action(() =[||]> { });
}
}", "=>_CSharpKeyword");
}
[WorkItem(867572)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestSubscription()
{
Test(@"class CCC
{
event System.Action e;
void M()
{
e +[||]= () => { };
}
}", "CCC.e.add");
}
[WorkItem(867554)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestComment()
{
Test(@"// some comm[||]ents here", "comments");
}
[WorkItem(867529)]
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestDynamic()
{
Test(@"class C
{
void M()
{
dyna[||]mic d = 0;
}
}", "dynamic_CSharpKeyword");
}
[Fact, Trait(Traits.Feature, Traits.Features.F1Help)]
public void TestRangeVariable()
{
Test(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var zzz = from y in args select [||]y;
}
}", "System.String");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
namespace AsterNET.FastAGI
{
/// <summary>
/// Default implementation of the AGIRequest interface.
/// </summary>
public class AGIRequest
{
#region Variables
#if LOGGER
private Logger logger = Logger.Instance();
#endif
private string rawCallerId;
private readonly Dictionary<string, string> request;
/// <summary> A map assigning the values of a parameter (an array of Strings) to the name of the parameter.</summary>
private Dictionary<string, List<string>> parameterMap;
private string parameters;
private string script;
private bool callerIdCreated;
#endregion
#region Constructor - AGIRequest(ICollection environment)
/// <summary>
/// Creates a new AGIRequest.
/// </summary>
/// <param name="environment">the first lines as received from Asterisk containing the environment.</param>
public AGIRequest(List<string> environment)
{
if (environment == null)
throw new ArgumentException("Environment must not be null.");
request = buildMap(environment);
}
#endregion
#region Request
public IDictionary Request
{
get { return request; }
}
#endregion
#region RequestURL
/// <summary>
/// Returns the full URL of the request in the form agi://host[:port][/script].
/// </summary>
public string RequestURL
{
get { return request["request"]; }
}
#endregion
#region Channel
/// <summary>
/// Returns the name of the channel.
/// </summary>
/// <returns>the name of the channel.</returns>
public string Channel
{
get { return request["channel"]; }
}
#endregion
#region UniqueId
/// <summary>
/// Returns the unqiue id of the channel.
/// </summary>
/// <returns>the unqiue id of the channel.</returns>
public string UniqueId
{
get { return request["uniqueid"]; }
}
#endregion
#region Type
/// <summary>
/// Returns the type of the channel, for example "SIP".
/// </summary>
/// <returns>the type of the channel, for example "SIP".</returns>
public string Type
{
get { return request["type"]; }
}
#endregion
#region Language
/// <summary>
/// Returns the language, for example "en".
/// </summary>
public string Language
{
get { return request["language"]; }
}
#endregion
#region CallerId
public string CallerId
{
get
{
string callerIdName = request["calleridname"];
string callerId = request["callerid"];
if (callerIdName != null)
{
if (callerId == null || callerId.ToLower(Helper.CultureInfo) == "unknown")
return null;
return callerId;
}
return callerId10();
}
}
#endregion
#region CallerIdName
public string CallerIdName
{
get
{
string callerIdName = request["calleridname"];
if (callerIdName != null)
{
// Asterisk 1.2
if (callerIdName.ToLower(Helper.CultureInfo) == "unknown")
return null;
return callerIdName;
}
return callerIdName10();
}
}
#endregion
#region Asterisk 1.0 CallerID and CallerIdName
private string callerId10()
{
int lbPosition;
int rbPosition;
if (!callerIdCreated)
{
rawCallerId = request["callerid"];
callerIdCreated = true;
}
if (rawCallerId == null)
{
return null;
}
lbPosition = rawCallerId.IndexOf('<');
rbPosition = rawCallerId.IndexOf('>');
if (lbPosition < 0 || rbPosition < 0)
{
return rawCallerId;
}
return rawCallerId.Substring(lbPosition + 1, (rbPosition) - (lbPosition + 1));
}
private string callerIdName10()
{
int lbPosition;
string callerIdName;
if (!callerIdCreated)
{
rawCallerId = request["callerid"];
callerIdCreated = true;
}
if (rawCallerId == null)
return null;
lbPosition = rawCallerId.IndexOf('<');
if (lbPosition < 0)
return null;
callerIdName = rawCallerId.Substring(0, (lbPosition) - (0)).Trim();
if (callerIdName.StartsWith("\"") && callerIdName.EndsWith("\""))
callerIdName = callerIdName.Substring(1, (callerIdName.Length - 1) - (1));
if (callerIdName.Length == 0)
return null;
return callerIdName;
}
#endregion
#region Dnid
public string Dnid
{
get
{
string dnid = request["dnid"];
if (dnid == null || dnid.ToLower(Helper.CultureInfo) == "unknown")
return null;
return dnid;
}
}
#endregion
#region Rdnis
public string Rdnis
{
get
{
string rdnis = request["rdnis"];
if (rdnis == null || rdnis.ToLower(Helper.CultureInfo) == "unknown")
return null;
return rdnis;
}
}
#endregion
#region Context
/// <summary>
/// Returns the context in the dial plan from which the AGI script was called.
/// </summary>
public string Context
{
get { return request["context"]; }
}
#endregion
#region Extension
/// <summary>
/// Returns the extension in the dial plan from which the AGI script was called.
/// </summary>
public string Extension
{
get { return request["extension"]; }
}
#endregion
#region Priority
/// <summary>
/// Returns the priority in the dial plan from which the AGI script was called.
/// </summary>
public string Priority
{
get
{
if (request["priority"] != null)
{
return request["priority"];
}
return "";
}
}
#endregion
#region Enhanced
/// <summary>
/// Returns wheather this agi is passed audio (EAGI - Enhanced AGI).<br />
/// Enhanced AGI is currently not supported on FastAGI.<br />
/// true if this agi is passed audio, false otherwise.
/// </summary>
public bool Enhanced
{
get
{
if (request["enhanced"] != null && request["enhanced"] == "1.0")
return true;
return false;
}
}
#endregion
#region AccountCode
/// <summary>
/// Returns the account code set for the call.
/// </summary>
public string AccountCode
{
get { return request["accountCode"]; }
}
#endregion
#region LocalAddress
public IPAddress LocalAddress { get; set; }
#endregion
#region LocalPort
public int LocalPort { get; set; }
#endregion
#region RemoteAddress
public IPAddress RemoteAddress { get; set; }
#endregion
#region RemotePort
public int RemotePort { get; set; }
#endregion
#region Script()
/// <summary>
/// Returns the name of the script to execute.
/// </summary>
public string Script
{
get
{
if (script != null)
return script;
script = request["network_script"];
if (script != null)
{
Match scriptMatcher = Common.AGI_SCRIPT_PATTERN.Match(script);
if (scriptMatcher.Success)
{
script = scriptMatcher.Groups[1].Value;
parameters = scriptMatcher.Groups[2].Value;
}
}
return script;
}
}
#endregion
#region CallingAni2
public int CallingAni2
{
get
{
if (request["callingani2"] == null)
return -1;
try
{
return Int32.Parse(request["callingani2"]);
}
catch
{
}
return -1;
}
}
#endregion
#region CallingPres
public int CallingPres
{
get
{
if (request["callingpres"] == null)
return -1;
try
{
return Int32.Parse(request["callingpres"]);
}
catch
{
}
return -1;
}
}
#endregion
#region CallingTns
public int CallingTns
{
get
{
if (request["callingtns"] == null)
return -1;
try
{
return Int32.Parse(request["callingtns"]);
}
catch
{
}
return -1;
}
}
#endregion
#region CallingTon
public int CallingTon
{
get
{
if (request["callington"] == null)
return -1;
try
{
return Int32.Parse(request["callington"]);
}
catch
{
}
return -1;
}
}
#endregion
#region Parameter(string name)
public string Parameter(string name)
{
List<string> values;
values = ParameterValues(name);
if (values == null || values.Count == 0)
return null;
return values[0];
}
#endregion
#region ParameterValues(string name)
public List<string> ParameterValues(string name)
{
if (ParameterMap().Count == 0)
return null;
return parameterMap[name];
}
#endregion
#region ParameterMap()
public Dictionary<string, List<string>> ParameterMap()
{
if (parameterMap == null)
parameterMap = parseParameters(parameters);
return parameterMap;
}
#endregion
#region ToString()
public override string ToString()
{
return Helper.ToString(this);
}
#endregion
#region buildMap(ICollection lines)
/// <summary>
/// Builds a map containing variable names as key (with the "agi_" prefix stripped) and the corresponding values.<br />
/// Syntactically invalid and empty variables are skipped.
/// </summary>
/// <param name="lines">the environment to transform.</param>
/// <returns> a map with the variables set corresponding to the given environment.</returns>
private Dictionary<string, string> buildMap(List<string> lines)
{
int colonPosition;
string key;
string value;
var map = new Dictionary<string, string>(lines.Count);
foreach (var line in lines)
{
colonPosition = line.IndexOf(':');
if (colonPosition < 0 || !line.StartsWith("agi_") || line.Length < colonPosition + 2)
continue;
key = line.Substring(4, colonPosition - 4).ToLower(Helper.CultureInfo);
value = line.Substring(colonPosition + 2);
if (value.Length != 0)
map.Add(key, value);
}
return map;
}
#endregion
#region parseParameters(string s)
/// <summary>
/// Parses the given parameter string and caches the result.
/// </summary>
/// <param name="s">the parameter string to parse</param>
/// <returns> a Map made up of parameter names their values</returns>
private Dictionary<string, List<string>> parseParameters(string parameters)
{
var result = new Dictionary<string, List<string>>();
string name;
string val;
if (string.IsNullOrEmpty(parameters))
return result;
string[] pars = parameters.Split('&');
if (pars.Length == 0)
return result;
foreach (var parameter in pars)
{
val = string.Empty;
int i = parameter.IndexOf('=');
if (i > 0)
{
name = HttpUtility.UrlDecode(parameter.Substring(0, i));
if (parameter.Length > i + 1)
val = HttpUtility.UrlDecode(parameter.Substring(i + 1));
}
else if (i < 0)
name = HttpUtility.UrlDecode(parameter);
else
continue;
if (!result.ContainsKey(name))
result.Add(name, new List<string>());
result[name].Add(val);
}
return result;
}
#endregion
}
}
| |
//***************************************************
//* This file was generated by JSharp
//***************************************************
namespace java.lang
{
public partial class Character : Object, global::java.io.Serializable, Comparable<Character>
{
public partial class Subset : global::java.lang.Object
{
public bool equals(global::System.Object prm1){return default(bool);}
public int hashCode(){return default(int);}
public Subset(global::java.lang.String prm1){}
public global::java.lang.String toString(){return default(global::java.lang.String);}
}
public partial class UnicodeBlock : global::java.lang.Character.Subset
{
public static global::java.lang.Character.UnicodeBlock AEGEAN_NUMBERS;
public static global::java.lang.Character.UnicodeBlock ALCHEMICAL_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock ALPHABETIC_PRESENTATION_FORMS;
public static global::java.lang.Character.UnicodeBlock ANCIENT_GREEK_MUSICAL_NOTATION;
public static global::java.lang.Character.UnicodeBlock ANCIENT_GREEK_NUMBERS;
public static global::java.lang.Character.UnicodeBlock ANCIENT_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock ARABIC;
public static global::java.lang.Character.UnicodeBlock ARABIC_PRESENTATION_FORMS_A;
public static global::java.lang.Character.UnicodeBlock ARABIC_PRESENTATION_FORMS_B;
public static global::java.lang.Character.UnicodeBlock ARABIC_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock ARMENIAN;
public static global::java.lang.Character.UnicodeBlock ARROWS;
public static global::java.lang.Character.UnicodeBlock AVESTAN;
public static global::java.lang.Character.UnicodeBlock BALINESE;
public static global::java.lang.Character.UnicodeBlock BAMUM;
public static global::java.lang.Character.UnicodeBlock BAMUM_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock BASIC_LATIN;
public static global::java.lang.Character.UnicodeBlock BATAK;
public static global::java.lang.Character.UnicodeBlock BENGALI;
public static global::java.lang.Character.UnicodeBlock BLOCK_ELEMENTS;
public static global::java.lang.Character.UnicodeBlock BOPOMOFO;
public static global::java.lang.Character.UnicodeBlock BOPOMOFO_EXTENDED;
public static global::java.lang.Character.UnicodeBlock BOX_DRAWING;
public static global::java.lang.Character.UnicodeBlock BRAHMI;
public static global::java.lang.Character.UnicodeBlock BRAILLE_PATTERNS;
public static global::java.lang.Character.UnicodeBlock BUGINESE;
public static global::java.lang.Character.UnicodeBlock BUHID;
public static global::java.lang.Character.UnicodeBlock BYZANTINE_MUSICAL_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock CARIAN;
public static global::java.lang.Character.UnicodeBlock CHAM;
public static global::java.lang.Character.UnicodeBlock CHEROKEE;
public static global::java.lang.Character.UnicodeBlock CJK_COMPATIBILITY;
public static global::java.lang.Character.UnicodeBlock CJK_COMPATIBILITY_FORMS;
public static global::java.lang.Character.UnicodeBlock CJK_COMPATIBILITY_IDEOGRAPHS;
public static global::java.lang.Character.UnicodeBlock CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock CJK_RADICALS_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock CJK_STROKES;
public static global::java.lang.Character.UnicodeBlock CJK_SYMBOLS_AND_PUNCTUATION;
public static global::java.lang.Character.UnicodeBlock CJK_UNIFIED_IDEOGRAPHS;
public static global::java.lang.Character.UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;
public static global::java.lang.Character.UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B;
public static global::java.lang.Character.UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C;
public static global::java.lang.Character.UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D;
public static global::java.lang.Character.UnicodeBlock COMBINING_DIACRITICAL_MARKS;
public static global::java.lang.Character.UnicodeBlock COMBINING_DIACRITICAL_MARKS_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock COMBINING_HALF_MARKS;
public static global::java.lang.Character.UnicodeBlock COMBINING_MARKS_FOR_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock COMMON_INDIC_NUMBER_FORMS;
public static global::java.lang.Character.UnicodeBlock CONTROL_PICTURES;
public static global::java.lang.Character.UnicodeBlock COPTIC;
public static global::java.lang.Character.UnicodeBlock COUNTING_ROD_NUMERALS;
public static global::java.lang.Character.UnicodeBlock CUNEIFORM;
public static global::java.lang.Character.UnicodeBlock CUNEIFORM_NUMBERS_AND_PUNCTUATION;
public static global::java.lang.Character.UnicodeBlock CURRENCY_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock CYPRIOT_SYLLABARY;
public static global::java.lang.Character.UnicodeBlock CYRILLIC;
public static global::java.lang.Character.UnicodeBlock CYRILLIC_EXTENDED_A;
public static global::java.lang.Character.UnicodeBlock CYRILLIC_EXTENDED_B;
public static global::java.lang.Character.UnicodeBlock CYRILLIC_SUPPLEMENTARY;
public static global::java.lang.Character.UnicodeBlock DESERET;
public static global::java.lang.Character.UnicodeBlock DEVANAGARI;
public static global::java.lang.Character.UnicodeBlock DEVANAGARI_EXTENDED;
public static global::java.lang.Character.UnicodeBlock DINGBATS;
public static global::java.lang.Character.UnicodeBlock DOMINO_TILES;
public static global::java.lang.Character.UnicodeBlock EGYPTIAN_HIEROGLYPHS;
public static global::java.lang.Character.UnicodeBlock EMOTICONS;
public static global::java.lang.Character.UnicodeBlock ENCLOSED_ALPHANUMERIC_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock ENCLOSED_ALPHANUMERICS;
public static global::java.lang.Character.UnicodeBlock ENCLOSED_CJK_LETTERS_AND_MONTHS;
public static global::java.lang.Character.UnicodeBlock ENCLOSED_IDEOGRAPHIC_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock ETHIOPIC;
public static global::java.lang.Character.UnicodeBlock ETHIOPIC_EXTENDED;
public static global::java.lang.Character.UnicodeBlock ETHIOPIC_EXTENDED_A;
public static global::java.lang.Character.UnicodeBlock ETHIOPIC_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock GENERAL_PUNCTUATION;
public static global::java.lang.Character.UnicodeBlock GEOMETRIC_SHAPES;
public static global::java.lang.Character.UnicodeBlock GEORGIAN;
public static global::java.lang.Character.UnicodeBlock GEORGIAN_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock GLAGOLITIC;
public static global::java.lang.Character.UnicodeBlock GOTHIC;
public static global::java.lang.Character.UnicodeBlock GREEK;
public static global::java.lang.Character.UnicodeBlock GREEK_EXTENDED;
public static global::java.lang.Character.UnicodeBlock GUJARATI;
public static global::java.lang.Character.UnicodeBlock GURMUKHI;
public static global::java.lang.Character.UnicodeBlock HALFWIDTH_AND_FULLWIDTH_FORMS;
public static global::java.lang.Character.UnicodeBlock HANGUL_COMPATIBILITY_JAMO;
public static global::java.lang.Character.UnicodeBlock HANGUL_JAMO;
public static global::java.lang.Character.UnicodeBlock HANGUL_JAMO_EXTENDED_A;
public static global::java.lang.Character.UnicodeBlock HANGUL_JAMO_EXTENDED_B;
public static global::java.lang.Character.UnicodeBlock HANGUL_SYLLABLES;
public static global::java.lang.Character.UnicodeBlock HANUNOO;
public static global::java.lang.Character.UnicodeBlock HEBREW;
public static global::java.lang.Character.UnicodeBlock HIGH_PRIVATE_USE_SURROGATES;
public static global::java.lang.Character.UnicodeBlock HIGH_SURROGATES;
public static global::java.lang.Character.UnicodeBlock HIRAGANA;
public static global::java.lang.Character.UnicodeBlock IDEOGRAPHIC_DESCRIPTION_CHARACTERS;
public static global::java.lang.Character.UnicodeBlock IMPERIAL_ARAMAIC;
public static global::java.lang.Character.UnicodeBlock INSCRIPTIONAL_PAHLAVI;
public static global::java.lang.Character.UnicodeBlock INSCRIPTIONAL_PARTHIAN;
public static global::java.lang.Character.UnicodeBlock IPA_EXTENSIONS;
public static global::java.lang.Character.UnicodeBlock JAVANESE;
public static global::java.lang.Character.UnicodeBlock KAITHI;
public static global::java.lang.Character.UnicodeBlock KANA_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock KANBUN;
public static global::java.lang.Character.UnicodeBlock KANGXI_RADICALS;
public static global::java.lang.Character.UnicodeBlock KANNADA;
public static global::java.lang.Character.UnicodeBlock KATAKANA;
public static global::java.lang.Character.UnicodeBlock KATAKANA_PHONETIC_EXTENSIONS;
public static global::java.lang.Character.UnicodeBlock KAYAH_LI;
public static global::java.lang.Character.UnicodeBlock KHAROSHTHI;
public static global::java.lang.Character.UnicodeBlock KHMER;
public static global::java.lang.Character.UnicodeBlock KHMER_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock LAO;
public static global::java.lang.Character.UnicodeBlock LATIN_1_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock LATIN_EXTENDED_A;
public static global::java.lang.Character.UnicodeBlock LATIN_EXTENDED_ADDITIONAL;
public static global::java.lang.Character.UnicodeBlock LATIN_EXTENDED_B;
public static global::java.lang.Character.UnicodeBlock LATIN_EXTENDED_C;
public static global::java.lang.Character.UnicodeBlock LATIN_EXTENDED_D;
public static global::java.lang.Character.UnicodeBlock LEPCHA;
public static global::java.lang.Character.UnicodeBlock LETTERLIKE_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock LIMBU;
public static global::java.lang.Character.UnicodeBlock LINEAR_B_IDEOGRAMS;
public static global::java.lang.Character.UnicodeBlock LINEAR_B_SYLLABARY;
public static global::java.lang.Character.UnicodeBlock LISU;
public static global::java.lang.Character.UnicodeBlock LOW_SURROGATES;
public static global::java.lang.Character.UnicodeBlock LYCIAN;
public static global::java.lang.Character.UnicodeBlock LYDIAN;
public static global::java.lang.Character.UnicodeBlock MAHJONG_TILES;
public static global::java.lang.Character.UnicodeBlock MALAYALAM;
public static global::java.lang.Character.UnicodeBlock MANDAIC;
public static global::java.lang.Character.UnicodeBlock MATHEMATICAL_ALPHANUMERIC_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock MATHEMATICAL_OPERATORS;
public static global::java.lang.Character.UnicodeBlock MEETEI_MAYEK;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_SYMBOLS_AND_ARROWS;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS;
public static global::java.lang.Character.UnicodeBlock MISCELLANEOUS_TECHNICAL;
public static global::java.lang.Character.UnicodeBlock MODIFIER_TONE_LETTERS;
public static global::java.lang.Character.UnicodeBlock MONGOLIAN;
public static global::java.lang.Character.UnicodeBlock MUSICAL_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock MYANMAR;
public static global::java.lang.Character.UnicodeBlock MYANMAR_EXTENDED_A;
public static global::java.lang.Character.UnicodeBlock NEW_TAI_LUE;
public static global::java.lang.Character.UnicodeBlock NKO;
public static global::java.lang.Character.UnicodeBlock NUMBER_FORMS;
public static global::java.lang.Character.UnicodeBlock OGHAM;
public static global::java.lang.Character.UnicodeBlock OL_CHIKI;
public static global::java.lang.Character.UnicodeBlock OLD_ITALIC;
public static global::java.lang.Character.UnicodeBlock OLD_PERSIAN;
public static global::java.lang.Character.UnicodeBlock OLD_SOUTH_ARABIAN;
public static global::java.lang.Character.UnicodeBlock OLD_TURKIC;
public static global::java.lang.Character.UnicodeBlock OPTICAL_CHARACTER_RECOGNITION;
public static global::java.lang.Character.UnicodeBlock ORIYA;
public static global::java.lang.Character.UnicodeBlock OSMANYA;
public static global::java.lang.Character.UnicodeBlock PHAGS_PA;
public static global::java.lang.Character.UnicodeBlock PHAISTOS_DISC;
public static global::java.lang.Character.UnicodeBlock PHOENICIAN;
public static global::java.lang.Character.UnicodeBlock PHONETIC_EXTENSIONS;
public static global::java.lang.Character.UnicodeBlock PHONETIC_EXTENSIONS_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock PLAYING_CARDS;
public static global::java.lang.Character.UnicodeBlock PRIVATE_USE_AREA;
public static global::java.lang.Character.UnicodeBlock REJANG;
public static global::java.lang.Character.UnicodeBlock RUMI_NUMERAL_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock RUNIC;
public static global::java.lang.Character.UnicodeBlock SAMARITAN;
public static global::java.lang.Character.UnicodeBlock SAURASHTRA;
public static global::java.lang.Character.UnicodeBlock SHAVIAN;
public static global::java.lang.Character.UnicodeBlock SINHALA;
public static global::java.lang.Character.UnicodeBlock SMALL_FORM_VARIANTS;
public static global::java.lang.Character.UnicodeBlock SPACING_MODIFIER_LETTERS;
public static global::java.lang.Character.UnicodeBlock SPECIALS;
public static global::java.lang.Character.UnicodeBlock SUNDANESE;
public static global::java.lang.Character.UnicodeBlock SUPERSCRIPTS_AND_SUBSCRIPTS;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTAL_ARROWS_A;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTAL_ARROWS_B;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTAL_MATHEMATICAL_OPERATORS;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTAL_PUNCTUATION;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTARY_PRIVATE_USE_AREA_A;
public static global::java.lang.Character.UnicodeBlock SUPPLEMENTARY_PRIVATE_USE_AREA_B;
public static global::java.lang.Character.UnicodeBlock SURROGATES_AREA;
public static global::java.lang.Character.UnicodeBlock SYLOTI_NAGRI;
public static global::java.lang.Character.UnicodeBlock SYRIAC;
public static global::java.lang.Character.UnicodeBlock TAGALOG;
public static global::java.lang.Character.UnicodeBlock TAGBANWA;
public static global::java.lang.Character.UnicodeBlock TAGS;
public static global::java.lang.Character.UnicodeBlock TAI_LE;
public static global::java.lang.Character.UnicodeBlock TAI_THAM;
public static global::java.lang.Character.UnicodeBlock TAI_VIET;
public static global::java.lang.Character.UnicodeBlock TAI_XUAN_JING_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock TAMIL;
public static global::java.lang.Character.UnicodeBlock TELUGU;
public static global::java.lang.Character.UnicodeBlock THAANA;
public static global::java.lang.Character.UnicodeBlock THAI;
public static global::java.lang.Character.UnicodeBlock TIBETAN;
public static global::java.lang.Character.UnicodeBlock TIFINAGH;
public static global::java.lang.Character.UnicodeBlock TRANSPORT_AND_MAP_SYMBOLS;
public static global::java.lang.Character.UnicodeBlock UGARITIC;
public static global::java.lang.Character.UnicodeBlock UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS;
public static global::java.lang.Character.UnicodeBlock UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED;
public static global::java.lang.Character.UnicodeBlock VAI;
public static global::java.lang.Character.UnicodeBlock VARIATION_SELECTORS;
public static global::java.lang.Character.UnicodeBlock VARIATION_SELECTORS_SUPPLEMENT;
public static global::java.lang.Character.UnicodeBlock VEDIC_EXTENSIONS;
public static global::java.lang.Character.UnicodeBlock VERTICAL_FORMS;
public static global::java.lang.Character.UnicodeBlock YI_RADICALS;
public static global::java.lang.Character.UnicodeBlock YI_SYLLABLES;
public static global::java.lang.Character.UnicodeBlock YIJING_HEXAGRAM_SYMBOLS;
public UnicodeBlock() : base(default(global::java.lang.String)){}
public static global::java.lang.Character.UnicodeBlock forName(global::java.lang.String prm1){return default(global::java.lang.Character.UnicodeBlock);}
public static global::java.lang.Character.UnicodeBlock of(int prm1){return default(global::java.lang.Character.UnicodeBlock);}
public static global::java.lang.Character.UnicodeBlock of(char prm1){return default(global::java.lang.Character.UnicodeBlock);}
}
public partial class UnicodeScript : global::java.lang.Enum<global::java.lang.Character.UnicodeScript>
{
public static global::java.lang.Character.UnicodeScript ARABIC;
public static global::java.lang.Character.UnicodeScript ARMENIAN;
public static global::java.lang.Character.UnicodeScript AVESTAN;
public static global::java.lang.Character.UnicodeScript BALINESE;
public static global::java.lang.Character.UnicodeScript BAMUM;
public static global::java.lang.Character.UnicodeScript BATAK;
public static global::java.lang.Character.UnicodeScript BENGALI;
public static global::java.lang.Character.UnicodeScript BOPOMOFO;
public static global::java.lang.Character.UnicodeScript BRAHMI;
public static global::java.lang.Character.UnicodeScript BRAILLE;
public static global::java.lang.Character.UnicodeScript BUGINESE;
public static global::java.lang.Character.UnicodeScript BUHID;
public static global::java.lang.Character.UnicodeScript CANADIAN_ABORIGINAL;
public static global::java.lang.Character.UnicodeScript CARIAN;
public static global::java.lang.Character.UnicodeScript CHAM;
public static global::java.lang.Character.UnicodeScript CHEROKEE;
public static global::java.lang.Character.UnicodeScript COMMON;
public static global::java.lang.Character.UnicodeScript COPTIC;
public static global::java.lang.Character.UnicodeScript CUNEIFORM;
public static global::java.lang.Character.UnicodeScript CYPRIOT;
public static global::java.lang.Character.UnicodeScript CYRILLIC;
public static global::java.lang.Character.UnicodeScript DESERET;
public static global::java.lang.Character.UnicodeScript DEVANAGARI;
public static global::java.lang.Character.UnicodeScript EGYPTIAN_HIEROGLYPHS;
public static global::java.lang.Character.UnicodeScript ETHIOPIC;
public static global::java.lang.Character.UnicodeScript GEORGIAN;
public static global::java.lang.Character.UnicodeScript GLAGOLITIC;
public static global::java.lang.Character.UnicodeScript GOTHIC;
public static global::java.lang.Character.UnicodeScript GREEK;
public static global::java.lang.Character.UnicodeScript GUJARATI;
public static global::java.lang.Character.UnicodeScript GURMUKHI;
public static global::java.lang.Character.UnicodeScript HAN;
public static global::java.lang.Character.UnicodeScript HANGUL;
public static global::java.lang.Character.UnicodeScript HANUNOO;
public static global::java.lang.Character.UnicodeScript HEBREW;
public static global::java.lang.Character.UnicodeScript HIRAGANA;
public static global::java.lang.Character.UnicodeScript IMPERIAL_ARAMAIC;
public static global::java.lang.Character.UnicodeScript INHERITED;
public static global::java.lang.Character.UnicodeScript INSCRIPTIONAL_PAHLAVI;
public static global::java.lang.Character.UnicodeScript INSCRIPTIONAL_PARTHIAN;
public static global::java.lang.Character.UnicodeScript JAVANESE;
public static global::java.lang.Character.UnicodeScript KAITHI;
public static global::java.lang.Character.UnicodeScript KANNADA;
public static global::java.lang.Character.UnicodeScript KATAKANA;
public static global::java.lang.Character.UnicodeScript KAYAH_LI;
public static global::java.lang.Character.UnicodeScript KHAROSHTHI;
public static global::java.lang.Character.UnicodeScript KHMER;
public static global::java.lang.Character.UnicodeScript LAO;
public static global::java.lang.Character.UnicodeScript LATIN;
public static global::java.lang.Character.UnicodeScript LEPCHA;
public static global::java.lang.Character.UnicodeScript LIMBU;
public static global::java.lang.Character.UnicodeScript LINEAR_B;
public static global::java.lang.Character.UnicodeScript LISU;
public static global::java.lang.Character.UnicodeScript LYCIAN;
public static global::java.lang.Character.UnicodeScript LYDIAN;
public static global::java.lang.Character.UnicodeScript MALAYALAM;
public static global::java.lang.Character.UnicodeScript MANDAIC;
public static global::java.lang.Character.UnicodeScript MEETEI_MAYEK;
public static global::java.lang.Character.UnicodeScript MONGOLIAN;
public static global::java.lang.Character.UnicodeScript MYANMAR;
public static global::java.lang.Character.UnicodeScript NEW_TAI_LUE;
public static global::java.lang.Character.UnicodeScript NKO;
public static global::java.lang.Character.UnicodeScript OGHAM;
public static global::java.lang.Character.UnicodeScript OL_CHIKI;
public static global::java.lang.Character.UnicodeScript OLD_ITALIC;
public static global::java.lang.Character.UnicodeScript OLD_PERSIAN;
public static global::java.lang.Character.UnicodeScript OLD_SOUTH_ARABIAN;
public static global::java.lang.Character.UnicodeScript OLD_TURKIC;
public static global::java.lang.Character.UnicodeScript ORIYA;
public static global::java.lang.Character.UnicodeScript OSMANYA;
public static global::java.lang.Character.UnicodeScript PHAGS_PA;
public static global::java.lang.Character.UnicodeScript PHOENICIAN;
public static global::java.lang.Character.UnicodeScript REJANG;
public static global::java.lang.Character.UnicodeScript RUNIC;
public static global::java.lang.Character.UnicodeScript SAMARITAN;
public static global::java.lang.Character.UnicodeScript SAURASHTRA;
public static global::java.lang.Character.UnicodeScript SHAVIAN;
public static global::java.lang.Character.UnicodeScript SINHALA;
public static global::java.lang.Character.UnicodeScript SUNDANESE;
public static global::java.lang.Character.UnicodeScript SYLOTI_NAGRI;
public static global::java.lang.Character.UnicodeScript SYRIAC;
public static global::java.lang.Character.UnicodeScript TAGALOG;
public static global::java.lang.Character.UnicodeScript TAGBANWA;
public static global::java.lang.Character.UnicodeScript TAI_LE;
public static global::java.lang.Character.UnicodeScript TAI_THAM;
public static global::java.lang.Character.UnicodeScript TAI_VIET;
public static global::java.lang.Character.UnicodeScript TAMIL;
public static global::java.lang.Character.UnicodeScript TELUGU;
public static global::java.lang.Character.UnicodeScript THAANA;
public static global::java.lang.Character.UnicodeScript THAI;
public static global::java.lang.Character.UnicodeScript TIBETAN;
public static global::java.lang.Character.UnicodeScript TIFINAGH;
public static global::java.lang.Character.UnicodeScript UGARITIC;
public static global::java.lang.Character.UnicodeScript UNKNOWN;
public static global::java.lang.Character.UnicodeScript VAI;
public static global::java.lang.Character.UnicodeScript YI;
public UnicodeScript(){}
public static global::java.lang.Character.UnicodeScript forName(global::java.lang.String prm1){return default(global::java.lang.Character.UnicodeScript);}
public static global::java.lang.Character.UnicodeScript of(int prm1){return default(global::java.lang.Character.UnicodeScript);}
public static global::java.lang.Character.UnicodeScript valueOf(global::java.lang.String prm1){return default(global::java.lang.Character.UnicodeScript);}
public static global::java.lang.Character.UnicodeScript[] values(){return default(global::java.lang.Character.UnicodeScript[]);}
}
public static byte COMBINING_SPACING_MARK;
public static byte CONNECTOR_PUNCTUATION;
public static byte CONTROL;
public static byte CURRENCY_SYMBOL;
public static byte DASH_PUNCTUATION;
public static byte DECIMAL_DIGIT_NUMBER;
public static byte DIRECTIONALITY_ARABIC_NUMBER;
public static byte DIRECTIONALITY_BOUNDARY_NEUTRAL;
public static byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR;
public static byte DIRECTIONALITY_EUROPEAN_NUMBER;
public static byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR;
public static byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR;
public static byte DIRECTIONALITY_LEFT_TO_RIGHT;
public static byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING;
public static byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE;
public static byte DIRECTIONALITY_NONSPACING_MARK;
public static byte DIRECTIONALITY_OTHER_NEUTRALS;
public static byte DIRECTIONALITY_PARAGRAPH_SEPARATOR;
public static byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT;
public static byte DIRECTIONALITY_RIGHT_TO_LEFT;
public static byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
public static byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING;
public static byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE;
public static byte DIRECTIONALITY_SEGMENT_SEPARATOR;
public static byte DIRECTIONALITY_UNDEFINED;
public static byte DIRECTIONALITY_WHITESPACE;
public static byte ENCLOSING_MARK;
public static byte END_PUNCTUATION;
public static byte FINAL_QUOTE_PUNCTUATION;
public static byte FORMAT;
public static byte INITIAL_QUOTE_PUNCTUATION;
public static byte LETTER_NUMBER;
public static byte LINE_SEPARATOR;
public static byte LOWERCASE_LETTER;
public static byte MATH_SYMBOL;
public static int MAX_CODE_POINT;
public static char MAX_HIGH_SURROGATE;
public static char MAX_LOW_SURROGATE;
public static int MAX_RADIX;
public static char MAX_SURROGATE;
public static char MAX_VALUE;
public static int MIN_CODE_POINT;
public static char MIN_HIGH_SURROGATE;
public static char MIN_LOW_SURROGATE;
public static int MIN_RADIX;
public static int MIN_SUPPLEMENTARY_CODE_POINT;
public static char MIN_SURROGATE;
public static char MIN_VALUE;
public static byte MODIFIER_LETTER;
public static byte MODIFIER_SYMBOL;
public static byte NON_SPACING_MARK;
public static byte OTHER_LETTER;
public static byte OTHER_NUMBER;
public static byte OTHER_PUNCTUATION;
public static byte OTHER_SYMBOL;
public static byte PARAGRAPH_SEPARATOR;
public static byte PRIVATE_USE;
public static int SIZE;
public static byte SPACE_SEPARATOR;
public static byte START_PUNCTUATION;
public static byte SURROGATE;
public static byte TITLECASE_LETTER;
public static Class<Character> TYPE;
public static byte UNASSIGNED;
public static byte UPPERCASE_LETTER;
public static int charCount(int prm1){return default(int);}
public virtual char charValue(){return default(char);}
public static int codePointAt(CharSequence prm1, int prm2){return default(int);}
public static int codePointAt(char[] prm1, int prm2){return default(int);}
public static int codePointAt(char[] prm1, int prm2, int prm3){return default(int);}
public static int codePointBefore(char[] prm1, int prm2, int prm3){return default(int);}
public static int codePointBefore(CharSequence prm1, int prm2){return default(int);}
public static int codePointBefore(char[] prm1, int prm2){return default(int);}
public static int codePointCount(char[] prm1, int prm2, int prm3){return default(int);}
public static int codePointCount(CharSequence prm1, int prm2, int prm3){return default(int);}
public static int compare(char prm1, char prm2){return default(int);}
public virtual int compareTo(Character prm1){return default(int);}
public static int digit(char prm1, int prm2){return default(int);}
public static int digit(int prm1, int prm2){return default(int);}
public override bool equals(global::System.Object prm1){return default(bool);}
public static char forDigit(int prm1, int prm2){return default(char);}
public static byte getDirectionality(char prm1){return default(byte);}
public static byte getDirectionality(int prm1){return default(byte);}
public static String getName(int prm1){return default(String);}
public static int getNumericValue(int prm1){return default(int);}
public static int getNumericValue(char prm1){return default(int);}
public static int getType(int prm1){return default(int);}
public static int getType(char prm1){return default(int);}
public override int hashCode(){return default(int);}
public static char highSurrogate(int prm1){return default(char);}
public static bool isAlphabetic(int prm1){return default(bool);}
public static bool isBmpCodePoint(int prm1){return default(bool);}
public static bool isDefined(char prm1){return default(bool);}
public static bool isDefined(int prm1){return default(bool);}
public static bool isDigit(int prm1){return default(bool);}
public static bool isDigit(char prm1){return default(bool);}
public static bool isHighSurrogate(char prm1){return default(bool);}
public static bool isIdentifierIgnorable(char prm1){return default(bool);}
public static bool isIdentifierIgnorable(int prm1){return default(bool);}
public static bool isIdeographic(int prm1){return default(bool);}
public static bool isISOControl(int prm1){return default(bool);}
public static bool isISOControl(char prm1){return default(bool);}
public static bool isJavaIdentifierPart(int prm1){return default(bool);}
public static bool isJavaIdentifierPart(char prm1){return default(bool);}
public static bool isJavaIdentifierStart(char prm1){return default(bool);}
public static bool isJavaIdentifierStart(int prm1){return default(bool);}
public static bool isJavaLetter(char prm1){return default(bool);}
public static bool isJavaLetterOrDigit(char prm1){return default(bool);}
public static bool isLetter(char prm1){return default(bool);}
public static bool isLetter(int prm1){return default(bool);}
public static bool isLetterOrDigit(char prm1){return default(bool);}
public static bool isLetterOrDigit(int prm1){return default(bool);}
public static bool isLowerCase(char prm1){return default(bool);}
public static bool isLowerCase(int prm1){return default(bool);}
public static bool isLowSurrogate(char prm1){return default(bool);}
public static bool isMirrored(int prm1){return default(bool);}
public static bool isMirrored(char prm1){return default(bool);}
public static bool isSpace(char prm1){return default(bool);}
public static bool isSpaceChar(int prm1){return default(bool);}
public static bool isSpaceChar(char prm1){return default(bool);}
public static bool isSupplementaryCodePoint(int prm1){return default(bool);}
public static bool isSurrogate(char prm1){return default(bool);}
public static bool isSurrogatePair(char prm1, char prm2){return default(bool);}
public static bool isTitleCase(char prm1){return default(bool);}
public static bool isTitleCase(int prm1){return default(bool);}
public static bool isUnicodeIdentifierPart(int prm1){return default(bool);}
public static bool isUnicodeIdentifierPart(char prm1){return default(bool);}
public static bool isUnicodeIdentifierStart(int prm1){return default(bool);}
public static bool isUnicodeIdentifierStart(char prm1){return default(bool);}
public static bool isUpperCase(int prm1){return default(bool);}
public static bool isUpperCase(char prm1){return default(bool);}
public static bool isValidCodePoint(int prm1){return default(bool);}
public static bool isWhitespace(int prm1){return default(bool);}
public static bool isWhitespace(char prm1){return default(bool);}
public Character(char prm1){}
public static char lowSurrogate(int prm1){return default(char);}
public static int offsetByCodePoints(char[] prm1, int prm2, int prm3, int prm4, int prm5){return default(int);}
public static int offsetByCodePoints(CharSequence prm1, int prm2, int prm3){return default(int);}
public static char reverseBytes(char prm1){return default(char);}
public static char[] toChars(int prm1){return default(char[]);}
public static int toChars(int prm1, char[] prm2, int prm3){return default(int);}
public static int toCodePoint(char prm1, char prm2){return default(int);}
public static char toLowerCase(char prm1){return default(char);}
public static int toLowerCase(int prm1){return default(int);}
public override String toString(){return default(String);}
public static String toString(char prm1){return default(String);}
public static int toTitleCase(int prm1){return default(int);}
public static char toTitleCase(char prm1){return default(char);}
public static int toUpperCase(int prm1){return default(int);}
public static char toUpperCase(char prm1){return default(char);}
public static Character valueOf(char prm1){return default(Character);}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// Dynamic Language Runtime Compiler.
/// This part compiles lambdas.
/// </summary>
internal partial class LambdaCompiler
{
#if FEATURE_COMPILE_TO_METHODBUILDER
private static int s_counter;
#endif
internal void EmitConstantArray<T>(T[] array)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
// Emit as runtime constant if possible
// if not, emit into IL
if (_method is DynamicMethod)
#else
Debug.Assert(_method is DynamicMethod);
#endif
{
EmitConstant(array, typeof(T[]));
}
#if FEATURE_COMPILE_TO_METHODBUILDER
else if (_typeBuilder != null)
{
// store into field in our type builder, we will initialize
// the value only once.
FieldBuilder fb = CreateStaticField("ConstantArray", typeof(T[]));
Label l = _ilg.DefineLabel();
_ilg.Emit(OpCodes.Ldsfld, fb);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Bne_Un, l);
_ilg.EmitArray(array);
_ilg.Emit(OpCodes.Stsfld, fb);
_ilg.MarkLabel(l);
_ilg.Emit(OpCodes.Ldsfld, fb);
}
else
{
_ilg.EmitArray(array);
}
#endif
}
private void EmitClosureCreation(LambdaCompiler inner)
{
bool closure = inner._scope.NeedsClosure;
bool boundConstants = inner._boundConstants.Count > 0;
if (!closure && !boundConstants)
{
_ilg.EmitNull();
return;
}
// new Closure(constantPool, currentHoistedLocals)
if (boundConstants)
{
_boundConstants.EmitConstant(this, inner._boundConstants.ToArray(), typeof(object[]));
}
else
{
_ilg.EmitNull();
}
if (closure)
{
_scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
}
else
{
_ilg.EmitNull();
}
_ilg.EmitNew(Closure_ObjectArray_ObjectArray);
}
/// <summary>
/// Emits code which creates new instance of the delegateType delegate.
///
/// Since the delegate is getting closed over the "Closure" argument, this
/// cannot be used with virtual/instance methods (inner must be static method)
/// </summary>
private void EmitDelegateConstruction(LambdaCompiler inner)
{
Type delegateType = inner._lambda.Type;
DynamicMethod dynamicMethod = inner._method as DynamicMethod;
#if FEATURE_COMPILE_TO_METHODBUILDER
if (dynamicMethod != null)
#else
Debug.Assert(dynamicMethod != null);
#endif
{
// Emit MethodInfo.CreateDelegate instead because DynamicMethod is not in Windows 8 Profile
_boundConstants.EmitConstant(this, dynamicMethod, typeof(MethodInfo));
_ilg.EmitType(delegateType);
EmitClosureCreation(inner);
_ilg.Emit(OpCodes.Callvirt, MethodInfo_CreateDelegate_Type_Object);
_ilg.Emit(OpCodes.Castclass, delegateType);
}
#if FEATURE_COMPILE_TO_METHODBUILDER
else
{
// new DelegateType(closure)
EmitClosureCreation(inner);
_ilg.Emit(OpCodes.Ldftn, inner._method);
_ilg.Emit(OpCodes.Newobj, (ConstructorInfo)(delegateType.GetMember(".ctor")[0]));
}
#endif
}
/// <summary>
/// Emits a delegate to the method generated for the LambdaExpression.
/// May end up creating a wrapper to match the requested delegate type.
/// </summary>
/// <param name="lambda">Lambda for which to generate a delegate</param>
///
private void EmitDelegateConstruction(LambdaExpression lambda)
{
// 1. Create the new compiler
LambdaCompiler impl;
#if FEATURE_COMPILE_TO_METHODBUILDER
if (_method is DynamicMethod)
#else
Debug.Assert(_method is DynamicMethod);
#endif
{
impl = new LambdaCompiler(_tree, lambda);
}
#if FEATURE_COMPILE_TO_METHODBUILDER
else
{
// When the lambda does not have a name or the name is empty, generate a unique name for it.
string name = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name;
MethodBuilder mb = _typeBuilder.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static);
impl = new LambdaCompiler(_tree, lambda, mb);
}
#endif
// 2. emit the lambda
// Since additional ILs are always emitted after the lambda's body, should not emit with tail call optimization.
impl.EmitLambdaBody(_scope, false, CompilationFlags.EmitAsNoTail);
// 3. emit the delegate creation in the outer lambda
EmitDelegateConstruction(impl);
}
private static Type[] GetParameterTypes(LambdaExpression lambda, Type firstType)
{
var parameters = lambda.Parameters;
var count = parameters.Count;
Type[] result;
int i;
if (firstType != null)
{
result = new Type[count + 1];
result[0] = firstType;
i = 1;
}
else
{
result = new Type[count];
i = 0;
}
for (var j = 0; j < count; j++, i++)
{
var p = parameters[j];
result[i] = p.IsByRef ? p.Type.MakeByRefType() : p.Type;
}
return result;
}
#if FEATURE_COMPILE_TO_METHODBUILDER
private static string GetUniqueMethodName()
{
return "<ExpressionCompilerImplementationDetails>{" + System.Threading.Interlocked.Increment(ref s_counter) + "}lambda_method";
}
#endif
private void EmitLambdaBody()
{
// The lambda body is the "last" expression of the lambda
CompilationFlags tailCallFlag = _lambda.TailCall ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail;
EmitLambdaBody(null, false, tailCallFlag);
}
/// <summary>
/// Emits the lambda body. If inlined, the parameters should already be
/// pushed onto the IL stack.
/// </summary>
/// <param name="parent">The parent scope.</param>
/// <param name="inlined">true if the lambda is inlined; false otherwise.</param>
/// <param name="flags">
/// The enum to specify if the lambda is compiled with the tail call optimization.
/// </param>
private void EmitLambdaBody(CompilerScope parent, bool inlined, CompilationFlags flags)
{
_scope.Enter(this, parent);
if (inlined)
{
// The arguments were already pushed onto the IL stack.
// Store them into locals, popping in reverse order.
//
// If any arguments were ByRef, the address is on the stack and
// we'll be storing it into the variable, which has a ref type.
for (int i = _lambda.Parameters.Count - 1; i >= 0; i--)
{
_scope.EmitSet(_lambda.Parameters[i]);
}
}
// Need to emit the expression start for the lambda body
flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
if (_lambda.ReturnType == typeof(void))
{
EmitExpressionAsVoid(_lambda.Body, flags);
}
else
{
EmitExpression(_lambda.Body, flags);
}
// Return must be the last instruction in a CLI method.
// But if we're inlining the lambda, we want to leave the return
// value on the IL stack.
if (!inlined)
{
_ilg.Emit(OpCodes.Ret);
}
_scope.Exit();
// Validate labels
Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda);
foreach (LabelInfo label in _labelInfo.Values)
{
label.ValidateFinish();
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Game.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace ColorReplacement
{
/// <summary>
/// Sample showing how to change the color of select areas on a model.
/// </summary>
public class ColorReplacementGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
Matrix view;
Matrix projection;
Model model;
/// <summary>
/// Desired color parts of the model will have after color replacement
/// </summary>
Vector3 targetColor = Color.Green.ToVector3();
/// <summary>
/// Maximum rate at which selected channels of the
/// target color are changed based on user input
/// </summary>
const float ColorChangeRate = 0.01f;
#endregion
#region Initialization
public ColorReplacementGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Create view matrix
view = Matrix.CreateLookAt(
new Vector3(0, 2.75f, 5), new Vector3(0, 0.25f, 0), Vector3.Up);
}
protected override void Initialize()
{
base.Initialize();
// Create projection matrix
projection = Matrix.CreatePerspectiveFieldOfView(1, GraphicsDevice.Viewport.AspectRatio, 1.0f, 10000.0f);
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("SpriteFont");
model = Content.Load<Model>("Car");
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
// Draw a spinning model
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
Matrix world = Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds * 0.2f);
DrawModel(world);
DrawOverlayText();
base.Draw(gameTime);
}
/// <summary>
/// Draws a model that uses BasicEffect or ReplaceColor.fx on its parts
/// </summary>
private void DrawModel(Matrix world)
{
Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in model.Meshes)
{
Matrix boneWorld = transforms[mesh.ParentBone.Index] * world;
foreach (Effect effect in mesh.Effects)
{
// The car model has been modified to reference ReplaceColor.fx
// The parameters need to be set differently for that effect
BasicEffect basicEffect = effect as BasicEffect;
if (basicEffect != null)
{
// Set parameters on a BasicEffect
basicEffect.EnableDefaultLighting();
basicEffect.World = boneWorld;
basicEffect.View = view;
basicEffect.Projection = projection;
}
else
{
// Set parameters on a color replacement effect
effect.Parameters["WorldViewProjection"].SetValue(
boneWorld * view * projection);
effect.Parameters["World"].SetValue(boneWorld);
effect.Parameters["TargetColor"].SetValue(targetColor);
}
}
mesh.Draw();
}
}
/// <summary>
/// Draws the text overlay including instructions and
/// the current target color
/// </summary>
private void DrawOverlayText()
{
spriteBatch.Begin();
spriteBatch.DrawString(spriteFont,
"Hold R/G/B key or X/A/B button and press Up/Down to change color",
new Vector2(50, 30), Color.Black);
spriteBatch.DrawString(spriteFont,
"Red (R key, B button): " + targetColor.X.ToString("0.000"),
new Vector2(50, 50), Color.Red);
spriteBatch.DrawString(spriteFont,
"Green (G key, A button): " + targetColor.Y.ToString("0.000"),
new Vector2(50, 70), Color.Lime);
spriteBatch.DrawString(spriteFont,
"Blue (B key, X button): " + targetColor.Z.ToString("0.000"),
new Vector2(50, 90), Color.Blue);
spriteBatch.End();
}
#endregion
#region HandleInput
/// <summary>
/// Handles input for quitting the game.
/// </summary>
void HandleInput()
{
KeyboardState keyboardState = Keyboard.GetState();
GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (keyboardState.IsKeyDown(Keys.Escape) ||
gamePadState.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
// Calculate how much to change the color with up/down
float colorChange = gamePadState.ThumbSticks.Left.Y * ColorChangeRate;
if (keyboardState.IsKeyDown(Keys.Up) ||
gamePadState.DPad.Up == ButtonState.Pressed)
{
colorChange = ColorChangeRate;
}
else if (keyboardState.IsKeyDown(Keys.Down) ||
gamePadState.DPad.Down == ButtonState.Pressed)
{
colorChange = -ColorChangeRate;
}
// Change red
if (keyboardState.IsKeyDown(Keys.R) ||
gamePadState.Buttons.B == ButtonState.Pressed)
{
targetColor.X = MathHelper.Clamp(targetColor.X + colorChange, 0, 1);
}
// Change green
if (keyboardState.IsKeyDown(Keys.G) ||
gamePadState.Buttons.A == ButtonState.Pressed)
{
targetColor.Y = MathHelper.Clamp(targetColor.Y + colorChange, 0, 1);
}
// Change blue
if (keyboardState.IsKeyDown(Keys.B) ||
gamePadState.Buttons.X == ButtonState.Pressed)
{
targetColor.Z = MathHelper.Clamp(targetColor.Z + colorChange, 0, 1);
}
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (ColorReplacementGame game = new ColorReplacementGame())
{
game.Run();
}
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using WhatsAppApi.Helper;
using WhatsAppApi.Parser;
using WhatsAppApi.Response;
using WhatsAppApi.Settings;
namespace WhatsAppApi
{
/// <summary>
/// Main api interface
/// </summary>
public class WhatsApp : WhatsSendBase
{
public WhatsApp(string phoneNum, string imei, string nick, bool debug = false, bool hidden = false)
{
this._constructBase(phoneNum, imei, nick, debug, hidden);
}
public string SendMessage(string to, string txt)
{
var tmpMessage = new FMessage(GetJID(to), true) { data = txt };
this.SendMessage(tmpMessage, this.hidden);
return tmpMessage.identifier_key.ToString();
}
public void SendMessageVcard(string to, string name, string vcard_data)
{
var tmpMessage = new FMessage(GetJID(to), true) { data = vcard_data, media_wa_type = FMessage.Type.Contact, media_name = name };
this.SendMessage(tmpMessage, this.hidden);
}
public void SendSync(string[] numbers, SyncMode mode = SyncMode.Delta, SyncContext context = SyncContext.Background, int index = 0, bool last = true)
{
List<ProtocolTreeNode> users = new List<ProtocolTreeNode>();
foreach (string number in numbers)
{
string _number = number;
if (!_number.StartsWith("+", StringComparison.InvariantCulture))
_number = string.Format("+{0}", number);
users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(_number)));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[]
{
new KeyValue("to", GetJID(this.phoneNumber)),
new KeyValue("type", "get"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("xmlns", "urn:xmpp:whatsapp:sync")
}, new ProtocolTreeNode("sync", new KeyValue[]
{
new KeyValue("mode", mode.ToString().ToLowerInvariant()),
new KeyValue("context", context.ToString().ToLowerInvariant()),
new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()),
new KeyValue("index", index.ToString()),
new KeyValue("last", last.ToString())
},
users.ToArray()
)
);
this.SendNode(node);
}
public void SendMessageImage(string to, byte[] ImageData, ImageType imgtype)
{
FMessage msg = this.getFmessageImage(to, ImageData, imgtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageImage(string to, byte[] ImageData, ImageType imgtype)
{
string type = string.Empty;
string extension = string.Empty;
switch (imgtype)
{
case ImageType.PNG:
type = "image/png";
extension = "png";
break;
case ImageType.GIF:
type = "image/gif";
extension = "gif";
break;
default:
type = "image/jpeg";
extension = "jpg";
break;
}
//create hash
string filehash = string.Empty;
using(HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(ImageData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "image", ImageData.Length, ImageData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true)
{
media_wa_type = FMessage.Type.Image,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
binary_data = this.CreateThumbnail(ImageData)
};
return msg;
}
return null;
}
public void SendMessageVideo(string to, byte[] videoData, VideoType vidtype)
{
FMessage msg = this.getFmessageVideo(to, videoData, vidtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageVideo(string to, byte[] videoData, VideoType vidtype)
{
to = GetJID(to);
string type = string.Empty;
string extension = string.Empty;
switch (vidtype)
{
case VideoType.MOV:
type = "video/quicktime";
extension = "mov";
break;
case VideoType.AVI:
type = "video/x-msvideo";
extension = "avi";
break;
default:
type = "video/mp4";
extension = "mp4";
break;
}
//create hash
string filehash = string.Empty;
using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(videoData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "video", videoData.Length, videoData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true) {
media_wa_type = FMessage.Type.Video,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
media_duration_seconds = response.duration
};
return msg;
}
return null;
}
public void SendMessageAudio(string to, byte[] audioData, AudioType audtype)
{
FMessage msg = this.getFmessageAudio(to, audioData, audtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageAudio(string to, byte[] audioData, AudioType audtype)
{
to = GetJID(to);
string type = string.Empty;
string extension = string.Empty;
switch (audtype)
{
case AudioType.WAV:
type = "audio/wav";
extension = "wav";
break;
case AudioType.OGG:
type = "audio/ogg";
extension = "ogg";
break;
default:
type = "audio/mpeg";
extension = "mp3";
break;
}
//create hash
string filehash = string.Empty;
using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(audioData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "audio", audioData.Length, audioData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true) {
media_wa_type = FMessage.Type.Audio,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
media_duration_seconds = response.duration
};
return msg;
}
return null;
}
protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
{
ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
new KeyValue("hash", b64hash),
new KeyValue("type", type),
new KeyValue("size", size.ToString())
});
string id = TicketManager.GenerateId();
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("id", id),
new KeyValue("to", WhatsConstants.WhatsAppServer),
new KeyValue("type", "set"),
new KeyValue("xmlns", "w:m")
}, media);
this.uploadResponse = null;
this.SendNode(node);
int i = 0;
while (this.uploadResponse == null && i <= 10)
{
i++;
this.pollMessage();
}
if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
{
WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
this.uploadResponse = null;
return res;
}
else
{
try
{
string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
this.uploadResponse = null;
Uri uri = new Uri(uploadUrl);
string hashname = string.Empty;
byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
StringBuilder sb = new StringBuilder();
foreach (byte b in buff)
{
sb.Append(b.ToString("X2"));
}
hashname = String.Format("{0}.{1}", sb.ToString(), extension);
string boundary = "zzXXzzYYzzXXzzQQ";
sb = new StringBuilder();
sb.AppendFormat("--{0}\r\n", boundary);
sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
sb.AppendFormat("{0}\r\n", to);
sb.AppendFormat("--{0}\r\n", boundary);
sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
sb.AppendFormat("{0}\r\n", this.phoneNumber);
sb.AppendFormat("--{0}\r\n", boundary);
sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
string header = sb.ToString();
sb = new StringBuilder();
sb.AppendFormat("\r\n--{0}--\r\n", boundary);
string footer = sb.ToString();
long clength = size + header.Length + footer.Length;
sb = new StringBuilder();
sb.AppendFormat("POST {0}\r\n", uploadUrl);
sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
sb.AppendFormat("Host: {0}\r\n", uri.Host);
sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
string post = sb.ToString();
TcpClient tc = new TcpClient(uri.Host, 443);
SslStream ssl = new SslStream(tc.GetStream());
ssl.AuthenticateAsClient(uri.Host);
List<byte> buf = new List<byte>();
buf.AddRange(Encoding.UTF8.GetBytes(post));
buf.AddRange(Encoding.UTF8.GetBytes(header));
buf.AddRange(fileData);
buf.AddRange(Encoding.UTF8.GetBytes(footer));
ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);
//moment of truth...
buff = new byte[1024];
ssl.Read(buff, 0, 1024);
string result = Encoding.UTF8.GetString(buff);
foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith("{"))
{
string fooo = line.TrimEnd(new char[] { (char)0 });
JavaScriptSerializer jss = new JavaScriptSerializer();
WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo);
if (!String.IsNullOrEmpty(resp.url))
{
return resp;
}
}
}
}
catch (Exception)
{ }
}
return null;
}
protected void SendQrSync(byte[] qrkey, byte[] token = null)
{
string id = TicketCounter.MakeId();
List<ProtocolTreeNode> children = new List<ProtocolTreeNode>();
children.Add(new ProtocolTreeNode("sync", null, qrkey));
if (token != null)
{
children.Add(new ProtocolTreeNode("code", null, token));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("type", "set"),
new KeyValue("id", id),
new KeyValue("xmlns", "w:web")
}, children.ToArray());
this.SendNode(node);
}
public void SendActive()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "active") });
this.SendNode(node);
}
public void SendAddParticipants(string gjid, IEnumerable<string> participants)
{
string id = TicketCounter.MakeId();
this.SendVerbParticipants(gjid, participants, id, "add");
}
public void SendUnavailable()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") });
this.SendNode(node);
}
public void SendClientConfig(string platform, string lg, string lc)
{
string v = TicketCounter.MakeId();
var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push"), new KeyValue("platform", platform), new KeyValue("lg", lg), new KeyValue("lc", lc) });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", v), new KeyValue("type", "set"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendClientConfig(string platform, string lg, string lc, Uri pushUri, bool preview, bool defaultSetting, bool groupsSetting, IEnumerable<GroupSetting> groups, Action onCompleted, Action<int> onError)
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq",
new[]
{
new KeyValue("id", id), new KeyValue("type", "set"),
new KeyValue("to", "") //this.Login.Domain)
},
new ProtocolTreeNode[]
{
new ProtocolTreeNode("config",
new[]
{
new KeyValue("xmlns","urn:xmpp:whatsapp:push"),
new KeyValue("platform", platform),
new KeyValue("lg", lg),
new KeyValue("lc", lc),
new KeyValue("clear", "0"),
new KeyValue("id", pushUri.ToString()),
new KeyValue("preview",preview ? "1" : "0"),
new KeyValue("default",defaultSetting ? "1" : "0"),
new KeyValue("groups",groupsSetting ? "1" : "0")
},
this.ProcessGroupSettings(groups))
});
this.SendNode(node);
}
public void SendClose()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") });
this.SendNode(node);
}
public void SendComposing(string to)
{
this.SendChatState(to, "composing");
}
protected void SendChatState(string to, string type)
{
var node = new ProtocolTreeNode("chatstate", new[] { new KeyValue("to", WhatsApp.GetJID(to)) }, new[] {
new ProtocolTreeNode(type, null)
});
this.SendNode(node);
}
public void SendCreateGroupChat(string subject, IEnumerable<string> participants)
{
string id = TicketCounter.MakeId();
IEnumerable<ProtocolTreeNode> participant = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) });
var child = new ProtocolTreeNode("create", new[] { new KeyValue("subject", subject) }, new ProtocolTreeNode[] { (ProtocolTreeNode) participant });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendDeleteAccount()
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq",
new KeyValue[]
{
new KeyValue("id", id),
new KeyValue("type", "get"),
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("xmlns", "urn:xmpp:whatsapp:account")
},
new ProtocolTreeNode[]
{
new ProtocolTreeNode("remove",
null
)
});
this.SendNode(node);
}
public void SendDeleteFromRoster(string jid)
{
string v = TicketCounter.MakeId();
var innerChild = new ProtocolTreeNode("item", new[] { new KeyValue("jid", jid), new KeyValue("subscription", "remove") });
var child = new ProtocolTreeNode("query", new[] { new KeyValue("xmlns", "jabber:iq:roster") }, new ProtocolTreeNode[] { innerChild });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("type", "set"), new KeyValue("id", v) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendEndGroupChat(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("group", new[] { new KeyValue("action", "delete") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetClientConfig()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetDirty()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("status", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:dirty") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetGroupInfo(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("query", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(gjid)) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetGroups()
{
string id = TicketCounter.MakeId();
this.SendGetGroups(id, "participating");
}
public void SendGetOwningGroups()
{
string id = TicketCounter.MakeId();
this.SendGetGroups(id, "owning");
}
public void SendGetParticipants(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("list", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsApp.GetJID(gjid)) }, child);
this.SendNode(node);
}
public string SendGetPhoto(string jid, string expectedPhotoId, bool largeFormat)
{
string id = TicketCounter.MakeId();
var attrList = new List<KeyValue>();
if (!largeFormat)
{
attrList.Add(new KeyValue("type", "preview"));
}
if (expectedPhotoId != null)
{
attrList.Add(new KeyValue("id", expectedPhotoId));
}
var child = new ProtocolTreeNode("picture", attrList.ToArray());
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(jid)) }, child);
this.SendNode(node);
return id;
}
public void SendGetPhotoIds(IEnumerable<string> jids)
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(this.phoneNumber)) },
new ProtocolTreeNode("list", new[] { new KeyValue("xmlns", "w:profile:picture") },
(from jid in jids select new ProtocolTreeNode("user", new[] { new KeyValue("jid", jid) })).ToArray<ProtocolTreeNode>()));
this.SendNode(node);
}
public void SendGetPrivacyList()
{
string id = TicketCounter.MakeId();
var innerChild = new ProtocolTreeNode("list", new[] { new KeyValue("name", "default") });
var child = new ProtocolTreeNode("query", null, innerChild);
var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "jabber:iq:privacy") }, child);
this.SendNode(node);
}
public void SendGetServerProperties()
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w"), new KeyValue("to", "s.whatsapp.net") },
new ProtocolTreeNode("props", null));
this.SendNode(node);
}
public void SendGetStatuses(string[] jids)
{
List<ProtocolTreeNode> targets = new List<ProtocolTreeNode>();
foreach (string jid in jids)
{
targets.Add(new ProtocolTreeNode("user", new[] { new KeyValue("jid", GetJID(jid)) }, null, null));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("type", "get"),
new KeyValue("xmlns", "status"),
new KeyValue("id", TicketCounter.MakeId())
}, new[] {
new ProtocolTreeNode("status", null, targets.ToArray(), null)
}, null);
this.SendNode(node);
}
public void SendInactive()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "inactive") });
this.SendNode(node);
}
public void SendLeaveGroup(string gjid)
{
this.SendLeaveGroups(new string[] { gjid });
}
public void SendLeaveGroups(IEnumerable<string> gjids)
{
string id = TicketCounter.MakeId();
IEnumerable<ProtocolTreeNode> innerChilds = from gjid in gjids select new ProtocolTreeNode("group", new[] { new KeyValue("id", gjid) });
var child = new ProtocolTreeNode("leave", null, innerChilds);
var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child);
this.SendNode(node);
}
public void SendMessage(FMessage message, bool hidden = false)
{
if (message.media_wa_type != FMessage.Type.Undefined)
{
this.SendMessageWithMedia(message);
}
else
{
this.SendMessageWithBody(message, hidden);
}
}
public void SendMessageBroadcast(string[] to, string message)
{
this.SendMessageBroadcast(to, new FMessage(string.Empty, true) { data = message, media_wa_type = FMessage.Type.Undefined });
}
public void SendMessageBroadcastImage(string[] recipients, byte[] ImageData, ImageType imgtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageImage(to, ImageData, imgtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcastAudio(string[] recipients, byte[] AudioData, AudioType audtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageAudio(to, AudioData, audtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcastVideo(string[] recipients, byte[] VideoData, VideoType vidtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageVideo(to, VideoData, vidtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcast(string[] to, FMessage message)
{
if (to != null && to.Length > 0 && message != null && !string.IsNullOrEmpty(message.data))
{
ProtocolTreeNode child;
if (message.media_wa_type == FMessage.Type.Undefined)
{
//text broadcast
child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
}
else
{
throw new NotImplementedException();
}
List<ProtocolTreeNode> toNodes = new List<ProtocolTreeNode>();
foreach (string target in to)
{
toNodes.Add(new ProtocolTreeNode("to", new KeyValue[] { new KeyValue("jid", WhatsAppApi.WhatsApp.GetJID(target)) }));
}
ProtocolTreeNode broadcastNode = new ProtocolTreeNode("broadcast", null, toNodes);
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
ProtocolTreeNode messageNode = new ProtocolTreeNode("message", new KeyValue[] {
new KeyValue("to", unixTimestamp.ToString() + "@broadcast"),
new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"),
new KeyValue("id", message.identifier_key.id)
}, new ProtocolTreeNode[] {
broadcastNode,
child
});
this.SendNode(messageNode);
}
}
public void SendNop()
{
this.SendNode(null);
}
public void SendPaused(string to)
{
this.SendChatState(to, "paused");
}
public void SendPing()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("ping", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("xmlns", "w:p"), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, child);
this.SendNode(node);
}
public void SendPresenceSubscriptionRequest(string to)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "subscribe"), new KeyValue("to", GetJID(to)) });
this.SendNode(node);
}
public void SendQueryLastOnline(string jid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("query", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(jid)), new KeyValue("xmlns", "jabber:iq:last") }, child);
this.SendNode(node);
}
public void SendRemoveParticipants(string gjid, List<string> participants)
{
string id = TicketCounter.MakeId();
this.SendVerbParticipants(gjid, participants, id, "remove");
}
public void SendSetGroupSubject(string gjid, string subject)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("subject", new[] { new KeyValue("value", subject) });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, child);
this.SendNode(node);
}
public void SendSetPhoto(string jid, byte[] bytes, byte[] thumbnailBytes = null)
{
string id = TicketCounter.MakeId();
bytes = this.ProcessProfilePicture(bytes);
var list = new List<ProtocolTreeNode> { new ProtocolTreeNode("picture", null, null, bytes) };
if (thumbnailBytes == null)
{
//auto generate
thumbnailBytes = this.CreateThumbnail(bytes);
}
//debug
System.IO.File.WriteAllBytes("pic.jpg", bytes);
System.IO.File.WriteAllBytes("picthumb.jpg", thumbnailBytes);
if (thumbnailBytes != null)
{
list.Add(new ProtocolTreeNode("picture", new[] { new KeyValue("type", "preview") }, null, thumbnailBytes));
}
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", GetJID(jid)) }, list.ToArray());
this.SendNode(node);
}
public void SendSetPrivacyBlockedList(IEnumerable<string> jidSet)
{
string id = TicketCounter.MakeId();
ProtocolTreeNode[] nodeArray = Enumerable.Select<string, ProtocolTreeNode>(jidSet, (Func<string, int, ProtocolTreeNode>)((jid, index) => new ProtocolTreeNode("item", new KeyValue[] { new KeyValue("type", "jid"), new KeyValue("value", jid), new KeyValue("action", "deny"), new KeyValue("order", index.ToString(CultureInfo.InvariantCulture)) }))).ToArray<ProtocolTreeNode>();
var child = new ProtocolTreeNode("list", new KeyValue[] { new KeyValue("name", "default") }, (nodeArray.Length == 0) ? null : nodeArray);
var node2 = new ProtocolTreeNode("query", null, child);
var node3 = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "jabber:iq:privacy") }, node2);
this.SendNode(node3);
}
public void SendStatusUpdate(string status)
{
string id = TicketCounter.MakeId();
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("type", "set"),
new KeyValue("id", id),
new KeyValue("xmlns", "status")
},
new [] {
new ProtocolTreeNode("status", null, System.Text.Encoding.UTF8.GetBytes(status))
});
this.SendNode(node);
}
public void SendSubjectReceived(string to, string id)
{
var child = new ProtocolTreeNode("received", new[] { new KeyValue("xmlns", "urn:xmpp:receipts") });
var node = GetSubjectMessage(to, id, child);
this.SendNode(node);
}
public void SendUnsubscribeHim(string jid)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribed"), new KeyValue("to", jid) });
this.SendNode(node);
}
public void SendUnsubscribeMe(string jid)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribe"), new KeyValue("to", jid) });
this.SendNode(node);
}
public void SendGetGroups(string id, string type)
{
var child = new ProtocolTreeNode("list", new[] { new KeyValue("type", type) });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child);
this.SendNode(node);
}
protected void SendMessageWithBody(FMessage message, bool hidden = false)
{
var child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
this.SendNode(GetMessageNode(message, child, hidden));
}
protected void SendMessageWithMedia(FMessage message)
{
ProtocolTreeNode node;
if (FMessage.Type.System == message.media_wa_type)
{
throw new SystemException("Cannot send system message over the network");
}
List<KeyValue> list = new List<KeyValue>(new KeyValue[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:mms"), new KeyValue("type", FMessage.GetMessage_WA_Type_StrValue(message.media_wa_type)) });
if (FMessage.Type.Location == message.media_wa_type)
{
list.AddRange(new KeyValue[] { new KeyValue("latitude", message.latitude.ToString(CultureInfo.InvariantCulture)), new KeyValue("longitude", message.longitude.ToString(CultureInfo.InvariantCulture)) });
if (message.location_details != null)
{
list.Add(new KeyValue("name", message.location_details));
}
if (message.location_url != null)
{
list.Add(new KeyValue("url", message.location_url));
}
}
else if (((FMessage.Type.Contact != message.media_wa_type) && (message.media_name != null)) && ((message.media_url != null) && (message.media_size > 0L)))
{
list.AddRange(new KeyValue[] { new KeyValue("file", message.media_name), new KeyValue("size", message.media_size.ToString(CultureInfo.InvariantCulture)), new KeyValue("url", message.media_url) });
if (message.media_duration_seconds > 0)
{
list.Add(new KeyValue("seconds", message.media_duration_seconds.ToString(CultureInfo.InvariantCulture)));
}
}
if ((FMessage.Type.Contact == message.media_wa_type) && (message.media_name != null))
{
node = new ProtocolTreeNode("media", list.ToArray(), new ProtocolTreeNode("vcard", new KeyValue[] { new KeyValue("name", message.media_name) }, WhatsApp.SYSEncoding.GetBytes(message.data)));
}
else
{
byte[] data = message.binary_data;
if ((data == null) && !string.IsNullOrEmpty(message.data))
{
try
{
data = Convert.FromBase64String(message.data);
}
catch (Exception)
{
}
}
if (data != null)
{
list.Add(new KeyValue("encoding", "raw"));
}
node = new ProtocolTreeNode("media", list.ToArray(), null, data);
}
this.SendNode(GetMessageNode(message, node));
}
protected void SendVerbParticipants(string gjid, IEnumerable<string> participants, string id, string inner_tag)
{
IEnumerable<ProtocolTreeNode> source = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) });
var child = new ProtocolTreeNode(inner_tag, null, source);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", GetJID(gjid)) }, child);
this.SendNode(node);
}
public void SendSetPrivacySetting(VisibilityCategory category, VisibilitySetting setting)
{
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("type", "set"),
new KeyValue("xmlns", "privacy")
}, new ProtocolTreeNode[] {
new ProtocolTreeNode("privacy", null, new ProtocolTreeNode[] {
new ProtocolTreeNode("category", new [] {
new KeyValue("name", this.privacyCategoryToString(category)),
new KeyValue("value", this.privacySettingToString(setting))
})
})
});
this.SendNode(node);
}
public void SendGetPrivacySettings()
{
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("type", "get"),
new KeyValue("xmlns", "privacy")
}, new ProtocolTreeNode[] {
new ProtocolTreeNode("privacy", null)
});
this.SendNode(node);
}
protected IEnumerable<ProtocolTreeNode> ProcessGroupSettings(IEnumerable<GroupSetting> groups)
{
ProtocolTreeNode[] nodeArray = null;
if ((groups != null) && groups.Any<GroupSetting>())
{
DateTime now = DateTime.Now;
nodeArray = (from @group in groups
select new ProtocolTreeNode("item", new[]
{ new KeyValue("jid", @group.Jid),
new KeyValue("notify", @group.Enabled ? "1" : "0"),
new KeyValue("mute", string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", new object[] { (!@group.MuteExpiry.HasValue || (@group.MuteExpiry.Value <= now)) ? 0 : ((int) (@group.MuteExpiry.Value - now).TotalSeconds) })) })).ToArray<ProtocolTreeNode>();
}
return nodeArray;
}
protected static ProtocolTreeNode GetMessageNode(FMessage message, ProtocolTreeNode pNode, bool hidden = false)
{
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
return new ProtocolTreeNode("message", new[] {
new KeyValue("to", message.identifier_key.remote_jid),
new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"),
new KeyValue("id", message.identifier_key.id),
new KeyValue("t",unixTimestamp.ToString())
},
new ProtocolTreeNode[] {
pNode
});
}
protected static ProtocolTreeNode GetSubjectMessage(string to, string id, ProtocolTreeNode child)
{
return new ProtocolTreeNode("message", new[] { new KeyValue("to", to), new KeyValue("type", "subject"), new KeyValue("id", id) }, child);
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient
{
internal sealed partial class SqlConnectionString : DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal static partial class DEFAULT
{
internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent;
internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME;
internal const string AttachDBFilename = "";
internal const int Connect_Timeout = ADP.DefaultConnectionTimeout;
internal const string Current_Language = "";
internal const string Data_Source = "";
internal const bool Encrypt = false;
internal const bool Enlist = true;
internal const string FailoverPartner = "";
internal const string Initial_Catalog = "";
internal const bool Integrated_Security = false;
internal const int Load_Balance_Timeout = 0; // default of 0 means don't use
internal const bool MARS = false;
internal const int Max_Pool_Size = 100;
internal const int Min_Pool_Size = 0;
internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
internal const int Packet_Size = 8000;
internal const string Password = "";
internal const bool Persist_Security_Info = false;
internal const bool Pooling = true;
internal const bool TrustServerCertificate = false;
internal const string Type_System_Version = "";
internal const string User_ID = "";
internal const bool User_Instance = false;
internal const bool Replication = false;
internal const int Connect_Retry_Count = 1;
internal const int Connect_Retry_Interval = 10;
}
// SqlConnection ConnectionString Options
// keys must be lowercase!
internal static class KEY
{
internal const string ApplicationIntent = "applicationintent";
internal const string Application_Name = "application name";
internal const string AsynchronousProcessing = "asynchronous processing";
internal const string AttachDBFilename = "attachdbfilename";
#if netcoreapp
internal const string PoolBlockingPeriod = "poolblockingperiod";
#endif
internal const string Connect_Timeout = "connect timeout";
internal const string Connection_Reset = "connection reset";
internal const string Context_Connection = "context connection";
internal const string Current_Language = "current language";
internal const string Data_Source = "data source";
internal const string Encrypt = "encrypt";
internal const string Enlist = "enlist";
internal const string FailoverPartner = "failover partner";
internal const string Initial_Catalog = "initial catalog";
internal const string Integrated_Security = "integrated security";
internal const string Load_Balance_Timeout = "load balance timeout";
internal const string MARS = "multipleactiveresultsets";
internal const string Max_Pool_Size = "max pool size";
internal const string Min_Pool_Size = "min pool size";
internal const string MultiSubnetFailover = "multisubnetfailover";
internal const string Network_Library = "network library";
internal const string Packet_Size = "packet size";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string Pooling = "pooling";
internal const string TransactionBinding = "transaction binding";
internal const string TrustServerCertificate = "trustservercertificate";
internal const string Type_System_Version = "type system version";
internal const string User_ID = "user id";
internal const string User_Instance = "user instance";
internal const string Workstation_Id = "workstation id";
internal const string Replication = "replication";
internal const string Connect_Retry_Count = "connectretrycount";
internal const string Connect_Retry_Interval = "connectretryinterval";
}
// Constant for the number of duplicate options in the connection string
private static class SYNONYM
{
// application name
internal const string APP = "app";
internal const string Async = "async";
// attachDBFilename
internal const string EXTENDED_PROPERTIES = "extended properties";
internal const string INITIAL_FILE_NAME = "initial file name";
// connect timeout
internal const string CONNECTION_TIMEOUT = "connection timeout";
internal const string TIMEOUT = "timeout";
// current language
internal const string LANGUAGE = "language";
// data source
internal const string ADDR = "addr";
internal const string ADDRESS = "address";
internal const string SERVER = "server";
internal const string NETWORK_ADDRESS = "network address";
// initial catalog
internal const string DATABASE = "database";
// integrated security
internal const string TRUSTED_CONNECTION = "trusted_connection";
// load balance timeout
internal const string Connection_Lifetime = "connection lifetime";
// network library
internal const string NET = "net";
internal const string NETWORK = "network";
// password
internal const string Pwd = "pwd";
// persist security info
internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
// user id
internal const string UID = "uid";
internal const string User = "user";
// workstation id
internal const string WSID = "wsid";
// make sure to update SynonymCount value below when adding or removing synonyms
}
internal const int SynonymCount = 18;
internal const int DeprecatedSynonymCount = 3;
internal enum TypeSystem
{
Latest = 2008,
SQLServer2000 = 2000,
SQLServer2005 = 2005,
SQLServer2008 = 2008,
SQLServer2012 = 2012,
}
internal static class TYPESYSTEMVERSION
{
internal const string Latest = "Latest";
internal const string SQL_Server_2000 = "SQL Server 2000";
internal const string SQL_Server_2005 = "SQL Server 2005";
internal const string SQL_Server_2008 = "SQL Server 2008";
internal const string SQL_Server_2012 = "SQL Server 2012";
}
internal enum TransactionBindingEnum
{
ImplicitUnbind,
ExplicitUnbind
}
internal static class TRANSACTIONBINDING
{
internal const string ImplicitUnbind = "Implicit Unbind";
internal const string ExplicitUnbind = "Explicit Unbind";
}
private static Dictionary<string, string> s_sqlClientSynonyms;
private readonly bool _integratedSecurity;
private readonly bool _encrypt;
private readonly bool _trustServerCertificate;
private readonly bool _enlist;
private readonly bool _mars;
private readonly bool _persistSecurityInfo;
private readonly bool _pooling;
private readonly bool _replication;
private readonly bool _userInstance;
private readonly bool _multiSubnetFailover;
private readonly int _connectTimeout;
private readonly int _loadBalanceTimeout;
private readonly int _maxPoolSize;
private readonly int _minPoolSize;
private readonly int _packetSize;
private readonly int _connectRetryCount;
private readonly int _connectRetryInterval;
private readonly ApplicationIntent _applicationIntent;
private readonly string _applicationName;
private readonly string _attachDBFileName;
private readonly string _currentLanguage;
private readonly string _dataSource;
private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB
private readonly string _failoverPartner;
private readonly string _initialCatalog;
private readonly string _password;
private readonly string _userID;
private readonly string _workstationId;
private readonly TransactionBindingEnum _transactionBinding;
private readonly TypeSystem _typeSystemVersion;
private readonly Version _typeSystemAssemblyVersion;
private static readonly Version constTypeSystemAsmVersion10 = new Version("10.0.0.0");
private static readonly Version constTypeSystemAsmVersion11 = new Version("11.0.0.0");
internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
{
ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
// Network Library has its own special error message
if (ContainsKey(KEY.Network_Library))
{
throw SQL.NetworkLibraryKeywordNotSupported();
}
_integratedSecurity = ConvertValueToIntegratedSecurity();
#if netcoreapp
_poolBlockingPeriod = ConvertValueToPoolBlockingPeriod();
#endif
_encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
_enlist = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist);
_mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
_persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
_pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
_replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
_userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
_multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);
_connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
_loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
_maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
_minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
_packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
_connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
_connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);
_applicationIntent = ConvertValueToApplicationIntent();
_applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
_attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
_currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
_dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
_initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
_password = ConvertValueToString(KEY.Password, DEFAULT.Password);
_trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);
// Temporary string - this value is stored internally as an enum.
string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);
_userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
_workstationId = ConvertValueToString(KEY.Workstation_Id, null);
if (_loadBalanceTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
}
if (_connectTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
}
if (_maxPoolSize < 1)
{
throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
}
if (_minPoolSize < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
}
if (_maxPoolSize < _minPoolSize)
{
throw ADP.InvalidMinMaxPoolSizeValues();
}
if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
{
throw SQL.InvalidPacketSizeValue();
}
ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
if (null != _workstationId)
{
ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
}
if (!string.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
{
// fail-over partner is set
if (_multiSubnetFailover)
{
throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
}
if (string.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
{
throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
}
}
// string.Contains(char) is .NetCore2.1+ specific
if (0 <= _attachDBFileName.IndexOf('|'))
{
throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
}
else
{
ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
}
_typeSystemAssemblyVersion = constTypeSystemAsmVersion10;
if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
{
throw SQL.UserInstanceFailoverNotCompatible();
}
if (string.IsNullOrEmpty(typeSystemVersionString))
{
typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
}
if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.Latest;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2000;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2005;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2008;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2012;
_typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
}
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
}
if (string.IsNullOrEmpty(transactionBindingString))
{
transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
}
if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
{
_transactionBinding = TransactionBindingEnum.ImplicitUnbind;
}
else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
{
_transactionBinding = TransactionBindingEnum.ExplicitUnbind;
}
else
{
throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
}
if (_applicationIntent == ApplicationIntent.ReadOnly && !string.IsNullOrEmpty(_failoverPartner))
throw SQL.ROR_FailoverNotSupportedConnString();
if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
{
throw ADP.InvalidConnectRetryCountValue();
}
if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
{
throw ADP.InvalidConnectRetryIntervalValue();
}
}
// This c-tor is used to create SSE and user instance connection strings when user instance is set to true
// BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message
internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions)
{
_integratedSecurity = connectionOptions._integratedSecurity;
_encrypt = connectionOptions._encrypt;
if (setEnlistValue.HasValue)
{
_enlist = setEnlistValue.Value;
}
else
{
_enlist = connectionOptions._enlist;
}
_mars = connectionOptions._mars;
_persistSecurityInfo = connectionOptions._persistSecurityInfo;
_pooling = connectionOptions._pooling;
_replication = connectionOptions._replication;
_userInstance = userInstance;
_connectTimeout = connectionOptions._connectTimeout;
_loadBalanceTimeout = connectionOptions._loadBalanceTimeout;
#if netcoreapp
_poolBlockingPeriod = connectionOptions._poolBlockingPeriod;
#endif
_maxPoolSize = connectionOptions._maxPoolSize;
_minPoolSize = connectionOptions._minPoolSize;
_multiSubnetFailover = connectionOptions._multiSubnetFailover;
_packetSize = connectionOptions._packetSize;
_applicationName = connectionOptions._applicationName;
_attachDBFileName = connectionOptions._attachDBFileName;
_currentLanguage = connectionOptions._currentLanguage;
_dataSource = dataSource;
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = connectionOptions._failoverPartner;
_initialCatalog = connectionOptions._initialCatalog;
_password = connectionOptions._password;
_userID = connectionOptions._userID;
_workstationId = connectionOptions._workstationId;
_typeSystemVersion = connectionOptions._typeSystemVersion;
_transactionBinding = connectionOptions._transactionBinding;
_applicationIntent = connectionOptions._applicationIntent;
_connectRetryCount = connectionOptions._connectRetryCount;
_connectRetryInterval = connectionOptions._connectRetryInterval;
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
}
internal bool IntegratedSecurity { get { return _integratedSecurity; } }
// We always initialize in Async mode so that both synchronous and asynchronous methods
// will work. In the future we can deprecate the keyword entirely.
internal bool Asynchronous { get { return true; } }
// SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security
internal bool ConnectionReset { get { return true; } }
// internal bool EnableUdtDownload { get { return _enableUdtDownload;} }
internal bool Encrypt { get { return _encrypt; } }
internal bool TrustServerCertificate { get { return _trustServerCertificate; } }
internal bool Enlist { get { return _enlist; } }
internal bool MARS { get { return _mars; } }
internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } }
internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } }
internal bool Pooling { get { return _pooling; } }
internal bool Replication { get { return _replication; } }
internal bool UserInstance { get { return _userInstance; } }
internal int ConnectTimeout { get { return _connectTimeout; } }
internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } }
internal int MaxPoolSize { get { return _maxPoolSize; } }
internal int MinPoolSize { get { return _minPoolSize; } }
internal int PacketSize { get { return _packetSize; } }
internal int ConnectRetryCount { get { return _connectRetryCount; } }
internal int ConnectRetryInterval { get { return _connectRetryInterval; } }
internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } }
internal string ApplicationName { get { return _applicationName; } }
internal string AttachDBFilename { get { return _attachDBFileName; } }
internal string CurrentLanguage { get { return _currentLanguage; } }
internal string DataSource { get { return _dataSource; } }
internal string LocalDBInstance { get { return _localDBInstance; } }
internal string FailoverPartner { get { return _failoverPartner; } }
internal string InitialCatalog { get { return _initialCatalog; } }
internal string Password { get { return _password; } }
internal string UserID { get { return _userID; } }
internal string WorkstationId { get { return _workstationId; } }
internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } }
internal Version TypeSystemAssemblyVersion { get { return _typeSystemAssemblyVersion; } }
internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } }
// This dictionary is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string.
internal static Dictionary<string, string> GetParseSynonyms()
{
Dictionary<string, string> synonyms = s_sqlClientSynonyms;
if (null == synonyms)
{
int count = SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount;
synonyms = new Dictionary<string, string>(count)
{
{ KEY.ApplicationIntent, KEY.ApplicationIntent },
{ KEY.Application_Name, KEY.Application_Name },
{ KEY.AsynchronousProcessing, KEY.AsynchronousProcessing },
{ KEY.AttachDBFilename, KEY.AttachDBFilename },
#if netcoreapp
{ KEY.PoolBlockingPeriod, KEY.PoolBlockingPeriod},
#endif
{ KEY.Connect_Timeout, KEY.Connect_Timeout },
{ KEY.Connection_Reset, KEY.Connection_Reset },
{ KEY.Context_Connection, KEY.Context_Connection },
{ KEY.Current_Language, KEY.Current_Language },
{ KEY.Data_Source, KEY.Data_Source },
{ KEY.Encrypt, KEY.Encrypt },
{ KEY.Enlist, KEY.Enlist },
{ KEY.FailoverPartner, KEY.FailoverPartner },
{ KEY.Initial_Catalog, KEY.Initial_Catalog },
{ KEY.Integrated_Security, KEY.Integrated_Security },
{ KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout },
{ KEY.MARS, KEY.MARS },
{ KEY.Max_Pool_Size, KEY.Max_Pool_Size },
{ KEY.Min_Pool_Size, KEY.Min_Pool_Size },
{ KEY.MultiSubnetFailover, KEY.MultiSubnetFailover },
{ KEY.Network_Library, KEY.Network_Library },
{ KEY.Packet_Size, KEY.Packet_Size },
{ KEY.Password, KEY.Password },
{ KEY.Persist_Security_Info, KEY.Persist_Security_Info },
{ KEY.Pooling, KEY.Pooling },
{ KEY.Replication, KEY.Replication },
{ KEY.TrustServerCertificate, KEY.TrustServerCertificate },
{ KEY.TransactionBinding, KEY.TransactionBinding },
{ KEY.Type_System_Version, KEY.Type_System_Version },
{ KEY.User_ID, KEY.User_ID },
{ KEY.User_Instance, KEY.User_Instance },
{ KEY.Workstation_Id, KEY.Workstation_Id },
{ KEY.Connect_Retry_Count, KEY.Connect_Retry_Count },
{ KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval },
{ SYNONYM.APP, KEY.Application_Name },
{ SYNONYM.Async, KEY.AsynchronousProcessing },
{ SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename },
{ SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename },
{ SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout },
{ SYNONYM.TIMEOUT, KEY.Connect_Timeout },
{ SYNONYM.LANGUAGE, KEY.Current_Language },
{ SYNONYM.ADDR, KEY.Data_Source },
{ SYNONYM.ADDRESS, KEY.Data_Source },
{ SYNONYM.NETWORK_ADDRESS, KEY.Data_Source },
{ SYNONYM.SERVER, KEY.Data_Source },
{ SYNONYM.DATABASE, KEY.Initial_Catalog },
{ SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security },
{ SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout },
{ SYNONYM.NET, KEY.Network_Library },
{ SYNONYM.NETWORK, KEY.Network_Library },
{ SYNONYM.Pwd, KEY.Password },
{ SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info },
{ SYNONYM.UID, KEY.User_ID },
{ SYNONYM.User, KEY.User_ID },
{ SYNONYM.WSID, KEY.Workstation_Id }
};
Debug.Assert(synonyms.Count == count, "incorrect initial ParseSynonyms size");
Interlocked.CompareExchange(ref s_sqlClientSynonyms, synonyms, null);
}
return synonyms;
}
internal string ObtainWorkstationId()
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
string result = WorkstationId;
if (null == result)
{
// permission to obtain Environment.MachineName is Asserted
// since permission to open the connection has been granted
// the information is shared with the server, but not directly with the user
result = ADP.MachineName();
ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
}
return result;
}
private void ValidateValueLength(string value, int limit, string key)
{
if (limit < value.Length)
{
throw ADP.InvalidConnectionOptionValueLength(key, limit);
}
}
internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent()
{
string value;
if (!TryGetParsetableValue(KEY.ApplicationIntent, out value))
{
return DEFAULT.ApplicationIntent;
}
// when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor,
// wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool)
try
{
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
// ArgumentException and other types are raised as is (no wrapping)
}
internal void ThrowUnsupportedIfKeywordSet(string keyword)
{
if (ContainsKey(keyword))
{
throw SQL.UnsupportedKeyword(keyword);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
namespace l2pvp
{
public partial class Defense : Form
{
Client c;
GameServer gs;
public Defense(Client _c, GameServer _gs)
{
InitializeComponent();
c = _c;
gs = _gs;
condition.Items.Add("Always");
condition.Items.Add("HP");
condition.Items.Add("Distance");
compare.Items.Add("=");
compare.Items.Add(">");
compare.Items.Add("<");
Effects sleep, hold, medusa, poison;
medusa = new Effects();
medusa.name = "Medusa";
medusa.id = 2048;
sleep = new Effects();
sleep.name = "Sleep";
sleep.id = 128;
hold = new Effects();
hold.name = "Root";
hold.id = 512;
poison = new Effects();
poison.name = "Poison";
poison.id = 2;
eff.Items.Add(medusa);
eff.Items.Add(sleep);
eff.Items.Add(hold);
eff.Items.Add(poison);
condition.SelectedIndex = 0;
compare.SelectedIndex = 0;
value.Text = "0";
eff.SelectedIndex = 0;
tb_mp.Text = "1500";
}
private void button1_Click(object sender, EventArgs e)
{
//add to listview
Effects thisEffect = new Effects();
DefenseSkills askill = new DefenseSkills();
askill.comparison = compare.SelectedIndex;
askill.condition = condition.SelectedIndex;
askill.skillname = sl.Items[sl.SelectedIndex].ToString();
askill.skillid = ((skill)sl.Items[sl.SelectedIndex]).id;
try
{
askill.value = Convert.ToInt32(value.Text);
}
catch
{
askill.value = 0;
}
thisEffect = ((Effects)eff.SelectedItem);
askill.effect = thisEffect.id;
try
{
askill.MP = Convert.ToUInt32(tb_mp.Text);
}
catch
{
askill.MP = 1500;
}
ListViewItem item = new ListViewItem(askill.skillname);
item.SubItems.Add(condition.Items[askill.condition].ToString());
item.SubItems.Add(compare.Items[askill.comparison].ToString());
item.SubItems.Add(askill.value.ToString());
item.SubItems.Add(thisEffect.name);
item.SubItems.Add(askill.MP.ToString());
item.Tag = askill;
listView1.Items.Add(item);
}
private void button3_Click(object sender, EventArgs e)
{
lock (c.dslock)
{
c.dskills.Clear();
foreach (ListViewItem item in listView1.Items)
{
c.dskills.Add((DefenseSkills)item.Tag);
}
}
this.Hide();
}
private void button4_Click(object sender, EventArgs e)
{
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection ic = listView1.SelectedItems;
foreach (ListViewItem i in ic)
{
listView1.Items.Remove(i);
}
}
private void button5_Click(object sender, EventArgs e)
{
string fname = textBox2.Text;
fname = "defend-" + fname;
StreamReader readfile;
try
{
readfile = new StreamReader(new FileStream(fname, FileMode.Open), Encoding.UTF8);
if (readfile == null)
return;
}
catch
{
MessageBox.Show("couldn't open file {0} for reading", fname);
return;
}
string line;
int count;
line = readfile.ReadLine();
try
{
count = Convert.ToInt32(line);
}
catch
{
count = 0;
}
listView1.Items.Clear();
for (int i = 0; i < count; i++)
{
try
{
line = readfile.ReadLine();
string[] items = line.Split(',');
DefenseSkills askill = new DefenseSkills();
askill.skillid = Convert.ToUInt32(items[0]);
askill.condition = Convert.ToInt32(items[1]);
askill.comparison = Convert.ToInt32(items[2]);
askill.value = Convert.ToInt32(items[3]);
askill.skillname = gs.skills[askill.skillid];
askill.effect = Convert.ToUInt32(items[4]);
askill.MP = Convert.ToUInt32(items[5]);
ListViewItem item = new ListViewItem(askill.skillname);
item.SubItems.Add(condition.Items[askill.condition].ToString());
item.SubItems.Add(compare.Items[askill.comparison].ToString());
item.SubItems.Add(askill.value.ToString());
item.SubItems.Add(askill.MP.ToString());
foreach (object o in eff.Items)
{
Effects neweffect = (Effects)o;
if (neweffect.id == askill.effect)
{
//found it
item.SubItems.Add(neweffect.name);
}
}
item.Tag = askill;
listView1.Items.Add(item);
}
catch
{
}
}
}
private void button6_Click(object sender, EventArgs e)
{
//file format
//Count
//<skill id> <condition id> <comparison id> <value>
string fname = textBox2.Text;
fname = "defend-" + fname;
StreamWriter writefile = new StreamWriter(new FileStream(fname, FileMode.Create), Encoding.UTF8);
int count = listView1.Items.Count;
writefile.WriteLine(count.ToString());
foreach (ListViewItem i in listView1.Items)
{
DefenseSkills a = (DefenseSkills)i.Tag;
writefile.WriteLine("{0},{1},{2},{3},{4},{5}",
a.skillid, a.condition, a.comparison, a.value,a.effect, a.MP);
}
writefile.Flush();
writefile.Close();
}
public void populateskilllist_d(List<uint> skilllist)
{
if (this.InvokeRequired)
Invoke(new poplist(populateskilllist), new object[] { skilllist });
else
populateskilllist(skilllist);
}
public delegate void poplist(List<uint> skilllist);
public void populateskilllist(List<uint> skilllist)
{
sl.Items.Clear();
string skillname;
foreach (uint i in skilllist)
{
if (gs.skills.ContainsKey(i))
{
skillname = gs.skills[i];
if (skillname != null)
{
//found skill
skill s = new skill();
s.name = skillname;
s.id = i;
sl.Items.Add(s);
}
}
}
}
}
public class Effects
{
public string name;
public uint id;
public override string ToString()
{
return name;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CPUBus = Cosmos.Core_Plugs.IOPortImpl;
using Cosmos.Core;
using GuessKernel;
//using Cosmos.Kernel;
namespace Cosmos.Hardware
{
/// <summary>
/// This class describes the mouse.
/// </summary>
public class Mouse
{
private Cosmos.Core.IOGroup.Mouse g = new Core.IOGroup.Mouse();
/// <summary>
/// The X location of the mouse.
/// </summary>
public uint X;
/// <summary>
/// The Y location of the mouse.
/// </summary>
public uint Y;
/// <summary>
/// The state the mouse is currently in.
/// </summary>
public MouseState Buttons;
/// <summary>
/// This is the required call to start
/// the mouse receiving interrupts.
/// </summary>
public void Initialize()
{
Cosmos.Core_Plugs.IOPortImpl.Read8(0X60);
g.p60.Byte = 0x20;
byte statusByte = Read();
byte modstatusByte = (byte)(((statusByte >> 2) << 1) + 1); // Enable status byte 2
byte final = (byte)(((modstatusByte >> 5) << 1) + ((modstatusByte << 4) >> 4)); // Disable status byte 5
g.p60.Byte = 0x60;
Write(final);
//Enable the auxiliary mouse device
WaitSignal();
g.p64.Byte = 0xA8;
//Tell the mouse to use default settings
Write(0xF6);
Read(); //Acknowledge
//Set Remote Mode
Write(0xF0);
Read(); //Acknowledge
////Enable the auxiliary mouse device
//WaitSignal();
//g.p64.Byte = 0xA8;
////// enable interrupt
//WaitSignal();
//g.p64.Byte = 0x20;
//WaitData();
//byte tmpst = g.p60.Byte;
//tmpst = (byte)(((tmpst >> 2) << 1) + 1);
//byte status = (byte)(((tmpst >> 5) << 1) + ((byte)(tmpst << 4) >> 4));
////byte status = (byte)(g.p60.Byte | 2);
//WaitSignal();
//g.p64.Byte = 0x60;
//WaitSignal();
//g.p60.Byte = status;
////Tell the mouse to use default settings
//Write(0xF6);
//Read(); //Acknowledge
////Set Remote Mode
//Write(0xF0);
//Read(); //Acknowledge
}
private byte Read()
{
WaitData();
return g.p60.Byte;
}
private void Write(byte b)
{
//Wait to be able to send a command
WaitSignal();
//Tell the mouse we are sending a command
g.p64.Byte = 0xD4;
//Wait for the final part
WaitSignal();
//Finally write
g.p60.Byte = b;
}
public bool TimedOut = false;
public bool TimedOut2 = false;
public bool TimedOut3 = false;
public bool TimedOut4 = false;
public bool TimedOut5 = false;
private void WaitData()
{
for (int i = 0; i < 100000 && ((g.p64.Byte & 1) != 1); i++)
{
if (i == 99999)
{
if (!TimedOut)
TimedOut = true;
else if (!TimedOut2)
TimedOut2 = true;
else if (!TimedOut3)
TimedOut3 = true;
else if (!TimedOut4)
TimedOut3 = true;
else if (!TimedOut5)
TimedOut3 = true;
}
}
}
private void WaitSignal()
{
for (int i = 0; i < 100000 && ((g.p64.Byte & 2) != 0); i++)
{
}
}
/// <summary>
/// The possible states of a mouse.
/// </summary>
public enum MouseState
{
/// <summary>
/// No button is pressed.
/// </summary>
None = 0,
/// <summary>
/// The left mouse button is pressed.
/// </summary>
Left = 1,
/// <summary>
/// The right mouse button is pressed.
/// </summary>
Right = 2,
/// <summary>
/// The middle mouse button is pressed.
/// </summary>
Middle = 4
}
private byte[] mouse_byte = new byte[4];
public void HandleMouse()
{
Write(0xEB);
uint i = Read();
if (i != 0xFA) // this means it didn't respond with an acknowledge
{
if (i == 0xFE) // The mouse send back 'Resend'
TimedOut4 = true;
else
{
TimedOut3 = true;
}
}
else
{
TimedOut4 = false;
#region Read Bytes
mouse_byte[0] = Read();
mouse_byte[1] = Read();
mouse_byte[2] = Read();
#endregion
#region Process Bytes
X += mouse_byte[1];
Y += mouse_byte[2];
if (X < 0)
{
X = 0;
}
else if (X > 319)
{
X = 319;
}
if (Y < 0)
{
Y = 0;
}
else if (Y > 199)
{
Y = 199;
}
if ((mouse_byte[0] & 1) == 1)
{
Buttons = MouseState.Left;
}
else if ((mouse_byte[0] & 2) == 1)
{
Buttons = MouseState.Right;
}
else if ((mouse_byte[0] & 3) == 1)
{
Buttons = MouseState.Middle;
}
#endregion
//Console.WriteLine("X: " + X + " Y: " + Y);
if (GuessOS.MouseX != X || GuessOS.MouseY != Y)
{
GuessOS.MouseX = X;
GuessOS.MouseY = Y;
Cosmos.System.Global.Console.WriteLine("X: " + X + " Y: " + Y);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
using static Dynamic.Operator.Tests.TypeCommon;
namespace Dynamic.Operator.Tests
{
public class DivideEqualTypeTests
{
[Fact]
public static void Bool()
{
dynamic d = true;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
Assert.Throws<RuntimeBinderException>(() => d /= s_byte);
Assert.Throws<RuntimeBinderException>(() => d /= s_char);
Assert.Throws<RuntimeBinderException>(() => d /= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d /= s_double);
Assert.Throws<RuntimeBinderException>(() => d /= s_float);
Assert.Throws<RuntimeBinderException>(() => d /= s_int);
Assert.Throws<RuntimeBinderException>(() => d /= s_long);
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
Assert.Throws<RuntimeBinderException>(() => d /= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d /= s_short);
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
Assert.Throws<RuntimeBinderException>(() => d /= s_uint);
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d /= s_ushort);
}
[Fact]
public static void Byte()
{
dynamic d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (byte)1;
d /= s_byte;
d = (byte)1;
d /= s_char;
d = (byte)1;
d /= s_decimal;
d = (byte)1;
d /= s_double;
d = (byte)1;
d /= s_float;
d = (byte)1;
d /= s_int;
d = (byte)1;
d /= s_long;
d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = (byte)1;
d /= s_sbyte;
d = (byte)1;
d /= s_short;
d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (byte)1;
d /= s_uint;
d = (byte)1;
d /= s_ulong;
d = (byte)1;
d /= s_short;
}
[Fact]
public static void Char()
{
dynamic d = 'a';
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 'a';
d /= s_byte;
d = 'a';
d /= s_char;
d = 'a';
d /= s_decimal;
d = 'a';
d /= s_double;
d = 'a';
d /= s_float;
d = 'a';
d /= s_int;
d = 'a';
d /= s_long;
d = 'a';
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = 'a';
d /= s_sbyte;
d = 'a';
d /= s_short;
d = 'a';
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 'a';
d /= s_uint;
d = 'a';
d /= s_ulong;
d = 'a';
d /= s_ushort;
}
[Fact]
public static void Decimal()
{
dynamic d = 1m;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 1m;
d /= s_byte;
d = 1m;
d /= s_char;
d = 1m;
d /= s_decimal;
d = 1m;
Assert.Throws<RuntimeBinderException>(() => d /= s_double);
d = 1m;
Assert.Throws<RuntimeBinderException>(() => d /= s_float);
d = 1m;
d /= s_int;
d = 1m;
d /= s_long;
d = 1m;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = 1m;
d /= s_sbyte;
d = 1m;
d /= s_short;
d = 1m;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 1m;
d /= s_uint;
d = 1m;
d /= s_ulong;
d = 1m;
d /= s_ushort;
}
[Fact]
public static void Double()
{
dynamic d = 10.1d;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 10.1d;
d /= s_byte;
d = 10.1d;
d /= s_char;
d = 10.1d;
Assert.Throws<RuntimeBinderException>(() => d /= s_decimal);
d = 10.1d;
d /= s_double;
d = 10.1d;
d /= s_float;
d = 10.1d;
d /= s_int;
d = 10.1d;
d /= s_long;
d = 10.1d;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d /= s_sbyte;
d = 10.1d;
d /= s_short;
d = 10.1d;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 10.1d;
d /= s_uint;
d = 10.1d;
d /= s_ulong;
d = 10.1d;
d /= s_ushort;
}
[Fact]
public static void Float()
{
dynamic d = 10.1f;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 10.1f;
d /= s_byte;
d = 10.1f;
d /= s_char;
d = 10.1f;
Assert.Throws<RuntimeBinderException>(() => d /= s_decimal);
d = 10.1f;
d /= s_double;
d = 10.1f;
d /= s_float;
d = 10.1f;
d /= s_int;
d = 10.1f;
d /= s_long;
d = 10.1f;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = 10.1f;
d /= s_sbyte;
d = 10.1f;
d /= s_short;
d = 10.1f;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 10.1f;
d /= s_uint;
d = 10.1f;
d /= s_ulong;
d = 10.1f;
d /= s_ushort;
}
[Fact]
public static void Int()
{
dynamic d = 10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 10;
d /= s_byte;
d = 10;
d /= s_char;
d = 10;
d /= s_decimal;
d = 10;
d /= s_double;
d = 10;
d /= s_float;
d = 10;
d /= s_int;
d = 10;
d /= s_long;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = 10;
d /= s_sbyte;
d = 10;
d /= s_short;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 10;
d /= s_uint;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
d = 10;
d /= s_ushort;
}
[Fact]
public static void Long()
{
dynamic d = 10L;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = 10L;
d /= s_byte;
d = 10L;
d /= s_char;
d = 10L;
d /= s_decimal;
d = 10L;
d /= s_double;
d = 10L;
d /= s_float;
d = 10L;
d /= s_int;
d = 10L;
d /= s_long;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = 10L;
d /= s_sbyte;
d = 10L;
d /= s_short;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = 10L;
d /= s_uint;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
d = 10L;
d /= s_ushort;
}
[Fact]
public static void Object()
{
dynamic d = new object();
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
Assert.Throws<RuntimeBinderException>(() => d /= s_byte);
Assert.Throws<RuntimeBinderException>(() => d /= s_char);
Assert.Throws<RuntimeBinderException>(() => d /= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d /= s_double);
Assert.Throws<RuntimeBinderException>(() => d /= s_float);
Assert.Throws<RuntimeBinderException>(() => d /= s_int);
Assert.Throws<RuntimeBinderException>(() => d /= s_long);
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
Assert.Throws<RuntimeBinderException>(() => d /= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d /= s_short);
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
Assert.Throws<RuntimeBinderException>(() => d /= s_uint);
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d /= s_ushort);
}
[Fact]
public static void SByte()
{
dynamic d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (sbyte)10;
d /= s_byte;
d = (sbyte)10;
d /= s_char;
d = (sbyte)10;
d /= s_decimal;
d = (sbyte)10;
d /= s_double;
d = (sbyte)10;
d /= s_float;
d = (sbyte)10;
d /= s_int;
d = (sbyte)10;
d /= s_long;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = (sbyte)10;
d /= s_sbyte;
d = (sbyte)10;
d /= s_short;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (sbyte)10;
d /= s_uint;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
d = (sbyte)10;
d /= s_ushort;
}
[Fact]
public static void Short()
{
dynamic d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (short)10;
d /= s_byte;
d = (short)10;
d /= s_char;
d = (short)10;
d /= s_decimal;
d = (short)10;
d /= s_double;
d = (short)10;
d /= s_float;
d = (short)10;
d /= s_int;
d = (short)10;
d /= s_long;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = (short)10;
d /= s_sbyte;
d = (short)10;
d /= s_short;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (short)10;
d /= s_uint;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d / s_ulong);
d = (short)10;
d /= s_ushort;
}
[Fact]
public static void String()
{
dynamic d = "abc";
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
Assert.Throws<RuntimeBinderException>(() => d /= s_byte);
Assert.Throws<RuntimeBinderException>(() => d /= s_char);
Assert.Throws<RuntimeBinderException>(() => d /= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d /= s_double);
Assert.Throws<RuntimeBinderException>(() => d /= s_float);
Assert.Throws<RuntimeBinderException>(() => d /= s_int);
Assert.Throws<RuntimeBinderException>(() => d /= s_long);
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
Assert.Throws<RuntimeBinderException>(() => d /= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d /= s_short);
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
Assert.Throws<RuntimeBinderException>(() => d /= s_uint);
Assert.Throws<RuntimeBinderException>(() => d /= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d /= s_ushort);
}
[Fact]
public static void UInt()
{
dynamic d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (uint)10;
d /= s_byte;
d = (uint)10;
d /= s_char;
d = (uint)10;
d /= s_decimal;
d = (uint)10;
d /= s_double;
d = (uint)10;
d /= s_float;
d = (uint)10;
d /= s_int;
d = (uint)10;
d /= s_long;
d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = (uint)10;
d /= s_sbyte;
d = (uint)10;
d /= s_short;
d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (uint)10;
d /= s_uint;
d = (uint)10;
d /= s_ulong;
d = (uint)10;
d /= s_ushort;
}
[Fact]
public static void ULong()
{
dynamic d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (ulong)10;
d /= s_byte;
d = (ulong)10;
d /= s_char;
d = (ulong)10;
d /= s_decimal;
d = (ulong)10;
d /= s_double;
d = (ulong)10;
d /= s_float;
d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_int);
Assert.Throws<RuntimeBinderException>(() => d / s_long);
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
Assert.Throws<RuntimeBinderException>(() => d /= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d /= s_short);
d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (ulong)10;
d /= s_uint;
d = (ulong)10;
d /= s_ulong;
d = (ulong)10;
d /= s_ushort;
}
[Fact]
public static void UShort()
{
dynamic d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_bool);
d = (ushort)10;
d /= s_byte;
d = (ushort)10;
d /= s_char;
d = (ushort)10;
d /= s_decimal;
d = (ushort)10;
d /= s_double;
d = (ushort)10;
d /= s_float;
d = (ushort)10;
d /= s_int;
d = (ushort)10;
d /= s_long;
d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_object);
d = (ushort)10;
d /= s_sbyte;
d = (ushort)10;
d /= s_short;
d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d /= s_string);
d = (ushort)10;
d /= s_uint;
d = (ushort)10;
d /= s_ulong;
d = (ushort)10;
d /= s_ushort;
}
}
}
| |
// 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 Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class TreeManipulationTests : TestModule
{
[Fact]
public static void ConstructorXDocument()
{
RunTestCase(new ParamsObjectsCreation { Attribute = new TestCaseAttribute { Name = "Constructors with params - XDocument" } });
}
[Fact]
public static void ConstructorXElementArray()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - array", Param = 0 } }); //Param = InputParamStyle.Array
}
[Fact]
public static void ConstructorXElementIEnumerable()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - IEnumerable", Param = 2 } }); //InputParamStyle.IEnumerable
}
[Fact]
public static void ConstructorXElementNodeArray()
{
RunTestCase(new ParamsObjectsCreationElem { Attribute = new TestCaseAttribute { Name = "Constructors with params - XElement - node + array", Param = 1 } }); //InputParamStyle.SingleAndArray
}
[Fact]
public static void IEnumerableOfXAttributeRemove()
{
RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove()", Params = new object[] { false } } });
}
[Fact]
public static void IEnumerableOfXAttributeRemoveWithRemove()
{
RunTestCase(new XAttributeEnumRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XAttribute>.Remove() with Events", Params = new object[] { true } } });
}
[Fact]
public static void IEnumerableOfXNodeRemove()
{
RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove()", Params = new object[] { false } } });
}
[Fact]
public static void IEnumerableOfXNodeRemoveWithEvents()
{
RunTestCase(new XNodeSequenceRemove { Attribute = new TestCaseAttribute { Name = "IEnumerable<XNode>.Remove() with Events", Params = new object[] { true } } });
}
[Fact]
public static void LoadFromReader()
{
RunTestCase(new LoadFromReader { Attribute = new TestCaseAttribute { Name = "Load from Reader" } });
}
[Fact]
public static void LoadFromStreamSanity()
{
RunTestCase(new LoadFromStream { Attribute = new TestCaseAttribute { Name = "Load from Stream - sanity" } });
}
[Fact]
public static void SaveWithWriter()
{
RunTestCase(new SaveWithWriter { Attribute = new TestCaseAttribute { Name = "Save with Writer" } });
}
[Fact]
public static void SimpleConstructors()
{
RunTestCase(new SimpleObjectsCreation { Attribute = new TestCaseAttribute { Name = "Simple constructors" } });
}
[Fact]
public static void XAttributeRemove()
{
RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove", Params = new object[] { false } } });
}
[Fact]
public static void XAttributeRemoveWithEvents()
{
RunTestCase(new XAttributeRemove { Attribute = new TestCaseAttribute { Name = "XAttribute.Remove with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerAddIntoElement()
{
RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add1", Params = new object[] { false } } });
}
[Fact]
public static void XContainerAddIntoDocument()
{
RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add2", Params = new object[] { false } } });
}
[Fact]
public static void XContainerAddFirstInvalidIntoXDocument()
{
RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst", Params = new object[] { false } } });
}
[Fact]
public static void XContainerAddFirstInvalidIntoXDocumentWithEvents()
{
RunTestCase(new AddFirstInvalidIntoXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirst with Events", Params = new object[] { true } } });
}
[Fact]
public static void AddFirstSingeNodeAddIntoElement()
{
RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement", Params = new object[] { false } } });
}
[Fact]
public static void AddFirstSingeNodeAddIntoElementWithEvents()
{
RunTestCase(new AddFirstSingeNodeAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstSingeNodeAddIntoElement with Events", Params = new object[] { true } } });
}
[Fact]
public static void AddFirstAddFirstIntoDocument()
{
RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument", Params = new object[] { false } } });
}
[Fact]
public static void AddFirstAddFirstIntoDocumentWithEvents()
{
RunTestCase(new AddFirstAddFirstIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.AddFirstAddFirstAddFirstIntoDocument with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerAddIntoElementWithEvents()
{
RunTestCase(new XContainerAddIntoElement { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerAddIntoDocumentWithEvents()
{
RunTestCase(new XContainerAddIntoDocument { Attribute = new TestCaseAttribute { Name = "XContainer.Add with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerFirstNode()
{
RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.FirstNode", Param = true } });
}
[Fact]
public static void XContainerLastNode()
{
RunTestCase(new FirstNode { Attribute = new TestCaseAttribute { Name = "XContainer.LastNode", Param = false } });
}
[Fact]
public static void XContainerNextPreviousNode()
{
RunTestCase(new NextNode { Attribute = new TestCaseAttribute { Name = "XContainer.Next/PreviousNode" } });
}
[Fact]
public static void XContainerRemoveNodesOnXElement()
{
RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } });
}
[Fact]
public static void XContainerRemoveNodesOnXElementWithEvents()
{
RunTestCase(new XContainerRemoveNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerRemoveNodesOnXDocument()
{
RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes()", Params = new object[] { false } } });
}
[Fact]
public static void XContainerRemoveNodesOnXDocumentWithEvents()
{
RunTestCase(new XContainerRemoveNodesOnXDocument { Attribute = new TestCaseAttribute { Name = "XContainer.RemoveNodes() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerReplaceNodesOnDocument()
{
RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument()", Params = new object[] { false } } });
}
[Fact]
public static void XContainerReplaceNodesOnDocumentWithEvents()
{
RunTestCase(new XContainerReplaceNodesOnDocument { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXDocument() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XContainerReplaceNodesOnXElement()
{
RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement()", Params = new object[] { false } } });
}
[Fact]
public static void XContainerReplaceNodesOnXElementWithEvents()
{
RunTestCase(new XContainerReplaceNodesOnXElement { Attribute = new TestCaseAttribute { Name = "XContainer.ReplaceNodesOnXElement() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XElementRemoveAttributes()
{
RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes", Params = new object[] { false } } });
}
[Fact]
public static void XElementRemoveAttributesWithEvents()
{
RunTestCase(new RemoveAttributes { Attribute = new TestCaseAttribute { Name = "XElement.RemoveAttributes with Events", Params = new object[] { true } } });
}
[Fact]
public static void XElementSetAttributeValue()
{
RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue()", Params = new object[] { false } } });
}
[Fact]
public static void XElementSetAttributeValueWithEvents()
{
RunTestCase(new XElement_SetAttributeValue { Attribute = new TestCaseAttribute { Name = "XElement.SetAttributeValue() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XElementSetElementValue()
{
RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue()", Params = new object[] { false } } });
}
[Fact]
public static void XElementSetElementValueWithEvents()
{
RunTestCase(new XElement_SetElementValue { Attribute = new TestCaseAttribute { Name = "XElement.SetElementValue() with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeAddAfter()
{
RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter", Params = new object[] { false } } });
}
[Fact]
public static void XNodeAddAfterWithEvents()
{
RunTestCase(new AddNodeAfter { Attribute = new TestCaseAttribute { Name = "XNode.AddAfter with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeAddBefore()
{
RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore", Params = new object[] { false } } });
}
[Fact]
public static void XNodeAddBeforeWithEvents()
{
RunTestCase(new AddNodeBefore { Attribute = new TestCaseAttribute { Name = "XNode.AddBefore with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeRemoveNodeMisc()
{
RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
public static void XNodeRemoveNodeMiscWithEvents()
{
RunTestCase(new XNodeRemoveNodeMisc { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeRemoveOnDocument()
{
RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
public static void XNodeRemoveOnDocumentWithEvents()
{
RunTestCase(new XNodeRemoveOnDocument { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeRemoveOnElement()
{
RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove", Params = new object[] { false } } });
}
[Fact]
public static void XNodeRemoveOnElementWithEvents()
{
RunTestCase(new XNodeRemoveOnElement { Attribute = new TestCaseAttribute { Name = "XNode.Remove with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeReplaceOnDocument1()
{
RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
public static void XNodeReplaceOnDocument1WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument1 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeReplaceOnDocument2()
{
RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
public static void XNodeReplaceOnDocument2WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument2 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeReplaceOnDocument3()
{
RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
public static void XNodeReplaceOnDocument3WithEvents()
{
RunTestCase(new XNodeReplaceOnDocument3 { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
[Fact]
public static void XNodeReplaceOnElement()
{
RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith", Params = new object[] { false } } });
}
[Fact]
public static void XNodeReplaceOnElementWithEvents()
{
RunTestCase(new XNodeReplaceOnElement { Attribute = new TestCaseAttribute { Name = "XNode.ReplaceWith with Events", Params = new object[] { true } } });
}
private static void RunTestCase(TestItem testCase)
{
var module = new TreeManipulationTests();
module.Init();
module.AddChild(testCase);
module.Execute();
Assert.Equal(0, module.FailCount);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// SyncMapItemResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Preview.Sync.Service.SyncMap
{
public class SyncMapItemResource : Resource
{
public sealed class QueryResultOrderEnum : StringEnum
{
private QueryResultOrderEnum(string value) : base(value) {}
public QueryResultOrderEnum() {}
public static implicit operator QueryResultOrderEnum(string value)
{
return new QueryResultOrderEnum(value);
}
public static readonly QueryResultOrderEnum Asc = new QueryResultOrderEnum("asc");
public static readonly QueryResultOrderEnum Desc = new QueryResultOrderEnum("desc");
}
public sealed class QueryFromBoundTypeEnum : StringEnum
{
private QueryFromBoundTypeEnum(string value) : base(value) {}
public QueryFromBoundTypeEnum() {}
public static implicit operator QueryFromBoundTypeEnum(string value)
{
return new QueryFromBoundTypeEnum(value);
}
public static readonly QueryFromBoundTypeEnum Inclusive = new QueryFromBoundTypeEnum("inclusive");
public static readonly QueryFromBoundTypeEnum Exclusive = new QueryFromBoundTypeEnum("exclusive");
}
private static Request BuildFetchRequest(FetchSyncMapItemOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathMapSid + "/Items/" + options.PathKey + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Fetch(FetchSyncMapItemOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> FetchAsync(FetchSyncMapItemOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Fetch(string pathServiceSid,
string pathMapSid,
string pathKey,
ITwilioRestClient client = null)
{
var options = new FetchSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> FetchAsync(string pathServiceSid,
string pathMapSid,
string pathKey,
ITwilioRestClient client = null)
{
var options = new FetchSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteSyncMapItemOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathMapSid + "/Items/" + options.PathKey + "",
queryParams: options.GetParams(),
headerParams: options.GetHeaderParams()
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static bool Delete(DeleteSyncMapItemOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncMapItemOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="ifMatch"> The If-Match HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static bool Delete(string pathServiceSid,
string pathMapSid,
string pathKey,
string ifMatch = null,
ITwilioRestClient client = null)
{
var options = new DeleteSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey){IfMatch = ifMatch};
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="ifMatch"> The If-Match HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathMapSid,
string pathKey,
string ifMatch = null,
ITwilioRestClient client = null)
{
var options = new DeleteSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey){IfMatch = ifMatch};
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateSyncMapItemOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathMapSid + "/Items",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Create(CreateSyncMapItemOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> CreateAsync(CreateSyncMapItemOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="key"> The key </param>
/// <param name="data"> The data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Create(string pathServiceSid,
string pathMapSid,
string key,
object data,
ITwilioRestClient client = null)
{
var options = new CreateSyncMapItemOptions(pathServiceSid, pathMapSid, key, data);
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="key"> The key </param>
/// <param name="data"> The data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> CreateAsync(string pathServiceSid,
string pathMapSid,
string key,
object data,
ITwilioRestClient client = null)
{
var options = new CreateSyncMapItemOptions(pathServiceSid, pathMapSid, key, data);
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadSyncMapItemOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathMapSid + "/Items",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static ResourceSet<SyncMapItemResource> Read(ReadSyncMapItemOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<SyncMapItemResource>.FromJson("items", response.Content);
return new ResourceSet<SyncMapItemResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncMapItemResource>> ReadAsync(ReadSyncMapItemOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<SyncMapItemResource>.FromJson("items", response.Content);
return new ResourceSet<SyncMapItemResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="order"> The order </param>
/// <param name="from"> The from </param>
/// <param name="bounds"> The bounds </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static ResourceSet<SyncMapItemResource> Read(string pathServiceSid,
string pathMapSid,
SyncMapItemResource.QueryResultOrderEnum order = null,
string from = null,
SyncMapItemResource.QueryFromBoundTypeEnum bounds = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncMapItemOptions(pathServiceSid, pathMapSid){Order = order, From = from, Bounds = bounds, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="order"> The order </param>
/// <param name="from"> The from </param>
/// <param name="bounds"> The bounds </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncMapItemResource>> ReadAsync(string pathServiceSid,
string pathMapSid,
SyncMapItemResource.QueryResultOrderEnum order = null,
string from = null,
SyncMapItemResource.QueryFromBoundTypeEnum bounds = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncMapItemOptions(pathServiceSid, pathMapSid){Order = order, From = from, Bounds = bounds, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<SyncMapItemResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<SyncMapItemResource>.FromJson("items", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<SyncMapItemResource> NextPage(Page<SyncMapItemResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Preview)
);
var response = client.Request(request);
return Page<SyncMapItemResource>.FromJson("items", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<SyncMapItemResource> PreviousPage(Page<SyncMapItemResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Preview)
);
var response = client.Request(request);
return Page<SyncMapItemResource>.FromJson("items", response.Content);
}
private static Request BuildUpdateRequest(UpdateSyncMapItemOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathMapSid + "/Items/" + options.PathKey + "",
postParams: options.GetParams(),
headerParams: options.GetHeaderParams()
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Update(UpdateSyncMapItemOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update SyncMapItem parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> UpdateAsync(UpdateSyncMapItemOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="data"> The data </param>
/// <param name="ifMatch"> The If-Match HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMapItem </returns>
public static SyncMapItemResource Update(string pathServiceSid,
string pathMapSid,
string pathKey,
object data,
string ifMatch = null,
ITwilioRestClient client = null)
{
var options = new UpdateSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey, data){IfMatch = ifMatch};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathMapSid"> The map_sid </param>
/// <param name="pathKey"> The key </param>
/// <param name="data"> The data </param>
/// <param name="ifMatch"> The If-Match HTTP request header </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMapItem </returns>
public static async System.Threading.Tasks.Task<SyncMapItemResource> UpdateAsync(string pathServiceSid,
string pathMapSid,
string pathKey,
object data,
string ifMatch = null,
ITwilioRestClient client = null)
{
var options = new UpdateSyncMapItemOptions(pathServiceSid, pathMapSid, pathKey, data){IfMatch = ifMatch};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a SyncMapItemResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> SyncMapItemResource object represented by the provided JSON </returns>
public static SyncMapItemResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<SyncMapItemResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The key
/// </summary>
[JsonProperty("key")]
public string Key { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The map_sid
/// </summary>
[JsonProperty("map_sid")]
public string MapSid { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The revision
/// </summary>
[JsonProperty("revision")]
public string Revision { get; private set; }
/// <summary>
/// The data
/// </summary>
[JsonProperty("data")]
public object Data { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The created_by
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
private SyncMapItemResource()
{
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.core
{
/// <summary>
/// <para>Provides resizing behavior to any widget.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.core.MResizable", OmitOptionalParameters = true, Export = false)]
public partial class MResizable
{
#region Properties
/// <summary>
/// <para>Property group to configure the resize behaviour for all edges at once</para>
/// </summary>
[JsProperty(Name = "resizable", NativeField = true)]
public object Resizable { get; set; }
/// <summary>
/// <para>Whether the bottom edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableBottom", NativeField = true)]
public bool ResizableBottom { get; set; }
/// <summary>
/// <para>Whether the left edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableLeft", NativeField = true)]
public bool ResizableLeft { get; set; }
/// <summary>
/// <para>Whether the right edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableRight", NativeField = true)]
public bool ResizableRight { get; set; }
/// <summary>
/// <para>Whether the top edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableTop", NativeField = true)]
public bool ResizableTop { get; set; }
/// <summary>
/// <para>The tolerance to activate resizing</para>
/// </summary>
[JsProperty(Name = "resizeSensitivity", NativeField = true)]
public double ResizeSensitivity { get; set; }
/// <summary>
/// <para>Whether a frame replacement should be used during the resize sequence</para>
/// </summary>
[JsProperty(Name = "useResizeFrame", NativeField = true)]
public bool UseResizeFrame { get; set; }
#endregion Properties
#region Methods
public MResizable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableBottom.</para>
/// </summary>
[JsMethod(Name = "getResizableBottom")]
public bool GetResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableLeft.</para>
/// </summary>
[JsMethod(Name = "getResizableLeft")]
public bool GetResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableRight.</para>
/// </summary>
[JsMethod(Name = "getResizableRight")]
public bool GetResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableTop.</para>
/// </summary>
[JsMethod(Name = "getResizableTop")]
public bool GetResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizeSensitivity.</para>
/// </summary>
[JsMethod(Name = "getResizeSensitivity")]
public double GetResizeSensitivity() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property useResizeFrame.</para>
/// </summary>
[JsMethod(Name = "getUseResizeFrame")]
public bool GetUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableBottom.</param>
[JsMethod(Name = "initResizableBottom")]
public void InitResizableBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableLeft.</param>
[JsMethod(Name = "initResizableLeft")]
public void InitResizableLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableRight.</param>
[JsMethod(Name = "initResizableRight")]
public void InitResizableRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableTop.</param>
[JsMethod(Name = "initResizableTop")]
public void InitResizableTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizeSensitivity
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizeSensitivity.</param>
[JsMethod(Name = "initResizeSensitivity")]
public void InitResizeSensitivity(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property useResizeFrame
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property useResizeFrame.</param>
[JsMethod(Name = "initUseResizeFrame")]
public void InitUseResizeFrame(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableBottom equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableBottom")]
public void IsResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableLeft equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableLeft")]
public void IsResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableRight equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableRight")]
public void IsResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableTop equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableTop")]
public void IsResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property useResizeFrame equals true.</para>
/// </summary>
[JsMethod(Name = "isUseResizeFrame")]
public void IsUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizable.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizable")]
public void ResetResizable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableBottom")]
public void ResetResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableLeft")]
public void ResetResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableRight")]
public void ResetResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableTop")]
public void ResetResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizeSensitivity.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizeSensitivity")]
public void ResetResizeSensitivity() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property useResizeFrame.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetUseResizeFrame")]
public void ResetUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group resizable.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="resizableTop">Sets the value of the property #resizableTop.</param>
/// <param name="resizableRight">Sets the value of the property #resizableRight.</param>
/// <param name="resizableBottom">Sets the value of the property #resizableBottom.</param>
/// <param name="resizableLeft">Sets the value of the property #resizableLeft.</param>
[JsMethod(Name = "setResizable")]
public void SetResizable(object resizableTop, object resizableRight, object resizableBottom, object resizableLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableBottom.</para>
/// </summary>
/// <param name="value">New value for property resizableBottom.</param>
[JsMethod(Name = "setResizableBottom")]
public void SetResizableBottom(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableLeft.</para>
/// </summary>
/// <param name="value">New value for property resizableLeft.</param>
[JsMethod(Name = "setResizableLeft")]
public void SetResizableLeft(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableRight.</para>
/// </summary>
/// <param name="value">New value for property resizableRight.</param>
[JsMethod(Name = "setResizableRight")]
public void SetResizableRight(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableTop.</para>
/// </summary>
/// <param name="value">New value for property resizableTop.</param>
[JsMethod(Name = "setResizableTop")]
public void SetResizableTop(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizeSensitivity.</para>
/// </summary>
/// <param name="value">New value for property resizeSensitivity.</param>
[JsMethod(Name = "setResizeSensitivity")]
public void SetResizeSensitivity(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property useResizeFrame.</para>
/// </summary>
/// <param name="value">New value for property useResizeFrame.</param>
[JsMethod(Name = "setUseResizeFrame")]
public void SetUseResizeFrame(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableBottom.</para>
/// </summary>
[JsMethod(Name = "toggleResizableBottom")]
public void ToggleResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableLeft.</para>
/// </summary>
[JsMethod(Name = "toggleResizableLeft")]
public void ToggleResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableRight.</para>
/// </summary>
[JsMethod(Name = "toggleResizableRight")]
public void ToggleResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableTop.</para>
/// </summary>
[JsMethod(Name = "toggleResizableTop")]
public void ToggleResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property useResizeFrame.</para>
/// </summary>
[JsMethod(Name = "toggleUseResizeFrame")]
public void ToggleUseResizeFrame() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// 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 gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>IndexEndpoint</c> resource.</summary>
public sealed partial class IndexEndpointName : gax::IResourceName, sys::IEquatable<IndexEndpointName>
{
/// <summary>The possible contents of <see cref="IndexEndpointName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>
/// .
/// </summary>
ProjectLocationIndexEndpoint = 1,
}
private static gax::PathTemplate s_projectLocationIndexEndpoint = new gax::PathTemplate("projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}");
/// <summary>Creates a <see cref="IndexEndpointName"/> 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="IndexEndpointName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static IndexEndpointName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new IndexEndpointName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="IndexEndpointName"/> with the pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="IndexEndpointName"/> constructed from the provided ids.</returns>
public static IndexEndpointName FromProjectLocationIndexEndpoint(string projectId, string locationId, string indexEndpointId) =>
new IndexEndpointName(ResourceNameType.ProjectLocationIndexEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexEndpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string indexEndpointId) =>
FormatProjectLocationIndexEndpoint(projectId, locationId, indexEndpointId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </returns>
public static string FormatProjectLocationIndexEndpoint(string projectId, string locationId, string indexEndpointId) =>
s_projectLocationIndexEndpoint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="IndexEndpointName"/> 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}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="IndexEndpointName"/> if successful.</returns>
public static IndexEndpointName Parse(string indexEndpointName) => Parse(indexEndpointName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="IndexEndpointName"/> 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}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexEndpointName">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="IndexEndpointName"/> if successful.</returns>
public static IndexEndpointName Parse(string indexEndpointName, bool allowUnparsed) =>
TryParse(indexEndpointName, allowUnparsed, out IndexEndpointName 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="IndexEndpointName"/> 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}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="IndexEndpointName"/>, 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 indexEndpointName, out IndexEndpointName result) =>
TryParse(indexEndpointName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="IndexEndpointName"/> 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}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexEndpointName">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="IndexEndpointName"/>, 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 indexEndpointName, bool allowUnparsed, out IndexEndpointName result)
{
gax::GaxPreconditions.CheckNotNull(indexEndpointName, nameof(indexEndpointName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationIndexEndpoint.TryParseName(indexEndpointName, out resourceName))
{
result = FromProjectLocationIndexEndpoint(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(indexEndpointName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private IndexEndpointName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string indexEndpointId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
IndexEndpointId = indexEndpointId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="IndexEndpointName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
public IndexEndpointName(string projectId, string locationId, string indexEndpointId) : this(ResourceNameType.ProjectLocationIndexEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexEndpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)))
{
}
/// <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>IndexEndpoint</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string IndexEndpointId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { 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.ProjectLocationIndexEndpoint: return s_projectLocationIndexEndpoint.Expand(ProjectId, LocationId, IndexEndpointId);
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 IndexEndpointName);
/// <inheritdoc/>
public bool Equals(IndexEndpointName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(IndexEndpointName a, IndexEndpointName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(IndexEndpointName a, IndexEndpointName b) => !(a == b);
}
public partial class IndexEndpoint
{
/// <summary>
/// <see cref="gcav::IndexEndpointName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::IndexEndpointName IndexEndpointName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::IndexEndpointName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeployedIndex
{
/// <summary><see cref="IndexName"/>-typed view over the <see cref="Index"/> resource name property.</summary>
public IndexName IndexAsIndexName
{
get => string.IsNullOrEmpty(Index) ? null : IndexName.Parse(Index, allowUnparsed: true);
set => Index = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsHeadExceptions
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestHeadExceptionTestServiceClient : ServiceClient<AutoRestHeadExceptionTestServiceClient>, IAutoRestHeadExceptionTestServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IHeadExceptionOperations.
/// </summary>
public virtual IHeadExceptionOperations HeadException { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestHeadExceptionTestServiceClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestHeadExceptionTestServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestHeadExceptionTestServiceClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestHeadExceptionTestServiceClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadExceptionTestServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadExceptionTestServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadExceptionTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadExceptionTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadExceptionTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
HeadException = new HeadExceptionOperations(this);
BaseUri = new System.Uri("http://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
#if !FULL_AOT_RUNTIME
namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
internal enum TypeKind
{
IsArray = 1,
IsPointer = 2,
IsByRef = 3,
}
// This is a kind of Type object that will represent the compound expression of a parameter type or field type.
#if MONO
partial class SymbolType : TypeInfo
#else
internal sealed class SymbolType : TypeInfo
#endif
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#if !MONO
#region Static Members
internal static Type FormCompoundType(char[] bFormat, Type baseType, int curIndex)
{
// This function takes a string to describe the compound type, such as "[,][]", and a baseType.
//
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
// Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 for
// the first dimension)
// Example: []* - pointer to a one dimensional array
// Example: *[] - one dimensional array. The element type is a pointer to the baseType
// Example: []& - ByRef of a single dimensional array. Only one & is allowed and it must appear the last!
// Example: [?] - Array with unknown bound
SymbolType symbolType;
int iLowerBound;
int iUpperBound;
if (bFormat == null || curIndex == bFormat.Length)
{
// we have consumed all of the format string
return baseType;
}
if (bFormat[curIndex] == '&')
{
// ByRef case
symbolType = new SymbolType(TypeKind.IsByRef);
symbolType.SetFormat(bFormat, curIndex, 1);
curIndex++;
if (curIndex != bFormat.Length)
// ByRef has to be the last char!!
throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
symbolType.SetElementType(baseType);
return symbolType;
}
if (bFormat[curIndex] == '[')
{
// Array type.
symbolType = new SymbolType(TypeKind.IsArray);
int startIndex = curIndex;
curIndex++;
iLowerBound = 0;
iUpperBound = -1;
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
// Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 sepcified)
while (bFormat[curIndex] != ']')
{
if (bFormat[curIndex] == '*')
{
symbolType.m_isSzArray = false;
curIndex++;
}
// consume, one dimension at a time
if ((bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') || bFormat[curIndex] == '-')
{
bool isNegative = false;
if (bFormat[curIndex] == '-')
{
isNegative = true;
curIndex++;
}
// lower bound is specified. Consume the low bound
while (bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9')
{
iLowerBound = iLowerBound * 10;
iLowerBound += bFormat[curIndex] - '0';
curIndex++;
}
if (isNegative)
{
iLowerBound = 0 - iLowerBound;
}
// set the upper bound to be less than LowerBound to indicate that upper bound it not specified yet!
iUpperBound = iLowerBound - 1;
}
if (bFormat[curIndex] == '.')
{
// upper bound is specified
// skip over ".."
curIndex++;
if (bFormat[curIndex] != '.')
{
// bad format!! Throw exception
throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
}
curIndex++;
// consume the upper bound
if ((bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9') || bFormat[curIndex] == '-')
{
bool isNegative = false;
iUpperBound = 0;
if (bFormat[curIndex] == '-')
{
isNegative = true;
curIndex++;
}
// lower bound is specified. Consume the low bound
while (bFormat[curIndex] >= '0' && bFormat[curIndex] <= '9')
{
iUpperBound = iUpperBound * 10;
iUpperBound += bFormat[curIndex] - '0';
curIndex++;
}
if (isNegative)
{
iUpperBound = 0 - iUpperBound;
}
if (iUpperBound < iLowerBound)
{
// User specified upper bound less than lower bound, this is an error.
// Throw error exception.
throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
}
}
}
if (bFormat[curIndex] == ',')
{
// We have more dimension to deal with.
// now set the lower bound, the size, and increase the dimension count!
curIndex++;
symbolType.SetBounds(iLowerBound, iUpperBound);
// clear the lower and upper bound information for next dimension
iLowerBound = 0;
iUpperBound = -1;
}
else if (bFormat[curIndex] != ']')
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
}
}
// The last dimension information
symbolType.SetBounds(iLowerBound, iUpperBound);
// skip over ']'
curIndex++;
symbolType.SetFormat(bFormat, startIndex, curIndex - startIndex);
// set the base type of array
symbolType.SetElementType(baseType);
return FormCompoundType(bFormat, symbolType, curIndex);
}
else if (bFormat[curIndex] == '*')
{
// pointer type.
symbolType = new SymbolType(TypeKind.IsPointer);
symbolType.SetFormat(bFormat, curIndex, 1);
curIndex++;
symbolType.SetElementType(baseType);
return FormCompoundType(bFormat, symbolType, curIndex);
}
return null;
}
#endregion
#region Data Members
internal TypeKind m_typeKind;
internal Type m_baseType;
internal int m_cRank; // count of dimension
// If LowerBound and UpperBound is equal, that means one element.
// If UpperBound is less than LowerBound, then the size is not specified.
internal int[] m_iaLowerBound;
internal int[] m_iaUpperBound; // count of dimension
private char[] m_bFormat; // format string to form the full name.
private bool m_isSzArray = true;
#endregion
#region Constructor
internal SymbolType(TypeKind typeKind)
{
m_typeKind = typeKind;
m_iaLowerBound = new int[4];
m_iaUpperBound = new int[4];
}
#endregion
#region Internal Members
internal void SetElementType(Type baseType)
{
if (baseType == null)
throw new ArgumentNullException("baseType");
Contract.EndContractBlock();
m_baseType = baseType;
}
private void SetBounds(int lower, int upper)
{
// Increase the rank, set lower and upper bound
if (lower != 0 || upper != -1)
m_isSzArray = false;
if (m_iaLowerBound.Length <= m_cRank)
{
// resize the bound array
int[] iaTemp = new int[m_cRank * 2];
Array.Copy(m_iaLowerBound, iaTemp, m_cRank);
m_iaLowerBound = iaTemp;
Array.Copy(m_iaUpperBound, iaTemp, m_cRank);
m_iaUpperBound = iaTemp;
}
m_iaLowerBound[m_cRank] = lower;
m_iaUpperBound[m_cRank] = upper;
m_cRank++;
}
internal void SetFormat(char[] bFormat, int curIndex, int length)
{
// Cache the text display format for this SymbolType
char[] bFormatTemp = new char[length];
Array.Copy(bFormat, curIndex, bFormatTemp, 0, length);
m_bFormat = bFormatTemp;
}
#endregion
#endif
#region Type Overrides
#if !MONO
internal override bool IsSzArray
{
get
{
if (m_cRank > 1)
return false;
return m_isSzArray;
}
}
public override Type MakePointerType()
{
return SymbolType.FormCompoundType((new String(m_bFormat) + "*").ToCharArray(), m_baseType, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType((new String(m_bFormat) + "&").ToCharArray(), m_baseType, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType((new String(m_bFormat) + "[]").ToCharArray(), m_baseType, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for(int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType((new String(m_bFormat) + s).ToCharArray(), m_baseType, 0) as SymbolType;
return st;
}
public override int GetArrayRank()
{
if (!IsArray)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
Contract.EndContractBlock();
return m_cRank;
}
#endif
public override Guid GUID
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); }
}
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target,
Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Module Module
{
get
{
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType);
return baseType.Module;
}
}
public override Assembly Assembly
{
get
{
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType);
return baseType.Assembly;
}
}
public override RuntimeTypeHandle TypeHandle
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); }
}
#if !MONO
public override String Name
{
get
{
Type baseType;
String sFormat = new String(m_bFormat);
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType)
sFormat = new String(((SymbolType)baseType).m_bFormat) + sFormat;
return baseType.Name + sFormat;
}
}
public override String FullName
{
get
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
}
}
public override String AssemblyQualifiedName
{
get
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
}
}
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endif
public override String Namespace
{
get { return m_baseType.Namespace; }
}
public override Type BaseType
{
get { return typeof(System.Array); }
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Type GetInterface(String name,bool ignoreCase)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Type[] GetInterfaces()
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override EventInfo[] GetEvents()
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
// Return the attribute flags of the base type?
Type baseType;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType);
return baseType.Attributes;
}
#if !MONO
protected override bool IsArrayImpl()
{
return m_typeKind == TypeKind.IsArray;
}
protected override bool IsPointerImpl()
{
return m_typeKind == TypeKind.IsPointer;
}
protected override bool IsByRefImpl()
{
return m_typeKind == TypeKind.IsByRef;
}
#endif
protected override bool IsPrimitiveImpl()
{
return false;
}
protected override bool IsValueTypeImpl()
{
return false;
}
protected override bool IsCOMObjectImpl()
{
return false;
}
public override bool IsConstructedGenericType
{
get
{
return false;
}
}
public override Type GetElementType()
{
return m_baseType;
}
protected override bool HasElementTypeImpl()
{
return m_baseType != null;
}
#if !MONO
public override Type UnderlyingSystemType
{
get { return this; }
}
#endif
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override bool IsDefined (Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
namespace RE
{
public /*abstract*/ partial class REBaseItem : UserControl
{
private ContextMenuStrip mergeContextMenu = null;
private bool modified = false;
public REBaseItem()
{
InitializeComponent();
(imgItemResize.Image as Bitmap).MakeTransparent(Color.White);
}
protected override void OnCreateControl()
{
base.OnCreateControl();
if (mergeContextMenu != null)
{
int i = 0;
while (mergeContextMenu.Items.Count != 0)
{
contextMenuStrip1.Items.Insert(i, mergeContextMenu.Items[0]);
i++;
}
}
else
{
menuTopSeparator.Visible = false;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
lblCaption.Width = ClientSize.Width - 8 - panContextMenu.Width;
panContextMenu.Left = lblCaption.Width + 5;
imgItemResize.Location = new Point(
ClientSize.Width - imgItemResize.Width,
ClientSize.Height - imgItemResize.Height);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using(Pen p=new Pen(SystemColors.ControlLightLight,1))
{
e.Graphics.DrawLine(p,0,0,Width-2,0);
e.Graphics.DrawLine(p,0,1,0,Height-2);
}
using(Pen p=new Pen(SystemColors.ControlDarkDark,1))
{
e.Graphics.DrawLine(p,Width-1,1,Width-1,Height-1);
e.Graphics.DrawLine(p,1,Height-1,Width-2,Height-1);
}
}
public void Close()
{
//TODO: add to undo stack!
//ask parent verif? if(LinkPanel.VerifItemRemove)
DisconnectAll();
Parent.Controls.Remove(this);
}
private void bringToFrontToolStripMenuItem_Click(object sender, EventArgs e)
{
BringToFront();
}
private void sendToBackToolStripMenuItem_Click(object sender, EventArgs e)
{
SendToBack();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
BackColor=SystemColors.Control;
//too bad, on close Parent=null here already
}
public void ItemSelectFocus()
{
//divert focus to something on item other than textbox to enable clipboard shortcuts
panContextMenu.Focus();
}
protected virtual void DisconnectAll()
{
ArrayList cq = new ArrayList();
cq.Add(this);
Control c;
while (cq.Count != 0)
{
c = cq[0] as Control;
cq.RemoveAt(0);
foreach (Control c1 in c.Controls)
{
if (c1.Controls.Count != 0) cq.Add(c1);
if (c1 is RELinkPoint) (c1 as RELinkPoint).ConnectedTo = null;
}
}
}
public RELinkPoint[] GetLinkPoints(bool OnlyConnected)
{
List<RELinkPoint> linkpoints = new List<RELinkPoint>();
ArrayList cq = new ArrayList();
cq.Add(this);
Control c;
while (cq.Count != 0)
{
c = cq[0] as Control;
cq.RemoveAt(0);
foreach (Control c1 in c.Controls)
{
if (c1.Controls.Count != 0) cq.Add(c1);
if (c1 is RELinkPoint)
{
RELinkPoint linkpoint = c1 as RELinkPoint;
if (!OnlyConnected || linkpoint.IsConnected) linkpoints.Add(linkpoint);
}
}
}
return linkpoints.ToArray();
}
[Browsable(true),Category("Appearance"),Description("Text displayed as item title")]
public string Caption
{
get
{
return lblCaption.Text;
}
set
{
lblCaption.Text = value;
}
}
[Browsable(false),Category("Appearance"),Description("Display the item as focused or as member of a selection, controlled by parent LinkPanel at run-time")]
public bool Selected
{
get
{
return lblCaption.BackColor==SystemColors.ActiveCaption;
}
set
{
if(value)
{
lblCaption.BackColor=SystemColors.ActiveCaption;
lblCaption.ForeColor=SystemColors.ActiveCaptionText;
}
else
{
lblCaption.BackColor=SystemColors.InactiveCaption;
lblCaption.ForeColor=SystemColors.InactiveCaptionText;
}
lblCaption.Invalidate();
}
}
[Category("Layout"),Description("Switch the bottom right resize handle to allow resizing of item")]
public bool Resizable
{
set{imgItemResize.Visible=value;}
get{return imgItemResize.Visible;}
}
[Browsable(true), Category("Behavior"), Description("ContextMenuStrip to merge with item's ContextMenuStrip")]
public ContextMenuStrip MergeContextMenuStrip
{
set { mergeContextMenu = value; }
get { return mergeContextMenu; }
}
public bool Modified
{
set
{
modified = value;
if (!modified)
foreach (Control c in Controls)
if (c is TextBox)
(c as TextBox).Modified = false;
//more classes? cascaded?
}
get
{
if (!modified)
foreach (Control c in Controls)
if (c is TextBox)
if ((c as TextBox).Modified) return true;
return modified;
}
}
public virtual void SaveToXml(XmlElement Element)
{
//inheritants must save properties
Element.SetAttribute("left",Left.ToString());
Element.SetAttribute("top",Top.ToString());
if (Resizable)
{
Element.SetAttribute("width", Width.ToString());
Element.SetAttribute("height", Height.ToString());
}
}
public virtual void LoadFromXml(XmlElement Element)
{
//inheritants must link linkpoints and read properties
if (Resizable)
SetBounds(
Int32.Parse(Element.GetAttribute("left")),
Int32.Parse(Element.GetAttribute("top")),
Int32.Parse(Element.GetAttribute("width")),
Int32.Parse(Element.GetAttribute("height")));
else
SetBounds(
Int32.Parse(Element.GetAttribute("left")),
Int32.Parse(Element.GetAttribute("top")),
Width,
Height);
}
private void panel1_Click(object sender, EventArgs e)
{
if (lblCaption.ContextMenuStrip != null)
lblCaption.ContextMenuStrip.Show(PointToScreen(panContextMenu.Location));
}
private void panContextMenu_MouseDown(object sender, MouseEventArgs e)
{
panContextMenu.BackColor = SystemColors.ButtonShadow;
}
private void panContextMenu_MouseUp(object sender, MouseEventArgs e)
{
panContextMenu.BackColor = SystemColors.ButtonFace;
}
private void panContextMenu_MouseEnter(object sender, EventArgs e)
{
panContextMenu.BackColor = SystemColors.ButtonHighlight;
}
private void panContextMenu_MouseLeave(object sender, EventArgs e)
{
panContextMenu.BackColor = SystemColors.ButtonFace;
}
protected bool StrToBool(string s)
{
return (s == "1") || (s == "true") || (s.ToLower() == "true");
}
protected string BoolToStr(bool b)
{
return b ? "1" : "0";
}
public virtual void Start()
{
//inheritants call emit on any linkpoints that have data ready
//also perform further processing by handling linkpoint Signal events
}
public virtual void Stop()
{
//inheritants perform clean-up code, any exceptions go ignored
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Linq;
using Encog.ML.EA.Genome;
using Encog.ML.EA.Population;
using Encog.ML.EA.Sort;
using Encog.ML.EA.Train;
using Encog.ML.Genetic;
namespace Encog.ML.EA.Species
{
/// <summary>
/// Speciate based on threshold. Any genomes with a compatibility score below a
/// level will be in the same species.
/// </summary>
[Serializable]
public abstract class ThresholdSpeciation : ISpeciation
{
/// <summary>
/// The minimum compatibility that two genes must have to be in the same
/// species.
/// </summary>
private double _compatibilityThreshold = 1.0;
/// <summary>
/// The maximum number of species. This is just a target. If the number of
/// species goes over this number then the compatibilityThreshold is
/// increased to decrease the number of species.
/// </summary>
private int _maxNumberOfSpecies = 40;
/// <summary>
/// The maximum number of generations allows with no improvement. After this
/// the genomes in this species are not allowed to reproduce or continue.
/// This does not apply to top species.
/// </summary>
private int _numGensAllowedNoImprovement = 15;
/// <summary>
/// The training being used.
/// </summary>
private IEvolutionaryAlgorithm _owner;
/// <summary>
/// The population.
/// </summary>
private IPopulation _population;
/// <summary>
/// The method used to sort the genomes in the species. More desirable
/// genomes should come first for later selection.
/// </summary>
private SortGenomesForSpecies _sortGenomes;
/// <summary>
/// The minimum compatibility that two genes must have to be in the same
/// species.
/// </summary>
public double CompatibilityThreshold
{
get { return _compatibilityThreshold; }
set { _compatibilityThreshold = value; }
}
/// <summary>
/// The maximum number of species. This is just a target. If the number of
/// species goes over this number then the compatibilityThreshold is
/// increased to decrease the number of species.
/// </summary>
public int MaxNumberOfSpecies
{
get { return _maxNumberOfSpecies; }
set { _maxNumberOfSpecies = value; }
}
/// <summary>
/// The maximum number of generations allows with no improvement. After this
/// the genomes in this species are not allowed to reproduce or continue.
/// This does not apply to top species.
/// </summary>
public int NumGensAllowedNoImprovement
{
get { return _numGensAllowedNoImprovement; }
set { _numGensAllowedNoImprovement = value; }
}
/// <summary>
/// The owner.
/// </summary>
public IEvolutionaryAlgorithm Owner
{
get { return _owner; }
}
/// <summary>
/// The method used to sort the genomes in the species. More desirable
/// genomes should come first for later selection.
/// </summary>
public SortGenomesForSpecies SortGenomes
{
get { return _sortGenomes; }
set { _sortGenomes = value; }
}
/// <inheritdoc />
public void Init(IEvolutionaryAlgorithm theOwner)
{
_owner = theOwner;
_population = theOwner.Population;
_sortGenomes = new SortGenomesForSpecies(_owner);
}
/// <inheritdoc />
public void PerformSpeciation(IList<IGenome> genomeList)
{
IList<IGenome> newGenomeList = ResetSpecies(genomeList);
SpeciateAndCalculateSpawnLevels(newGenomeList);
}
/// <summary>
/// Add a genome.
/// </summary>
/// <param name="species">The species to add to.</param>
/// <param name="genome">The genome to add.</param>
public void AddSpeciesMember(ISpecies species, IGenome genome)
{
if (_owner.ValidationMode)
{
if (species.Members.Contains(genome))
{
throw new GeneticError("Species already contains genome: "
+ genome);
}
}
if (_owner.SelectionComparer.Compare(genome,
species.Leader) < 0)
{
species.BestScore = genome.AdjustedScore;
species.GensNoImprovement = 0;
species.Leader = genome;
}
species.Add(genome);
}
/// <summary>
/// Adjust the species compatibility threshold. This prevents us from having
/// too many species. Dynamically increase or decrease the
/// compatibilityThreshold.
/// </summary>
private void AdjustCompatibilityThreshold()
{
// has this been disabled (unlimited species)
if (_maxNumberOfSpecies < 1)
{
return;
}
const double thresholdIncrement = 0.01;
if (_population.Species.Count > _maxNumberOfSpecies)
{
_compatibilityThreshold += thresholdIncrement;
}
else if (_population.Species.Count < 2)
{
_compatibilityThreshold -= thresholdIncrement;
}
}
/// <summary>
/// Divide up the potential offspring by the most fit species. To do this we
/// look at the total species score, vs each individual species percent
/// contribution to that score.
/// </summary>
/// <param name="speciesCollection">The current species list.</param>
/// <param name="totalSpeciesScore">The total score over all species.</param>
private void DivideByFittestSpecies(IEnumerable<ISpecies> speciesCollection,
double totalSpeciesScore)
{
ISpecies bestSpecies = FindBestSpecies();
// loop over all species and calculate its share
ISpecies[] speciesArray = speciesCollection.ToArray();
foreach (ISpecies element in speciesArray)
{
var species = element;
// calculate the species share based on the percent of the total
// species score
var share = (int) Math
.Round((species.OffspringShare/totalSpeciesScore)
*_owner.Population.PopulationSize);
// do not give the best species a zero-share
if ((species == bestSpecies) && (share == 0))
{
share = 1;
}
// if the share is zero, then remove the species
if ((species.Members.Count == 0) || (share == 0))
{
RemoveSpecies(species);
}
// if the species has not improved over the specified number of
// generations, then remove it.
else if ((species.GensNoImprovement > _numGensAllowedNoImprovement)
&& (species != bestSpecies))
{
RemoveSpecies(species);
}
else
{
// otherwise assign a share and sort the members.
species.OffspringCount = share;
species.Members.Sort(_sortGenomes);
}
}
}
/// <summary>
/// Find the best species.
/// </summary>
/// <returns>The best species.</returns>
public ISpecies FindBestSpecies()
{
if (_owner.BestGenome != null)
{
return _owner.BestGenome.Species;
}
return null;
}
/// <summary>
/// Attempt to remove a removable species. If the species is the best
/// species, then do not remove it. If the species is the last species, don't
/// remove it.
/// </summary>
/// <param name="species">The species to attempt to remove.</param>
public void RemoveSpecies(ISpecies species)
{
if (species != FindBestSpecies())
{
if (_population.Species.Count > 1)
{
_population.Species.Remove(species);
}
}
}
/// <summary>
/// If no species has a good score then divide the potential offspring amount
/// all species evenly.
/// </summary>
/// <param name="speciesCollection">The current set of species.</param>
private void DivideEven(IList<ISpecies> speciesCollection)
{
double ratio = 1.0/speciesCollection.Count;
foreach (ISpecies species in speciesCollection)
{
var share = (int) Math.Round(ratio
*_owner.Population.PopulationSize);
species.OffspringCount = share;
}
}
/// <summary>
/// Level off all of the species shares so that they add up to the desired
/// population size. If they do not add up to the desired species size, this
/// was a result of rounding the floating point share amounts to integers.
/// </summary>
private void LevelOff()
{
List<ISpecies> list = _population.Species;
if (list.Count == 0)
{
throw new EncogError(
"Can't speciate, next generation contains no species.");
}
list.Sort(new SpeciesComparer(_owner));
// best species gets at least one offspring
if (list[0].OffspringCount == 0)
{
list[0].OffspringCount = 1;
}
// total up offspring
int total = list.Sum(species => species.OffspringCount);
// how does the total offspring count match the target
int diff = _population.PopulationSize - total;
if (diff < 0)
{
// need less offspring
int index = list.Count - 1;
while ((diff != 0) && (index > 0))
{
ISpecies species = list[index];
int t = Math.Min(species.OffspringCount,
Math.Abs(diff));
species.OffspringCount = (species.OffspringCount - t);
if (species.OffspringCount == 0)
{
list.Remove(species);
}
diff += t;
index--;
}
}
else
{
// need more offspring
list[0].OffspringCount = (
list[0].OffspringCount + diff);
}
}
/// <summary>
/// Reset for an iteration.
/// </summary>
/// <param name="inputGenomes">The genomes to speciate.</param>
/// <returns></returns>
private IList<IGenome> ResetSpecies(IList<IGenome> inputGenomes)
{
ISpecies[] speciesArray = _population.Species.ToArray();
// Add the genomes
IList<IGenome> result = inputGenomes.ToList();
foreach (ISpecies element in speciesArray)
{
var s = (BasicSpecies) element;
s.Purge();
// did the leader die? If so, disband the species. (but don't kill
// the genomes)
if (!inputGenomes.Contains(s.Leader))
{
RemoveSpecies(s);
}
else if (s.GensNoImprovement > _numGensAllowedNoImprovement)
{
RemoveSpecies(s);
}
// remove the leader from the list we return. the leader already has
// a species
result.Remove(s.Leader);
}
if (_population.Species.Count == 0)
{
throw new EncogError("Can't speciate, the population is empty.");
}
return result;
}
/// <summary>
/// Determine the species.
/// </summary>
/// <param name="genomes">The genomes to speciate.</param>
private void SpeciateAndCalculateSpawnLevels(IList<IGenome> genomes)
{
double maxScore = 0;
if (genomes.Count == 0)
{
throw new EncogError("Can't speciate, the population is empty.");
}
IList<ISpecies> speciesCollection = _population.Species;
if (speciesCollection.Count == 0)
{
throw new EncogError("Can't speciate, there are no species.1");
}
// calculate compatibility between genomes and species
AdjustCompatibilityThreshold();
// assign genomes to species (if any exist)
foreach (IGenome g in genomes)
{
ISpecies currentSpecies = null;
IGenome genome = g;
if (!Double.IsNaN(genome.AdjustedScore)
&& !double.IsInfinity(genome.AdjustedScore))
{
maxScore = Math.Max(genome.AdjustedScore, maxScore);
}
foreach (ISpecies s in speciesCollection)
{
double compatibility = GetCompatibilityScore(genome,
s.Leader);
if (compatibility <= _compatibilityThreshold)
{
currentSpecies = s;
AddSpeciesMember(s, genome);
genome.Species = s;
break;
}
}
// if this genome did not fall into any existing species, create a
// new species
if (currentSpecies == null)
{
currentSpecies = new BasicSpecies(_population, genome);
_population.Species.Add(currentSpecies);
}
}
//
double totalSpeciesScore = speciesCollection.Sum(species => species.CalculateShare(_owner.ScoreFunction.ShouldMinimize, maxScore));
if (speciesCollection.Count == 0)
{
throw new EncogError("Can't speciate, there are no species.2");
}
if (totalSpeciesScore < EncogFramework.DefaultDoubleEqual)
{
// This should not happen much, or if it does, only in the
// beginning.
// All species scored zero. So they are all equally bad. Just divide
// up the right to produce offspring evenly.
DivideEven(speciesCollection);
}
else
{
// Divide up the number of offspring produced to the most fit
// species.
DivideByFittestSpecies(speciesCollection, totalSpeciesScore);
}
LevelOff();
}
/// <summary>
/// Determine how compatible two genomes are. More compatible genomes will be
/// placed into the same species. The lower the number, the more compatible.
/// </summary>
/// <param name="genome1">The first genome.</param>
/// <param name="genome2">The second genome.</param>
/// <returns>The compatability level.</returns>
public abstract double GetCompatibilityScore(IGenome genome1, IGenome genome2);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SteamLanguageParser;
using System.Text.RegularExpressions;
namespace GoSteamLanguageGenerator
{
public class GoGen
{
/// <summary>
/// Maps the SteamLanguage types to Go types.
/// </summary>
private static Dictionary<String, String> typeMap = new Dictionary<String, String> {
{"byte", "uint8"},
{"short", "int16"},
{"ushort", "uint16"},
{"int", "int32"},
{"uint", "uint32"},
{"long", "int64"},
{"ulong", "uint64"},
{"char", "uint16"}
};
private bool debug;
public GoGen(bool debug)
{
this.debug = debug;
}
/// <summary>
/// Maps the enum names to their underlying Go types. In most cases, this is int32.
/// </summary>
private Dictionary<string, string> enumTypes = new Dictionary<string, string>();
public void EmitEnums(Node root, StringBuilder sb)
{
sb.AppendLine("// Generated code");
sb.AppendLine("// DO NOT EDIT");
sb.AppendLine();
sb.AppendLine("package steamlang");
sb.AppendLine();
sb.AppendLine("import (");
sb.AppendLine(" \"strings\"");
sb.AppendLine(" \"sort\"");
sb.AppendLine(" \"fmt\"");
sb.AppendLine(")");
sb.AppendLine();
foreach (Node n in root.childNodes) {
EmitEnumNode(n as EnumNode, sb);
}
}
public void EmitClasses(Node root, StringBuilder sb)
{
sb.AppendLine("// Generated code");
sb.AppendLine("// DO NOT EDIT");
sb.AppendLine();
sb.AppendLine("package steamlang");
sb.AppendLine();
sb.AppendLine("import (");
sb.AppendLine(" \"io\"");
sb.AppendLine(" \"encoding/binary\"");
sb.AppendLine(" \"github.com/golang/protobuf/proto\"");
sb.AppendLine(" \"github.com/Philipp15b/go-steam/steamid\"");
sb.AppendLine(" \"github.com/Philipp15b/go-steam/rwu\"");
sb.AppendLine(" . \"github.com/Philipp15b/go-steam/internal/protobuf\"");
sb.AppendLine(")");
sb.AppendLine();
foreach (Node n in root.childNodes) {
EmitClassNode(n as ClassNode, sb);
}
}
private static string EmitSymbol(Symbol sym)
{
string s = null;
if (sym is WeakSymbol) {
s = (sym as WeakSymbol).Identifier;
} else if (sym is StrongSymbol) {
StrongSymbol ssym = sym as StrongSymbol;
if (ssym.Prop == null) {
s = ssym.Class.Name;
} else {
s = ssym.Class.Name + "_" + ssym.Prop.Name;
}
}
return s.Replace("ulong.MaxValue", "^uint64(0)").Replace("SteamKit2.Internal.", "").Replace("SteamKit2.GC.Internal.", "");
}
private static string EmitType(Symbol sym)
{
string type = EmitSymbol(sym);
return typeMap.ContainsKey(type) ? typeMap[type] : type;
}
private static string GetUpperName(string name)
{
return name.Substring(0, 1).ToUpper() + name.Remove(0, 1);
}
private void EmitEnumNode(EnumNode enode, StringBuilder sb)
{
string type = enode.Type != null ? EmitType(enode.Type) : "int32";
enumTypes.Add(enode.Name, type);
sb.AppendLine("type " + enode.Name + " " + type);
sb.AppendLine();
sb.AppendLine("const (");
bool first = true;
foreach (PropNode prop in enode.childNodes) {
string val = String.Join(" | ", prop.Default.Select(item => {
var name = EmitSymbol(item);
// if this is an element of this enum, make sure to prefix it with its name
return (enode.childNodes.Exists(node => node.Name == name) ? enode.Name + "_" : "") + name;
}));
sb.Append(" " + enode.Name + "_" + prop.Name + " " + enode.Name + " = " + val);
if (prop.Obsolete != null) {
if (prop.Obsolete.Length > 0)
sb.Append(" // Deprecated: " + prop.Obsolete);
else
sb.Append(" // Deprecated");
}
sb.AppendLine();
if (first)
first = false;
}
sb.AppendLine(")");
sb.AppendLine();
if (debug)
EmitEnumStringer(enode, sb);
}
private void EmitEnumStringer(EnumNode enode, StringBuilder sb)
{
sb.AppendLine("var " + enode.Name + "_name = map[" + enode.Name + "]string{");
// duplicate elements don't really make sense here, so we filter them
var uniqueNodes = new List<PropNode>();
{
var allValues = new List<long>();
foreach (var node in enode.childNodes) {
if (!(node is PropNode))
continue;
var prop = node as PropNode;
long val = EvalEnum(enode, prop);
if (allValues.Contains(val))
continue;
allValues.Add(val);
uniqueNodes.Add(prop);
}
}
foreach (PropNode prop in uniqueNodes) {
sb.Append(" " + EvalEnum(enode, prop) + ": ");
sb.AppendLine("\"" + enode.Name + "_" + prop.Name + "\",");
}
sb.AppendLine("}");
sb.AppendLine();
sb.AppendLine("func (e " + enode.Name + ") String() string {");
sb.AppendLine(" if s, ok := " + enode.Name + "_name[e]; ok {");
sb.AppendLine(" return s");
sb.AppendLine(" }");
sb.AppendLine(" var flags []string");
sb.AppendLine(" for k, v := range " + enode.Name + "_name {");
sb.AppendLine(" if e&k != 0 {");
sb.AppendLine(" flags = append(flags, v)");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" if len(flags) == 0 {");
sb.AppendLine(" return fmt.Sprintf(\"%d\", e)");
sb.AppendLine(" }");
sb.AppendLine(" sort.Strings(flags)");
sb.AppendLine(" return strings.Join(flags, \" | \")");
sb.AppendLine("}");
sb.AppendLine();
}
private long EvalEnum(EnumNode enode, PropNode prop)
{
long number = 0;
foreach (Symbol sym in prop.Default) {
long n = 0;
var val = (sym as WeakSymbol).Identifier;
if (new Regex("^[-0-9]+$|^0x[-0-9a-fA-F]+$").IsMatch(val)) {
int bas = 10;
if (val.StartsWith("0x", StringComparison.Ordinal)) {
bas = 16;
val = val.Substring(2);
}
n = Convert.ToInt64(val, bas);
} else {
var otherNode = enode.childNodes.Single(o => o is PropNode && (o as PropNode).Name == val) as PropNode;
n = EvalEnum(enode, otherNode);
}
number = number | n;
}
return number;
}
private void EmitClassNode(ClassNode cnode, StringBuilder sb)
{
EmitClassConstants(cnode, sb);
EmitClassDef(cnode, sb);
EmitClassConstructor(cnode, sb);
EmitClassEMsg(cnode, sb);
EmitClassSerializer(cnode, sb);
EmitClassDeserializer(cnode, sb);
}
private void EmitClassConstants(ClassNode cnode, StringBuilder sb)
{
Func<PropNode, string> emitElement = node => cnode.Name + "_" + node.Name + " " + EmitType(node.Type) + " = " + EmitType(node.Default.FirstOrDefault());
var statics = cnode.childNodes.Where(node => node is PropNode && (node as PropNode).Flags == "const");
if (statics.Count() == 1) {
sb.AppendLine("const " + emitElement(cnode.childNodes[0] as PropNode));
sb.AppendLine();
return;
}
bool first = true;
foreach (PropNode node in statics) {
if (first) {
sb.AppendLine("const (");
first = false;
}
sb.AppendLine(" " + emitElement(node));
}
if (!first) {
sb.AppendLine(")");
sb.AppendLine();
}
}
private void EmitClassDef(ClassNode cnode, StringBuilder sb)
{
sb.AppendLine("type " + cnode.Name + " struct {");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal" && EmitSymbol(node.Type) == "byte") {
sb.AppendLine(" " + GetUpperName(node.Name) + " bool");
} else if (node.Flags == "steamidmarshal" && EmitSymbol(node.Type) == "ulong") {
sb.AppendLine(" " + GetUpperName(node.Name) + " steamid.SteamId");
} else if (node.Flags == "proto") {
sb.AppendLine(" " + GetUpperName(node.Name) + " *" + EmitType(node.Type));
} else {
int arraySize;
string typestr = EmitType(node.Type);
if (!String.IsNullOrEmpty(node.FlagsOpt) && Int32.TryParse(node.FlagsOpt, out arraySize)) {
// TODO: use arrays instead of slices?
typestr = "[]" + typestr;
}
sb.AppendLine(" " + GetUpperName(node.Name) + " " + typestr);
}
}
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassConstructor(ClassNode cnode, StringBuilder sb)
{
sb.AppendLine("func New" + cnode.Name + "() *" + cnode.Name + " {");
sb.AppendLine(" return &" + cnode.Name + "{");
foreach (PropNode node in cnode.childNodes) {
string ctor = null;
Symbol firstDefault = node.Default.FirstOrDefault();
if (node.Flags == "const") {
continue;
} else if (node.Flags == "proto") {
ctor = "new(" + GetUpperName(EmitType(node.Type)) + ")";
} else if (firstDefault == null) {
// only arrays/slices need explicit initialization
if (String.IsNullOrEmpty(node.FlagsOpt))
continue;
ctor = "make([]" + EmitType(node.Type) + ", " + node.FlagsOpt + ", " + node.FlagsOpt + ")";
} else {
ctor = EmitSymbol(firstDefault);
}
sb.AppendLine(" " + GetUpperName(node.Name) + ": " + ctor + ",");
}
sb.AppendLine(" }");
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassEMsg(ClassNode cnode, StringBuilder sb)
{
if (cnode.Ident == null)
return;
string ident = EmitSymbol(cnode.Ident);
if (!ident.Contains("EMsg_"))
return;
sb.AppendLine("func (d *" + cnode.Name + ") GetEMsg() EMsg {");
sb.AppendLine(" return " + ident);
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassSerializer(ClassNode cnode, StringBuilder sb)
{
var nodeToBuf = new Dictionary<PropNode, string>();
int tempNum = 0;
sb.AppendLine("func (d *" + cnode.Name + ") Serialize(w io.Writer) error {");
sb.AppendLine(" var err error");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "proto") {
sb.AppendLine(" buf" + tempNum + ", err := proto.Marshal(d." + GetUpperName(node.Name) + ")");
sb.AppendLine(" if err != nil { return err }");
if (node.FlagsOpt != null) {
sb.AppendLine(" d." + GetUpperName(node.FlagsOpt) + " = int32(len(buf" + tempNum + "))");
}
nodeToBuf[node] = "buf" + tempNum;
tempNum++;
}
}
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal") {
sb.AppendLine(" err = rwu.WriteBool(w, d." + GetUpperName(node.Name) + ")");
} else if (node.Flags == "steamidmarshal") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
} else if (node.Flags == "protomask") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))");
} else if (node.Flags == "protomaskgc") {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, EMsg(uint32(d." + GetUpperName(node.Name) + ") | ProtoMask))");
} else if (node.Flags == "proto") {
sb.AppendLine(" _, err = w.Write(" + nodeToBuf[node] + ")");
} else {
sb.AppendLine(" err = binary.Write(w, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
}
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
}
sb.AppendLine(" return err");
sb.AppendLine("}");
sb.AppendLine();
}
private void EmitClassDeserializer(ClassNode cnode, StringBuilder sb)
{
int tempNum = 0;
sb.AppendLine("func (d *" + cnode.Name + ") Deserialize(r io.Reader) error {");
sb.AppendLine(" var err error");
foreach (PropNode node in cnode.childNodes) {
if (node.Flags == "const") {
continue;
} else if (node.Flags == "boolmarshal") {
sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.ReadBool(r)");
} else if (node.Flags == "steamidmarshal") {
sb.AppendLine(" t" + tempNum + ", err := rwu.ReadUint64(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = steamid.SteamId(t" + tempNum + ")");
tempNum++;
continue;
} else if (node.Flags == "protomask") {
string type = EmitType(node.Type);
if (enumTypes.ContainsKey(type))
type = enumTypes[type];
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(type) + "(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = EMsg(uint32(t" + tempNum + ") & EMsgMask)");
tempNum++;
continue;
} else if (node.Flags == "protomaskgc") {
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(EmitType(node.Type)) + "(r)");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = uint32(t" + tempNum + ") & EMsgMask");
tempNum++;
continue;
} else if (node.Flags == "proto") {
sb.AppendLine(" buf" + tempNum + " := make([]byte, d." + GetUpperName(node.FlagsOpt) + ", d." + GetUpperName(node.FlagsOpt) + ")");
sb.AppendLine(" _, err = io.ReadFull(r, buf" + tempNum + ")");
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" err = proto.Unmarshal(buf" + tempNum + ", d." + GetUpperName(node.Name) + ")");
tempNum++;
} else {
string type = EmitType(node.Type);
if (!String.IsNullOrEmpty(node.FlagsOpt)) {
sb.AppendLine(" err = binary.Read(r, binary.LittleEndian, d." + GetUpperName(node.Name) + ")");
} else if (!enumTypes.ContainsKey(type)) {
sb.AppendLine(" d." + GetUpperName(node.Name) + ", err = rwu.Read" + GetUpperName(type) + "(r)");
} else {
sb.AppendLine(" t" + tempNum + ", err := rwu.Read" + GetUpperName(enumTypes[type]) + "(r)");
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
sb.AppendLine(" d." + GetUpperName(node.Name) + " = " + type + "(t" + tempNum + ")");
tempNum++;
continue;
}
}
if (node != cnode.childNodes[cnode.childNodes.Count - 1])
sb.AppendLine(" if err != nil { return err }");
}
sb.AppendLine(" return err");
sb.AppendLine("}");
sb.AppendLine();
}
}
}
| |
using System;
using System.Collections.Generic;
using Htc.Vita.Core.Log;
namespace Htc.Vita.Core.Json
{
/// <summary>
/// Class JsonObject.
/// </summary>
public abstract class JsonObject
{
/// <summary>
/// Gets all the keys in JsonObject.
/// </summary>
/// <returns>ICollection<System.String>.</returns>
public ICollection<string> AllKeys()
{
ICollection<string> result = null;
try
{
result = OnAllKeys();
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result ?? new List<string>();
}
/// <summary>
/// Determines whether JsonObject has the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns><c>true</c> if JsonObject has the specified key ; otherwise, <c>false</c>.</returns>
public bool HasKey(string key)
{
var result = false;
try
{
result = OnHasKey(key);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the bool value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Boolean.</returns>
public bool ParseBool(string key)
{
return ParseBool(
key,
false
);
}
/// <summary>
/// Parses the bool value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Boolean.</returns>
public bool ParseBool(
string key,
bool defaultValue)
{
var result = defaultValue;
try
{
result = OnParseBool(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the bool if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Boolean.</returns>
public bool ParseBoolIfKeyExist(string key)
{
return ParseBoolIfKeyExist(
key,
false
);
}
/// <summary>
/// Parses the bool if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Boolean.</returns>
public bool ParseBoolIfKeyExist(
string key,
bool defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseBool(
key,
defaultValue
);
}
/// <summary>
/// Parses the double value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Double.</returns>
public double ParseDouble(string key)
{
return ParseDouble(
key,
0.0D
);
}
/// <summary>
/// Parses the double value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Double.</returns>
public double ParseDouble(
string key,
double defaultValue)
{
var result = defaultValue;
try
{
result = OnParseDouble(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the double value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>System.Double.</returns>
public double ParseDoubleIfKeyExists(string key)
{
return ParseDoubleIfKeyExists(
key,
0.0D
);
}
/// <summary>
/// Parses the double value if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Double.</returns>
public double ParseDoubleIfKeyExists(
string key,
double defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseDouble(
key,
defaultValue
);
}
/// <summary>
/// Parses the float value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Single.</returns>
public float ParseFloat(string key)
{
return ParseFloat(
key,
0.0F
);
}
/// <summary>
/// Parses the float value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Single.</returns>
public float ParseFloat(
string key,
float defaultValue)
{
var result = defaultValue;
try
{
result = OnParseFloat(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the float value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>System.Single.</returns>
public float ParseFloatIfKeyExists(string key)
{
return ParseFloatIfKeyExists(
key,
0.0F
);
}
/// <summary>
/// Parses the float value if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Single.</returns>
public float ParseFloatIfKeyExists(
string key,
float defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseFloat(
key,
defaultValue
);
}
/// <summary>
/// Parses the int value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Int32.</returns>
public int ParseInt(string key)
{
return ParseInt(
key,
0
);
}
/// <summary>
/// Parses the int value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int32.</returns>
public int ParseInt(
string key,
int defaultValue)
{
var result = defaultValue;
try
{
result = OnParseInt(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the int value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>System.Int32.</returns>
public int ParseIntIfKeyExists(string key)
{
return ParseIntIfKeyExists(
key,
0
);
}
/// <summary>
/// Parses the int value if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int32.</returns>
public int ParseIntIfKeyExists(
string key,
int defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseInt(
key,
defaultValue
);
}
/// <summary>
/// Parses the long value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Int64.</returns>
public long ParseLong(string key)
{
return ParseLong(
key,
0L
);
}
/// <summary>
/// Parses the long value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int64.</returns>
public long ParseLong(
string key,
long defaultValue)
{
var result = defaultValue;
try
{
result = OnParseLong(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the long value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>System.Int64.</returns>
public long ParseLongIfKeyExists(string key)
{
return ParseLongIfKeyExists(
key,
0L
);
}
/// <summary>
/// Parses the long value if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int64.</returns>
public long ParseLongIfKeyExists(
string key,
long defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseLong(
key,
defaultValue
);
}
/// <summary>
/// Parses the string value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.String.</returns>
public string ParseString(string key)
{
return ParseString(
key,
null
);
}
/// <summary>
/// Parses the string value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.String.</returns>
public string ParseString(
string key,
string defaultValue)
{
var result = defaultValue;
try
{
result = OnParseString(
key,
defaultValue
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the string value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>System.String.</returns>
public string ParseStringIfKeyExists(string key)
{
return ParseStringIfKeyExists(
key,
null
);
}
/// <summary>
/// Parses the string value if key exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.String.</returns>
public string ParseStringIfKeyExists(
string key,
string defaultValue)
{
if (!HasKey(key))
{
return defaultValue;
}
return ParseString(
key,
defaultValue
);
}
/// <summary>
/// Parses the URI value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Uri.</returns>
public Uri ParseUri(string key)
{
var data = ParseString(key);
if (string.IsNullOrWhiteSpace(data))
{
return null;
}
Uri result = null;
try
{
result = new Uri(data);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the URI value if key exists.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Uri.</returns>
public Uri ParseUriIfKeyExists(string key)
{
if (!HasKey(key))
{
return null;
}
return ParseUri(key);
}
/// <summary>
/// Parses the JsonArray value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>JsonArray.</returns>
public JsonArray ParseJsonArray(string key)
{
JsonArray result = null;
try
{
result = OnParseJsonArray(key);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the JsonArray value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>JsonArray.</returns>
public JsonArray ParseJsonArrayIfKeyExists(string key)
{
if (!HasKey(key))
{
return null;
}
return ParseJsonArray(key);
}
/// <summary>
/// Parses the JsonObject value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>JsonObject.</returns>
public JsonObject ParseJsonObject(string key)
{
JsonObject result = null;
try
{
result = OnParseJsonObject(key);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Parses the JsonObject value if key exist.
/// </summary>
/// <param name="key">The key if key exist.</param>
/// <returns>JsonArray.</returns>
public JsonObject ParseJsonObjectIfKeyExists(string key)
{
if (!HasKey(key))
{
return null;
}
return ParseJsonObject(key);
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
bool value)
{
var result = this;
try
{
result = OnPutBool(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
double value)
{
var result = this;
try
{
result = OnPutDouble(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
float value)
{
var result = this;
try
{
result = OnPutFloat(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
int value)
{
var result = this;
try
{
result = OnPutInt(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
long value)
{
var result = this;
try
{
result = OnPutLong(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
string value)
{
var result = this;
try
{
result = OnPutString(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
JsonArray value)
{
var result = this;
try
{
result = OnPutJsonArray(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject Put(
string key,
JsonObject value)
{
var result = this;
try
{
result = OnPutJsonObject(
key,
value
);
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Puts the value if it is not null.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNull(
string key,
string value)
{
if (value == null)
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Puts the value if it is not null.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNull(
string key,
JsonArray value)
{
if (value == null)
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Puts the value if it is not null.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNull(
string key,
JsonObject value)
{
if (value == null)
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Puts the value if it is not null and not white space.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNullAndNotWhiteSpace(
string key,
string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Puts the value if it is not null and not empty.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNullAndNotEmpty(
string key,
JsonArray value)
{
if (value == null)
{
return this;
}
if (value.Size() <= 0)
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Puts the value if it is not null and not empty.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
public JsonObject PutIfNotNullAndNotEmpty(
string key,
JsonObject value)
{
if (value == null)
{
return this;
}
if (value.AllKeys().Count <= 0)
{
return this;
}
return Put(
key,
value
);
}
/// <summary>
/// Converts to pretty-print string.
/// </summary>
/// <returns>System.String.</returns>
public string ToPrettyString()
{
var result = string.Empty;
try
{
result = OnToPrettyString();
result = result?.Trim() ?? string.Empty;
}
catch (Exception e)
{
Logger.GetInstance(typeof(JsonObject)).Error(e.ToString());
}
return result;
}
/// <summary>
/// Called when getting all the keys in JsonObject.
/// </summary>
/// <returns>ICollection<System.String>.</returns>
protected abstract ICollection<string> OnAllKeys();
/// <summary>
/// Called when determining whether JsonObject has the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns><c>true</c> if JsonObject has the specified key ; otherwise, <c>false</c>.</returns>
protected abstract bool OnHasKey(string key);
/// <summary>
/// Called when parsing the bool value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Boolean.</returns>
protected abstract bool OnParseBool(
string key,
bool defaultValue
);
/// <summary>
/// Called when parsing the double value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Double.</returns>
protected abstract double OnParseDouble(
string key,
double defaultValue
);
/// <summary>
/// Called when parsing the float value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Single.</returns>
protected abstract float OnParseFloat(
string key,
float defaultValue
);
/// <summary>
/// Called when parsing the int value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int32.</returns>
protected abstract int OnParseInt(
string key,
int defaultValue
);
/// <summary>
/// Called when parsing the long value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.Int64.</returns>
protected abstract long OnParseLong(
string key,
long defaultValue
);
/// <summary>
/// Called when parsing the string value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>System.String.</returns>
protected abstract string OnParseString(
string key,
string defaultValue
);
/// <summary>
/// Called when parsing the JsonArray value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>JsonArray.</returns>
protected abstract JsonArray OnParseJsonArray(string key);
/// <summary>
/// Called when parsing the JsonObject value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnParseJsonObject(string key);
/// <summary>
/// Called when putting the bool value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutBool(
string key,
bool value
);
/// <summary>
/// Called when putting the double value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutDouble(
string key,
double value
);
/// <summary>
/// Called when putting the float value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutFloat(
string key,
float value
);
/// <summary>
/// Called when putting the int value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutInt(
string key,
int value
);
/// <summary>
/// Called when putting the long value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutLong(
string key,
long value
);
/// <summary>
/// Called when putting the string value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutString(
string key,
string value
);
/// <summary>
/// Called when putting the JsonArray value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutJsonArray(
string key,
JsonArray value
);
/// <summary>
/// Called when putting the JsonObject value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>JsonObject.</returns>
protected abstract JsonObject OnPutJsonObject(
string key,
JsonObject value
);
/// <summary>
/// Called when converting to pretty-print string.
/// </summary>
/// <returns>System.String.</returns>
protected abstract string OnToPrettyString();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.Administration.Logs;
using Content.Server.Body.Components;
using Content.Server.Body.Systems;
using Content.Server.Chemistry.Components;
using Content.Server.Chemistry.EntitySystems;
using Content.Server.Cooldown;
using Content.Server.Weapon.Melee.Components;
using Content.Shared.Damage;
using Content.Shared.Sound;
using Content.Shared.Audio;
using Content.Shared.Database;
using Content.Shared.Hands;
using Content.Shared.Interaction;
using Content.Shared.Physics;
using Content.Shared.Weapons.Melee;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Player;
using Robust.Shared.Timing;
namespace Content.Server.Weapon.Melee
{
public sealed class MeleeWeaponSystem : EntitySystem
{
[Dependency] private IGameTiming _gameTiming = default!;
[Dependency] private readonly DamageableSystem _damageableSystem = default!;
[Dependency] private SolutionContainerSystem _solutionsSystem = default!;
[Dependency] private readonly AdminLogSystem _logSystem = default!;
[Dependency] private readonly BloodstreamSystem _bloodstreamSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<MeleeWeaponComponent, HandSelectedEvent>(OnHandSelected);
SubscribeLocalEvent<MeleeWeaponComponent, ClickAttackEvent>(OnClickAttack);
SubscribeLocalEvent<MeleeWeaponComponent, WideAttackEvent>(OnWideAttack);
SubscribeLocalEvent<MeleeWeaponComponent, AfterInteractEvent>(OnAfterInteract);
SubscribeLocalEvent<MeleeChemicalInjectorComponent, MeleeHitEvent>(OnChemicalInjectorHit);
}
private void OnHandSelected(EntityUid uid, MeleeWeaponComponent comp, HandSelectedEvent args)
{
var curTime = _gameTiming.CurTime;
var cool = TimeSpan.FromSeconds(comp.CooldownTime * 0.5f);
if (curTime < comp.CooldownEnd)
{
if (comp.CooldownEnd - curTime < cool)
{
comp.LastAttackTime = curTime;
comp.CooldownEnd += cool;
}
else
return;
}
else
{
comp.LastAttackTime = curTime;
comp.CooldownEnd = curTime + cool;
}
RaiseLocalEvent(uid, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false);
}
private void OnClickAttack(EntityUid owner, MeleeWeaponComponent comp, ClickAttackEvent args)
{
args.Handled = true;
var curTime = _gameTiming.CurTime;
if (curTime < comp.CooldownEnd || args.Target == null)
return;
var location = EntityManager.GetComponent<TransformComponent>(args.User).Coordinates;
var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager);
var angle = Angle.FromWorldVec(diff);
if (args.Target is {Valid: true} target)
{
// Raise event before doing damage so we can cancel damage if the event is handled
var hitEvent = new MeleeHitEvent(new List<EntityUid>() { target }, args.User);
RaiseLocalEvent(owner, hitEvent, false);
if (!hitEvent.Handled)
{
var targets = new[] { target };
SendAnimation(comp.ClickArc, angle, args.User, owner, targets, comp.ClickAttackEffect, false);
RaiseLocalEvent(target, new AttackedEvent(args.Used, args.User, args.ClickLocation));
var modifiedDamage = DamageSpecifier.ApplyModifierSets(comp.Damage + hitEvent.BonusDamage, hitEvent.ModifiersList);
var damageResult = _damageableSystem.TryChangeDamage(target, modifiedDamage);
if (damageResult != null)
{
if (args.Used == args.User)
_logSystem.Add(LogType.MeleeHit,
$"{ToPrettyString(args.User):user} melee attacked {ToPrettyString(args.Target.Value):target} using their hands and dealt {damageResult.Total:damage} damage");
else
_logSystem.Add(LogType.MeleeHit,
$"{ToPrettyString(args.User):user} melee attacked {ToPrettyString(args.Target.Value):target} using {ToPrettyString(args.Used):used} and dealt {damageResult.Total:damage} damage");
}
if (hitEvent.HitSoundOverride != null)
{
SoundSystem.Play(Filter.Pvs(owner), hitEvent.HitSoundOverride.GetSound(), target, AudioHelpers.WithVariation(0.25f));
}
else
{
SoundSystem.Play(Filter.Pvs(owner), comp.HitSound.GetSound(), target);
}
}
}
else
{
SoundSystem.Play(Filter.Pvs(owner), comp.MissSound.GetSound(), args.User);
return;
}
comp.LastAttackTime = curTime;
comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.CooldownTime);
RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false);
}
private void OnWideAttack(EntityUid owner, MeleeWeaponComponent comp, WideAttackEvent args)
{
args.Handled = true;
var curTime = _gameTiming.CurTime;
if (curTime < comp.CooldownEnd)
{
return;
}
var location = EntityManager.GetComponent<TransformComponent>(args.User).Coordinates;
var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager);
var angle = Angle.FromWorldVec(diff);
// This should really be improved. GetEntitiesInArc uses pos instead of bounding boxes.
var entities = ArcRayCast(EntityManager.GetComponent<TransformComponent>(args.User).WorldPosition, angle, comp.ArcWidth, comp.Range, EntityManager.GetComponent<TransformComponent>(owner).MapID, args.User);
var hitEntities = new List<EntityUid>();
foreach (var entity in entities)
{
if (entity.IsInContainer() || entity == args.User)
continue;
if (EntityManager.HasComponent<DamageableComponent>(entity))
{
hitEntities.Add(entity);
}
}
// Raise event before doing damage so we can cancel damage if handled
var hitEvent = new MeleeHitEvent(hitEntities, args.User);
RaiseLocalEvent(owner, hitEvent, false);
SendAnimation(comp.Arc, angle, args.User, owner, hitEntities);
if (!hitEvent.Handled)
{
if (entities.Count != 0)
{
if (hitEvent.HitSoundOverride != null)
{
SoundSystem.Play(Filter.Pvs(owner), hitEvent.HitSoundOverride.GetSound(), Transform(entities.First()).Coordinates);
}
else
{
SoundSystem.Play(Filter.Pvs(owner), comp.HitSound.GetSound(), Transform(entities.First()).Coordinates);
}
}
else
{
SoundSystem.Play(Filter.Pvs(owner), comp.MissSound.GetSound(), Transform(args.User).Coordinates);
}
var modifiedDamage = DamageSpecifier.ApplyModifierSets(comp.Damage + hitEvent.BonusDamage, hitEvent.ModifiersList);
foreach (var entity in hitEntities)
{
RaiseLocalEvent(entity, new AttackedEvent(args.Used, args.User, args.ClickLocation));
var damageResult = _damageableSystem.TryChangeDamage(entity, modifiedDamage);
if (damageResult != null)
{
if (args.Used == args.User)
_logSystem.Add(LogType.MeleeHit,
$"{ToPrettyString(args.User):user} melee attacked {ToPrettyString(entity):target} using their hands and dealt {damageResult.Total:damage} damage");
else
_logSystem.Add(LogType.MeleeHit,
$"{ToPrettyString(args.User):user} melee attacked {ToPrettyString(entity):target} using {ToPrettyString(args.Used):used} and dealt {damageResult.Total:damage} damage");
}
}
}
comp.LastAttackTime = curTime;
comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.ArcCooldownTime);
RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false);
}
/// <summary>
/// Used for melee weapons that want some behavior on AfterInteract,
/// but also want the cooldown (stun batons, flashes)
/// </summary>
private void OnAfterInteract(EntityUid owner, MeleeWeaponComponent comp, AfterInteractEvent args)
{
if (args.Handled || !args.CanReach)
return;
var curTime = _gameTiming.CurTime;
if (curTime < comp.CooldownEnd)
{
return;
}
if (!args.Target.HasValue)
return;
var location = EntityManager.GetComponent<TransformComponent>(args.User).Coordinates;
var diff = args.ClickLocation.ToMapPos(EntityManager) - location.ToMapPos(EntityManager);
var angle = Angle.FromWorldVec(diff);
var hitEvent = new MeleeInteractEvent(args.Target.Value, args.User);
RaiseLocalEvent(owner, hitEvent, false);
if (!hitEvent.CanInteract) return;
SendAnimation(comp.ClickArc, angle, args.User, owner, new List<EntityUid>() { args.Target.Value }, comp.ClickAttackEffect, false);
comp.LastAttackTime = curTime;
comp.CooldownEnd = comp.LastAttackTime + TimeSpan.FromSeconds(comp.CooldownTime);
RaiseLocalEvent(owner, new RefreshItemCooldownEvent(comp.LastAttackTime, comp.CooldownEnd), false);
}
private HashSet<EntityUid> ArcRayCast(Vector2 position, Angle angle, float arcWidth, float range, MapId mapId, EntityUid ignore)
{
var widthRad = Angle.FromDegrees(arcWidth);
var increments = 1 + 35 * (int) Math.Ceiling(widthRad / (2 * Math.PI));
var increment = widthRad / increments;
var baseAngle = angle - widthRad / 2;
var resSet = new HashSet<EntityUid>();
for (var i = 0; i < increments; i++)
{
var castAngle = new Angle(baseAngle + increment * i);
var res = Get<SharedPhysicsSystem>().IntersectRay(mapId,
new CollisionRay(position, castAngle.ToWorldVec(),
(int) (CollisionGroup.Impassable | CollisionGroup.MobImpassable)), range, ignore).ToList();
if (res.Count != 0)
{
resSet.Add(res[0].HitEntity);
}
}
return resSet;
}
private void OnChemicalInjectorHit(EntityUid owner, MeleeChemicalInjectorComponent comp, MeleeHitEvent args)
{
if (!_solutionsSystem.TryGetInjectableSolution(owner, out var solutionContainer))
return;
var hitBloodstreams = new List<BloodstreamComponent>();
foreach (var entity in args.HitEntities)
{
if (Deleted(entity))
continue;
if (EntityManager.TryGetComponent<BloodstreamComponent?>(entity, out var bloodstream))
hitBloodstreams.Add(bloodstream);
}
if (hitBloodstreams.Count < 1)
return;
var removedSolution = solutionContainer.SplitSolution(comp.TransferAmount * hitBloodstreams.Count);
var removedVol = removedSolution.TotalVolume;
var solutionToInject = removedSolution.SplitSolution(removedVol * comp.TransferEfficiency);
var volPerBloodstream = solutionToInject.TotalVolume * (1 / hitBloodstreams.Count);
foreach (var bloodstream in hitBloodstreams)
{
var individualInjection = solutionToInject.SplitSolution(volPerBloodstream);
_bloodstreamSystem.TryAddToChemicals((bloodstream).Owner, individualInjection, bloodstream);
}
}
public void SendAnimation(string arc, Angle angle, EntityUid attacker, EntityUid source, IEnumerable<EntityUid> hits, bool textureEffect = false, bool arcFollowAttacker = true)
{
RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayMeleeWeaponAnimationMessage(arc, angle, attacker, source,
hits.Select(e => e).ToList(), textureEffect, arcFollowAttacker), Filter.Pvs(source, 1f));
}
public void SendLunge(Angle angle, EntityUid source)
{
RaiseNetworkEvent(new MeleeWeaponSystemMessages.PlayLungeAnimationMessage(angle, source), Filter.Pvs(source, 1f));
}
}
/// <summary>
/// Raised directed on the melee weapon entity used to attack something in combat mode,
/// whether through a click attack or wide attack.
/// </summary>
public sealed class MeleeHitEvent : HandledEntityEventArgs
{
/// <summary>
/// Modifier sets to apply to the hit event when it's all said and done.
/// This should be modified by adding a new entry to the list.
/// </summary>
public List<DamageModifierSet> ModifiersList = new();
/// <summary>
/// Damage to add to the default melee weapon damage. Applied before modifiers.
/// </summary>
/// <remarks>
/// This might be required as damage modifier sets cannot add a new damage type to a DamageSpecifier.
/// </remarks>
public DamageSpecifier BonusDamage = new();
/// <summary>
/// A list containing every hit entity. Can be zero.
/// </summary>
public IEnumerable<EntityUid> HitEntities { get; }
/// <summary>
/// Used to define a new hit sound in case you want to override the default GenericHit.
/// Also gets a pitch modifier added to it.
/// </summary>
public SoundSpecifier? HitSoundOverride {get; set;}
/// <summary>
/// The user who attacked with the melee weapon.
/// </summary>
public EntityUid User { get; }
public MeleeHitEvent(List<EntityUid> hitEntities, EntityUid user)
{
HitEntities = hitEntities;
User = user;
}
}
/// <summary>
/// Raised directed on the melee weapon entity used to attack something in combat mode,
/// whether through a click attack or wide attack.
/// </summary>
public sealed class MeleeInteractEvent : EntityEventArgs
{
/// <summary>
/// The entity interacted with.
/// </summary>
public EntityUid Entity { get; }
/// <summary>
/// The user who interacted using the melee weapon.
/// </summary>
public EntityUid User { get; }
/// <summary>
/// Modified by the event handler to specify whether they could successfully interact with the entity.
/// Used to know whether to send the hit animation or not.
/// </summary>
public bool CanInteract { get; set; } = false;
public MeleeInteractEvent(EntityUid entity, EntityUid user)
{
Entity = entity;
User = user;
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation object for a file in a project
/// </summary>
[ComVisible(true)]
public class OAFileItem : OAProjectItem
{
#region ctors
internal OAFileItem(OAProject project, FileNode node)
: base(project, node)
{
}
#endregion
private new FileNode Node => (FileNode)base.Node;
public override string Name
{
get
{
return this.Node.FileName;
}
set
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() => base.Name = value);
}
}
#region overridden methods
/// <summary>
/// Returns the dirty state of the document.
/// </summary>
/// <exception cref="InvalidOperationException">Is thrown if the project is closed or it the service provider attached to the project is invalid.</exception>
/// <exception cref="ComException">Is thrown if the dirty state cannot be retrived.</exception>
public override bool IsDirty
{
get
{
CheckProjectIsValid();
var isDirty = false;
using (var scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
var manager = this.Node.GetDocumentManager();
Utilities.CheckNotNull(manager);
isDirty = manager.IsDirty;
});
}
return isDirty;
}
}
/// <summary>
/// Gets the Document associated with the item, if one exists.
/// </summary>
public override EnvDTE.Document Document
{
get
{
CheckProjectIsValid();
EnvDTE.Document document = null;
using (var scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
IVsUIHierarchy hier;
uint itemid;
IVsWindowFrame windowFrame;
VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, VSConstants.LOGVIEWID_Any, out hier, out itemid, out windowFrame);
if (windowFrame != null)
{
object var;
ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var));
object documentAsObject;
ErrorHandler.ThrowOnFailure(scope.Extensibility.GetDocumentFromDocCookie((int)var, out documentAsObject));
Utilities.CheckNotNull(documentAsObject);
document = (Document)documentAsObject;
}
});
}
return document;
}
}
/// <summary>
/// Opens the file item in the specified view.
/// </summary>
/// <param name="ViewKind">Specifies the view kind in which to open the item (file)</param>
/// <returns>Window object</returns>
public override EnvDTE.Window Open(string viewKind)
{
CheckProjectIsValid();
IVsWindowFrame windowFrame = null;
var docData = IntPtr.Zero;
using (var scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
try
{
// Validate input params
var logicalViewGuid = VSConstants.LOGVIEWID_Primary;
try
{
if (!(string.IsNullOrEmpty(viewKind)))
{
logicalViewGuid = new Guid(viewKind);
}
}
catch (FormatException)
{
// Not a valid guid
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid), "viewKind");
}
uint itemid;
IVsHierarchy ivsHierarchy;
uint docCookie;
var rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt == null)
{
throw new InvalidOperationException("Could not get running document table from the services exposed by this project");
}
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.Node.Url, out ivsHierarchy, out itemid, out docData, out docCookie));
// Open the file using the IVsProject interface
// We get the outer hierarchy so that projects can customize opening.
var project = this.Node.ProjectMgr.GetOuterInterface<IVsProject>();
ErrorHandler.ThrowOnFailure(project.OpenItem(this.Node.ID, ref logicalViewGuid, docData, out windowFrame));
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
}
});
}
// Get the automation object and return it
return ((windowFrame != null) ? VsShellUtilities.GetWindowObject(windowFrame) : null);
}
/// <summary>
/// Saves the project item.
/// </summary>
/// <param name="fileName">The name with which to save the project or project item.</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public override void Save(string fileName)
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
this.DoSave(false, fileName);
});
}
/// <summary>
/// Saves the project item.
/// </summary>
/// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param>
/// <returns>true if the rename was successful. False if Save as failes</returns>
public override bool SaveAs(string fileName)
{
try
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
this.DoSave(true, fileName);
});
}
catch (InvalidOperationException)
{
return false;
}
catch (COMException)
{
return false;
}
return true;
}
/// <summary>
/// Gets a value indicating whether the project item is open in a particular view type.
/// </summary>
/// <param name="viewKind">A Constants.vsViewKind* indicating the type of view to check./param>
/// <returns>A Boolean value indicating true if the project is open in the given view type; false if not. </returns>
public override bool get_IsOpen(string viewKind)
{
CheckProjectIsValid();
// Validate input params
var logicalViewGuid = VSConstants.LOGVIEWID_Primary;
try
{
if (!(string.IsNullOrEmpty(viewKind)))
{
logicalViewGuid = new Guid(viewKind);
}
}
catch (FormatException)
{
// Not a valid guid
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid), "viewKind");
}
var isOpen = false;
using (var scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
IVsUIHierarchy hier;
uint itemid;
IVsWindowFrame windowFrame;
isOpen = VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, logicalViewGuid, out hier, out itemid, out windowFrame);
});
}
return isOpen;
}
/// <summary>
/// Gets the ProjectItems for the object.
/// </summary>
public override ProjectItems ProjectItems
{
get
{
return this.Node.ProjectMgr.Site.GetUIThread().Invoke<ProjectItems>(() =>
{
if (this.Project.ProjectNode.CanFileNodesHaveChilds)
{
return new OAProjectItems(this.Project, this.Node);
}
else
{
return base.ProjectItems;
}
});
}
}
#endregion
#region helpers
/// <summary>
/// Saves or Save As the file
/// </summary>
/// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
/// <param name="fileName">The name of the project file.</param>
private void DoSave(bool isCalledFromSaveAs, string fileName)
{
Utilities.ArgumentNotNull("fileName", fileName);
CheckProjectIsValid();
using (var scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.Node.ProjectMgr.Site.GetUIThread().Invoke(() =>
{
var docData = IntPtr.Zero;
try
{
var rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt == null)
{
throw new InvalidOperationException("Could not get running document table from the services exposed by this project");
}
// First we see if someone else has opened the requested view of the file.
uint itemid;
IVsHierarchy ivsHierarchy;
uint docCookie;
int canceled;
var url = this.Node.Url;
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out ivsHierarchy, out itemid, out docData, out docCookie));
// If an empty file name is passed in for Save then make the file name the project name.
if (!isCalledFromSaveAs && fileName.Length == 0)
{
ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, url, this.Node.ID, docData, out canceled));
}
else
{
Utilities.ValidateFileName(this.Node.ProjectMgr.Site, fileName);
// Compute the fullpath from the directory of the existing Url.
var fullPath = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(url), fileName);
if (!isCalledFromSaveAs)
{
if (!CommonUtils.IsSamePath(this.Node.Url, fullPath))
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled));
}
else
{
ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled));
}
}
if (canceled == 1)
{
throw new InvalidOperationException();
}
}
catch (COMException e)
{
throw new InvalidOperationException(e.Message);
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
}
});
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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.Text;
namespace AmplitudeNS.MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
return int.Parse(number);
}
return float.Parse(number);
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// Internal wrapper for third-party adapters (PSPropertyAdapter)
/// </summary>
internal class ThirdPartyAdapter : PropertyOnlyAdapter
{
internal ThirdPartyAdapter(Type adaptedType, PSPropertyAdapter externalAdapter)
{
AdaptedType = adaptedType;
_externalAdapter = externalAdapter;
}
/// <summary>
/// The type this instance is adapting.
/// </summary>
internal Type AdaptedType { get; }
/// <summary>
/// The type of the external adapter.
/// </summary>
internal Type ExternalAdapterType
{
get
{
return _externalAdapter.GetType();
}
}
/// <summary>
/// Returns the TypeNameHierarchy out of an object.
/// </summary>
protected override IEnumerable<string> GetTypeNameHierarchy(object obj)
{
Collection<string> typeNameHierarchy = null;
try
{
typeNameHierarchy = _externalAdapter.GetTypeNameHierarchy(obj);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetTypeNameHierarchyError",
exception,
ExtendedTypeSystem.GetTypeNameHierarchyError, obj.ToString());
}
if (typeNameHierarchy == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetTypeNameHierarchy");
}
return typeNameHierarchy;
}
/// <summary>
/// Retrieves all the properties available in the object.
/// </summary>
protected override void DoAddAllProperties<T>(object obj, PSMemberInfoInternalCollection<T> members)
{
Collection<PSAdaptedProperty> properties = null;
try
{
properties = _externalAdapter.GetProperties(obj);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperties",
exception,
ExtendedTypeSystem.GetProperties, obj.ToString());
}
if (properties == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetProperties");
}
foreach (PSAdaptedProperty property in properties)
{
InitializeProperty(property, obj);
members.Add(property as T);
}
}
/// <summary>
/// Returns null if propertyName is not a property in the adapter or
/// the corresponding PSProperty with its adapterData set to information
/// to be used when retrieving the property.
/// </summary>
protected override PSProperty DoGetProperty(object obj, string propertyName)
{
PSAdaptedProperty property = null;
try
{
property = _externalAdapter.GetProperty(obj, propertyName);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperty",
exception,
ExtendedTypeSystem.GetProperty, propertyName, obj.ToString());
}
if (property != null)
{
InitializeProperty(property, obj);
}
return property;
}
protected override PSProperty DoGetFirstPropertyOrDefault(object obj, MemberNamePredicate predicate)
{
PSAdaptedProperty property = null;
try
{
property = _externalAdapter.GetFirstPropertyOrDefault(obj, predicate);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperty",
exception,
ExtendedTypeSystem.GetProperty, nameof(predicate), obj.ToString());
}
if (property != null)
{
InitializeProperty(property, obj);
}
return property;
}
/// <summary>
/// Ensures that the adapter and base object are set in the given PSAdaptedProperty.
/// </summary>
private void InitializeProperty(PSAdaptedProperty property, object baseObject)
{
if (property.adapter == null)
{
property.adapter = this;
property.baseObject = baseObject;
}
}
/// <summary>
/// Returns true if the property is settable.
/// </summary>
protected override bool PropertyIsSettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsSettable(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsSettableError",
exception,
ExtendedTypeSystem.PropertyIsSettableError, property.Name);
}
}
/// <summary>
/// Returns true if the property is gettable.
/// </summary>
protected override bool PropertyIsGettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsGettable(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsGettableError",
exception,
ExtendedTypeSystem.PropertyIsGettableError, property.Name);
}
}
/// <summary>
/// Returns the value from a property coming from a previous call to DoGetProperty.
/// </summary>
protected override object PropertyGet(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.GetPropertyValue(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyGetError",
exception,
ExtendedTypeSystem.PropertyGetError, property.Name);
}
}
/// <summary>
/// Sets the value of a property coming from a previous call to DoGetProperty.
/// </summary>
protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
_externalAdapter.SetPropertyValue(adaptedProperty, setValue);
}
catch (SetValueException) { throw; }
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertySetError",
exception,
ExtendedTypeSystem.PropertySetError, property.Name);
}
}
/// <summary>
/// Returns the name of the type corresponding to the property.
/// </summary>
protected override string PropertyType(PSProperty property, bool forDisplay)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
string propertyTypeName = null;
try
{
propertyTypeName = _externalAdapter.GetPropertyTypeName(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyTypeError",
exception,
ExtendedTypeSystem.PropertyTypeError, property.Name);
}
return propertyTypeName ?? "System.Object";
}
private readonly PSPropertyAdapter _externalAdapter;
}
/// <summary>
/// User-defined property adapter.
/// </summary>
/// <remarks>
/// This class is used to expose a simplified version of the type adapter API
/// </remarks>
public abstract class PSPropertyAdapter
{
/// <summary>
/// Returns the type hierarchy for the given object.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public virtual Collection<string> GetTypeNameHierarchy(object baseObject)
{
if (baseObject == null)
{
throw new ArgumentNullException(nameof(baseObject));
}
Collection<string> types = new Collection<string>();
for (Type type = baseObject.GetType(); type != null; type = type.BaseType)
{
types.Add(type.FullName);
}
return types;
}
/// <summary>
/// Returns a list of the adapted properties.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract Collection<PSAdaptedProperty> GetProperties(object baseObject);
/// <summary>
/// Returns a specific property, or null if the base object does not contain the given property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract PSAdaptedProperty GetProperty(object baseObject, string propertyName);
/// <summary>
/// Returns true if the given property is settable.
/// </summary>
public abstract bool IsSettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns true if the given property is gettable.
/// </summary>
public abstract bool IsGettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns the value of a given property.
/// </summary>
public abstract object GetPropertyValue(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Sets the value of a given property.
/// </summary>
public abstract void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value);
/// <summary>
/// Returns the type for a given property.
/// </summary>
public abstract string GetPropertyTypeName(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns a property if it's name matches the specified <see cref="MemberNamePredicate"/>, otherwise null.
/// </summary>
/// <returns>An adapted property if the predicate matches, or <see langword="null"/>.</returns>
public virtual PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, MemberNamePredicate predicate)
{
foreach (var property in GetProperties(baseObject))
{
if (predicate(property.Name))
{
return property;
}
}
return null;
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using Google.GData.Client;
namespace Google.GData.Documents
{
/// <summary>
/// A subclass of FeedQuery, to create an Documents query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
///
/// Documents List supports the following standard GData query parameters:
/// alt, author, q, start-index, max-results, updated-min, updated-max, /category
/// For more information about the standard parameters, see the GData protocol reference document.
/// In addition to the standard GData query parameters, the Documents List data API uses the following parameters.
/// Parameter Meaning
/// title Specifies the search terms for the title of a document.
/// This parameter used without title-exact will only submit partial queries, not exact queries.
///
/// title-exact Specifies whether the title query should be taken as an exact string.
/// Meaningless without title. Possible values are true and false.
///
/// The Documents List data API supports the following categories.
/// Category: Document Type
/// Scheme: http://schemas.google.com/g/2005#kind
/// Term: http://schemas.google.com/docs/2007#type
/// Label: type
/// All documents of the corresponding type in the requesting users document list.
/// Type is currently one of (document|spreadsheet|presentation)
/// Category: Starred Status
/// Scheme: http://schemas.google.com/g/2005/labels
/// Term: starred
/// Label: starred
/// All documents that have been starred by the requesting user
/// Category: Containing Folders
/// Scheme: http://schemas.google.com/docs/2007/folders/user-email
/// Term: folder-id
/// Label: folder-name
/// All documents inside the given folder for the requesting user
/// </summary>
public class DocumentsListQuery : FeedQuery
{
/// <summary>
/// document feed base URI
/// </summary>
public static string documentsBaseUri = "https://docs.google.com/feeds/default/private/full";
/// <summary>
/// document feed base URI with ACLs
/// </summary>
public static string documentsAclUri = "https://docs.google.com/feeds/default/private/expandAcl";
/// <summary>
/// template to construct a folder URI for a folder ID
/// </summary>
public static string foldersUriTemplate = "https://docs.google.com/feeds/default/private/full/{0}/contents";
/// <summary>
/// template to get the ACLs for a resourceID
/// </summary>
public static string aclsUriTemplate = "https://docs.google.com/feeds/default/private/full/{0}/acl";
/// <summary>
/// template to get the media for a resourceID
/// </summary>
public static string mediaUriTemplate = "https://docs.google.com/feeds/default/media/{0}";
/// <summary>
/// uri to get you all folders
/// </summary>
public static string allFoldersUri = "https://docs.google.com/feeds/default/private/full/-/folder";
/// <summary>
/// template to access the changes feed
/// </summary>
public static string allChangesTemplate = "https://docs.google.com/feeds/{0}/private/changes";
/// <summary>
/// template to access the metadata feed
/// </summary>
public static string metadataTemplate = "https://docs.google.com/feeds/metadata/{0}";
/// <summary>
/// template to get a revision for a given resourceID and revisionID
/// </summary>
public static string revisionsUriTemplate =
"https://docs.google.com/feeds/default/private/full/{0}/revisions/{1}";
/// <summary>
/// URI to access the archive feed
/// </summary>
public static string archiveUri = "https://docs.google.com/feeds/default/private/archive";
/// <summary>
/// predefined query category for documents
/// </summary>
public static QueryCategory DOCUMENTS = new QueryCategory(new AtomCategory("document"));
/// <summary>
/// predefined query category for spreadsheets
/// </summary>
public static QueryCategory SPREADSHEETS = new QueryCategory(new AtomCategory("spreadsheet"));
/// <summary>
/// predefined query category for presentations
/// </summary>
public static QueryCategory PRESENTATIONS = new QueryCategory(new AtomCategory("presentation"));
/// <summary>
/// predefined query category for drawings
/// </summary>
public static QueryCategory DRAWINGS = new QueryCategory(new AtomCategory("drawing"));
/// <summary>
/// predefined query category for PDFS
/// </summary>
public static QueryCategory PDFS = new QueryCategory(new AtomCategory("pdf"));
/// <summary>
/// predefined query category for Forms
/// </summary>
public static QueryCategory FORMS = new QueryCategory(new AtomCategory("form"));
/// <summary>
/// predefined query category for starred documents
/// </summary>
public static QueryCategory STARRED = new QueryCategory(new AtomCategory("starred"));
/// <summary>
/// predefined query category for starred documents
/// </summary>
public static QueryCategory VIEWED = new QueryCategory(new AtomCategory("viewed"));
/// <summary>
/// predefined query category for hidden documents
/// </summary>
public static QueryCategory HIDDEN = new QueryCategory(new AtomCategory("hidden"));
/// <summary>
/// predefined query category for trashed documents
/// </summary>
public static QueryCategory TRASHED = new QueryCategory(new AtomCategory("trashed"));
/// <summary>
/// predefined query category for user owned documents
/// </summary>
public static QueryCategory MINE = new QueryCategory(new AtomCategory("mine"));
/// <summary>
/// predefined query category for private documents
/// </summary>
public static QueryCategory PRIVATE = new QueryCategory(new AtomCategory("private"));
/// <summary>
/// predefined query category for shared documents
/// </summary>
public static QueryCategory SHARED = new QueryCategory(new AtomCategory("shared-with-domain"));
//Local variable to hold if the root collection should be shown in the feed.
//Local variable to hold the contents of a title query
//Local variable to hold if the title query we are doing should be exact.
/// <summary>
/// base constructor
/// </summary>
public DocumentsListQuery()
: base(documentsBaseUri)
{
CategoryQueriesAsParameter = true;
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public DocumentsListQuery(string queryUri)
: base(queryUri)
{
CategoryQueriesAsParameter = true;
}
/// <summary>Doclist does not support index based paging</returns>
[Obsolete("Index based paging is not supported on DocumentsList")]
public override int StartIndex
{
get { return 0; }
set { }
}
/// <summary>
/// Restricts the results to only starred documents
/// </summary>
[CLSCompliant(false)]
public bool Starred
{
get { return Categories.Contains(STARRED); }
set
{
if (value)
{
Categories.Add(STARRED);
}
else
{
Categories.Remove(STARRED);
}
}
}
/// <summary>
/// Restricts the results to only viewed documents
/// </summary>
[CLSCompliant(false)]
public bool Viewed
{
get { return Categories.Contains(VIEWED); }
set
{
if (value)
{
Categories.Add(VIEWED);
}
else
{
Categories.Remove(VIEWED);
}
}
}
/// <summary>
/// Restricts the results to only trashed documents
/// </summary>
[CLSCompliant(false)]
public bool Trashed
{
get { return Categories.Contains(TRASHED); }
set
{
if (value)
{
Categories.Add(TRASHED);
}
else
{
Categories.Remove(TRASHED);
}
}
}
/// <summary>
/// Restricts the results to only documents owned by the user
/// </summary>
[CLSCompliant(false)]
public bool Mine
{
get { return Categories.Contains(MINE); }
set
{
if (value)
{
Categories.Add(MINE);
}
else
{
Categories.Remove(MINE);
}
}
}
/// <summary>
/// if true, shows folders in the result
/// </summary>
[CLSCompliant(false)]
public bool ShowFolders { get; set; }
/// <summary>
/// if true, shows root in the result
/// </summary>
public bool ShowRoot { get; set; }
/// <summary>
/// Restricts the results to only documents with titles matching a string.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Restricts the results to only documents matching a string provided
/// by the Title property exactly. (No partial matches.)
/// </summary>
public bool TitleExact { get; set; }
/// <summary>
/// Searches for documents with a specific owner. Use the email address of the owner
/// </summary>
public string Owner { get; set; }
/// <summary>
/// Searches for documents which can be written to by specific users.
/// Use a single email address or a comma separated list of email addresses.
/// </summary>
public string Writer { get; set; }
/// <summary>
/// Searches for documents which can be read by specific users.
/// Use a single email address or a comma separated list of email addresses.
/// </summary>
public string Reader { get; set; }
/// <summary>
/// Specifies whether to attempt OCR on a .jpg, .png, of .gif upload.
/// </summary>
public bool Ocr { get; set; }
/// <summary>
/// Specifies whether the query should return documents which are in the trash as well as other documents.
/// </summary>
public bool ShowDeleted { get; set; }
/// <summary>
/// Specifies the language to translate a document into.
/// </summary>
public string TargetLanguage { get; set; }
/// <summary>
/// Specifies the source langugate to translate a document from.
/// </summary>
public string SourceLanguage { get; set; }
/// <summary>
/// Lower bound on the last time a document was edited by the current user.
/// </summary>
public DateTime EditedMin { get; set; }
/// <summary>Upper bound on the last time a document was edited by the current user.</summary>
public DateTime EditedMax { get; set; }
/// <summary>
/// Specifies whether the query should return additional profile information for the users.
/// </summary>
public bool IncludeProfileInfo { get; set; }
/// <summary>Parses custom properties out of the incoming URI</summary>
/// <param name="targetUri">A URI representing a query on a feed</param>
/// <returns>returns the base uri</returns>
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = {'?', '&'};
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (string token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = {'='};
string[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "title-exact":
TitleExact = bool.Parse(parameters[1]);
break;
case "title":
Title = parameters[1];
break;
case "owner":
Owner = parameters[1];
break;
case "reader":
Reader = parameters[1];
break;
case "writer":
Writer = parameters[1];
break;
case "targetLanguage":
TargetLanguage = parameters[1];
break;
case "sourceLanguage":
SourceLanguage = parameters[1];
break;
case "showfolders":
ShowFolders = bool.Parse(parameters[1]);
break;
case "ocr":
Ocr = bool.Parse(parameters[1]);
break;
case "showDeleted":
ShowDeleted = bool.Parse(parameters[1]);
break;
case "edited-min":
EditedMin = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
break;
case "edited-max":
EditedMax = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
break;
case "include-profile-info":
IncludeProfileInfo = bool.Parse(parameters[1]);
break;
case "showroot":
ShowRoot = bool.Parse(parameters[1]);
break;
}
}
}
}
return Uri;
}
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> A string representing the query part of the URI.</returns>
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
paramInsertion = AppendQueryPart(Title, "title", paramInsertion, newPath);
if (TitleExact)
{
paramInsertion = AppendQueryPart("true", "title-exact", paramInsertion, newPath);
}
if (ShowFolders)
{
paramInsertion = AppendQueryPart("true", "showfolders", paramInsertion, newPath);
}
if (Ocr)
{
paramInsertion = AppendQueryPart("true", "ocr", paramInsertion, newPath);
}
if (ShowDeleted)
{
paramInsertion = AppendQueryPart("true", "showDeleted", paramInsertion, newPath);
}
if (ShowRoot)
{
paramInsertion = AppendQueryPart("true", "showroot", paramInsertion, newPath);
}
if (IncludeProfileInfo)
{
paramInsertion = AppendQueryPart("true", "include-profile-info", paramInsertion, newPath);
}
paramInsertion = AppendQueryPart(Owner, "owner", paramInsertion, newPath);
paramInsertion = AppendQueryPart(Writer, "writer", paramInsertion, newPath);
paramInsertion = AppendQueryPart(Reader, "reader", paramInsertion, newPath);
paramInsertion = AppendQueryPart(EditedMin, "edited-min", paramInsertion, newPath);
paramInsertion = AppendQueryPart(EditedMax, "edited-max", paramInsertion, newPath);
paramInsertion = AppendQueryPart(TargetLanguage, "targetLanguage", paramInsertion, newPath);
paramInsertion = AppendQueryPart(SourceLanguage, "sourceLanguage", paramInsertion, newPath);
return newPath.ToString();
}
}
/// <summary>
/// a subclass setup to just retrieve all word processor documents
/// </summary>
public class TextDocumentQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public TextDocumentQuery()
{
Categories.Add(DOCUMENTS);
}
}
/// <summary>
/// a subclass setup to just retrieve all spreadsheets
/// </summary>
public class SpreadsheetQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public SpreadsheetQuery()
{
Categories.Add(SPREADSHEETS);
}
}
/// <summary>
/// a subclass setup to just retrieve all presentations
/// </summary>
public class PresentationsQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public PresentationsQuery()
{
Categories.Add(PRESENTATIONS);
}
}
/// <summary>
/// a subclass setup to just retrieve all drawings
/// </summary>
public class DrawingsQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public DrawingsQuery()
{
Categories.Add(DRAWINGS);
}
}
/// <summary>
/// a subclass setup to just retrieve all PDFs
/// </summary>
public class PDFsQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public PDFsQuery()
{
Categories.Add(PDFS);
}
}
/// <summary>
/// a subclass setup to just retrieve all Folders
/// </summary>
public class FolderQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public FolderQuery()
{
baseUri = allFoldersUri;
}
/// <summary>
/// base constructor
/// </summary>
public FolderQuery(string folderId)
{
baseUri = string.Format(foldersUriTemplate, folderId);
ShowFolders = true;
}
}
/// <summary>
/// a subclass setup to retrieve all changes
/// </summary>
public class ChangesQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public ChangesQuery()
: this("default")
{
}
/// <summary>
/// base constructor
/// </summary>
public ChangesQuery(string userId)
{
baseUri = string.Format(allChangesTemplate, userId);
}
public override int StartIndex { get; set; }
public bool ExpandAcl { get; set; }
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (ExpandAcl)
{
paramInsertion = AppendQueryPart("true", "expand-acl", paramInsertion, newPath);
}
return newPath.ToString();
}
}
/// <summary>
/// a subclass setup to retrieve information about a user account
/// </summary>
public class MetadataQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public MetadataQuery()
: this("default")
{
}
/// <summary>
/// base constructor
/// </summary>
public MetadataQuery(string userId)
{
baseUri = string.Format(metadataTemplate, userId);
}
public int RemainingChangestampsFirst { get; set; }
public int RemainingChangestampsLimit { get; set; }
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (RemainingChangestampsFirst > 0)
{
paramInsertion = AppendQueryPart(
RemainingChangestampsFirst.ToString(),
"remaining-changestamps-first",
paramInsertion,
newPath);
}
if (RemainingChangestampsLimit > 0)
{
paramInsertion = AppendQueryPart(
RemainingChangestampsLimit.ToString(),
"remaining-changestamps-limit",
paramInsertion,
newPath);
}
return newPath.ToString();
}
}
/// <summary>
/// a query object used to interact with the Archive feed
/// </summary>
public class ArchiveQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public ArchiveQuery(string archiveId)
{
baseUri = archiveUri + "/" + archiveId;
}
}
/// <summary>
/// a query object used to interact with the Revision feed
/// </summary>
public class RevisionQuery : DocumentsListQuery
{
/// <summary>
/// base constructor
/// </summary>
public RevisionQuery(string revisionUri)
{
baseUri = revisionUri;
}
}
}
| |
//
// Created by Shopify.
// Copyright (c) 2016 Shopify Inc. All rights reserved.
// Copyright (c) 2016 Xamarin Inc. All rights reserved.
//
// 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 CoreGraphics;
using Foundation;
using PassKit;
using SafariServices;
using UIKit;
using Shopify.Buy;
namespace ShopifyiOSSample
{
public class PreCheckoutViewController : UITableViewController
{
private readonly BuyClient client;
private Checkout _checkout;
private PKPaymentSummaryItem[] summaryItems;
private enum UITableViewSections
{
SummaryItems,
DiscountGiftCard,
Continue,
Count
}
private enum UITableViewDiscountGiftCardSection
{
Discount,
GiftCard,
Count
}
public PreCheckoutViewController(BuyClient client, Checkout checkout)
: base(UITableViewStyle.Grouped)
{
this.client = client;
this.checkout = checkout;
}
public NSNumberFormatter CurrencyFormatter { get; set; }
private Checkout checkout
{
get { return _checkout; }
set
{
_checkout = value;
// We can take advantage of the PKPaymentSummaryItems used for
// Apple Pay to display summary items natively in our own
// checkout
summaryItems = _checkout.ApplePaySummaryItems();
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Title = "Add Discount or Gift Card(s)";
TableView.RegisterClassForCellReuse(typeof(UITableViewCell), "Cell");
}
public override nint NumberOfSections(UITableView tableView)
{
return (int)UITableViewSections.Count;
}
public override nint RowsInSection(UITableView tableView, nint section)
{
switch ((UITableViewSections)(int)section)
{
case UITableViewSections.SummaryItems:
return summaryItems == null ? 0 : summaryItems.Length;
case UITableViewSections.DiscountGiftCard:
return (int)UITableViewDiscountGiftCardSection.Count;
default:
return 1;
}
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = null;
switch ((UITableViewSections)indexPath.Section)
{
case UITableViewSections.SummaryItems:
cell = tableView.DequeueReusableCell("SummaryCell") ?? new SummaryItemsTableViewCell("SummaryCell");
var summaryItem = summaryItems[indexPath.Row];
cell.TextLabel.Text = summaryItem.Label;
cell.DetailTextLabel.Text = CurrencyFormatter.StringFromNumber(summaryItem.Amount);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
// Only show a line above the last cell
if (indexPath.Row != summaryItems.Length - 2)
{
cell.SeparatorInset = new UIEdgeInsets(0.0f, 0.0f, 0.0f, cell.Bounds.Size.Width);
}
break;
case UITableViewSections.DiscountGiftCard:
cell = tableView.DequeueReusableCell("Cell", indexPath);
cell.SeparatorInset = UIEdgeInsets.Zero;
switch ((UITableViewDiscountGiftCardSection)indexPath.Row)
{
case UITableViewDiscountGiftCardSection.Discount:
cell.TextLabel.Text = "Add Discount";
break;
case UITableViewDiscountGiftCardSection.GiftCard:
cell.TextLabel.Text = "Apply Gift Card";
break;
}
cell.TextLabel.TextAlignment = UITextAlignment.Center;
break;
case UITableViewSections.Continue:
cell = tableView.DequeueReusableCell("Cell", indexPath);
cell.TextLabel.Text = "Continue";
cell.TextLabel.TextAlignment = UITextAlignment.Center;
break;
}
cell.PreservesSuperviewLayoutMargins = false;
cell.LayoutMargins = UIEdgeInsets.Zero;
return cell;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
switch ((UITableViewSections)indexPath.Section)
{
case UITableViewSections.DiscountGiftCard:
switch ((UITableViewDiscountGiftCardSection)indexPath.Row)
{
case UITableViewDiscountGiftCardSection.Discount:
AddDiscount();
break;
case UITableViewDiscountGiftCardSection.GiftCard:
ApplyGiftCard();
break;
}
break;
case UITableViewSections.Continue:
ProceedToCheckout();
break;
}
tableView.DeselectRow(indexPath, true);
}
private void AddDiscount()
{
var alertController = UIAlertController.Create("Enter Discount Code", null, UIAlertControllerStyle.Alert);
alertController.AddTextField(textField =>
{
textField.Placeholder = "Discount Code";
});
alertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, action =>
{
Console.WriteLine("Cancel action");
}));
alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, async action =>
{
var discount = new Discount(alertController.TextFields[0].Text);
checkout.Discount = discount;
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
try
{
checkout = await client.UpdateCheckoutAsync(checkout);
Console.WriteLine("Successfully added discount");
TableView.ReloadData();
}
catch (NSErrorException ex)
{
Console.WriteLine("Error applying discount: {0}", ex.Error);
}
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
}));
PresentViewController(alertController, true, null);
}
private void ApplyGiftCard()
{
var alertController = UIAlertController.Create("Enter Gift Card Code", null, UIAlertControllerStyle.Alert);
alertController.AddTextField(textField =>
{
textField.Placeholder = "Gift Card Code";
});
alertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, action =>
{
Console.WriteLine("Cancel action");
}));
alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, async action =>
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
try
{
checkout = await client.ApplyGiftCardAsync(alertController.TextFields[0].Text, checkout);
Console.WriteLine("Successfully added gift card");
TableView.ReloadData();
}
catch (NSErrorException ex)
{
Console.WriteLine("Error applying gift card: {0}", ex.Error);
}
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
}));
PresentViewController(alertController, true, null);
}
private void ProceedToCheckout()
{
var checkoutController = new CheckoutViewController(client, checkout);
checkoutController.CurrencyFormatter = CurrencyFormatter;
NavigationController.PushViewController(checkoutController, true);
}
}
}
| |
// ScriptMetadata.cs
// Script#/Libraries/CoreLib
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices {
/// <summary>
/// This attribute can be placed on types in system script assemblies that should not
/// be imported. It is only meant to be used within mscorlib.dll.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NonScriptableAttribute : Attribute {
}
/// <summary>
/// This attribute can be placed on types that should not be emitted into generated
/// script, as they represent existing script or native types. All members without another naming attribute are considered to use [PreserveName].
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct)]
[NonScriptable]
public sealed class ImportedAttribute : Attribute {
/// <summary>
/// Indicates that the type obeys the Saltarelle type system. If false (the default), the type is ignored in inheritance lists, casts to it is a no-op, and Object will be used if the type is used as a generic argument.
/// The default is false. Requiring this to be set should be very uncommon.
/// </summary>
public bool ObeysTypeSystem { get; set; }
/// <summary>
/// Code used to check whether an object is of this type. Can use the placeholder {this} to reference the object being checked, as well as all type parameter for the type.
/// </summary>
public string TypeCheckCode { get; set; }
}
/// <summary>
/// Marks an assembly as a script assembly that can be used with Script#.
/// Additionally, each script must have a unique name that can be used as
/// a dependency name.
/// This name is also used to generate unique names for internal types defined
/// within the assembly. The ScriptQualifier attribute can be used to provide a
/// shorter name if needed.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptAssemblyAttribute : Attribute {
public ScriptAssemblyAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// Provides a prefix to use when generating types internal to this assembly so that
/// they can be unique within a given a script namespace.
/// The specified prefix overrides the script name provided in the ScriptAssembly
/// attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptQualifierAttribute : Attribute {
public ScriptQualifierAttribute(string prefix) {
Prefix = prefix;
}
public string Prefix { get; private set; }
}
/// <summary>
/// This attribute indicates that the namespace of type within a system assembly
/// should be ignored at script generation time. It is useful for creating namespaces
/// for the purpose of c# code that don't exist at runtime.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IgnoreNamespaceAttribute : Attribute {
}
/// <summary>
/// Specifies the namespace that should be used in generated script. The script namespace
/// is typically a short name, that is often shared across multiple assemblies.
/// The developer is responsible for ensuring that public types across assemblies that share
/// a script namespace are unique.
/// For internal types, the ScriptQualifier attribute can be used to provide a short prefix
/// to generate unique names.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptNamespaceAttribute : Attribute {
public ScriptNamespaceAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// This attribute can be placed on a static class that only contains static string
/// fields representing a set of resource strings.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
[NonScriptable]
public sealed class ResourcesAttribute : Attribute {
}
/// <summary>
/// This attribute turns methods on a static class as global methods in the generated
/// script. Note that the class must be static, and must contain only methods.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
[NonScriptable]
public sealed class GlobalMethodsAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class MixinAttribute : Attribute {
public MixinAttribute(string expression) {
Expression = expression;
}
public string Expression { get; private set; }
}
/// <summary>
/// This attribute marks an enumeration type within a system assembly as as a set of
/// names. Rather than the specific value, the name of the enumeration field is
/// used as a string.
/// </summary>
[AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NamedValuesAttribute : Attribute {
}
/// <summary>
/// This attribute marks an enumeration type within a system assembly as as a set of
/// numeric values. Rather than the enum field, the value of the enumeration field is
/// used as a literal.
/// </summary>
[AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NumericValuesAttribute : Attribute {
}
/// <summary>
/// This attribute allows defining an alternate method signature that is not generated
/// into script, but can be used for defining overloads to enable optional parameter semantics
/// for a method. It must be applied on a method defined as extern, since an alternate signature
/// method does not contain an actual method body.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class AlternateSignatureAttribute : Attribute {
}
/// <summary>
/// This attribute denotes a C# property that manifests like a field in the generated
/// JavaScript (i.e. is not accessed via get/set methods). This is really meant only
/// for use when defining OM corresponding to native objects exposed to script.
/// If no other name is specified (and the property is not an indexer), the field is treated as if it were decorated with a [PreserveName] attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IntrinsicPropertyAttribute : Attribute {
}
/// <summary>
/// Allows specifying the name to use for a type or member in the generated script.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Event | AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptNameAttribute : Attribute {
public ScriptNameAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// This attribute allows suppressing the default behavior of converting
/// member names to camel-cased equivalents in the generated JavaScript.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveCaseAttribute : Attribute {
}
/// <summary>
/// This attribute allows suppressing the default behavior of converting
/// member names of attached type to camel-cased equivalents in the generated JavaScript.
/// When applied to an assembly, all types in the assembly are considered to have this
/// attribute by default</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Assembly, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveMemberCaseAttribute : Attribute {
public PreserveMemberCaseAttribute() {
Preserve = true;
}
public PreserveMemberCaseAttribute(bool preserve) {
Preserve = preserve;
}
public bool Preserve { get; private set; }
}
/// <summary>
/// This attribute allows suppressing the default behavior of minimizing
/// private type names and member names in the generated JavaScript.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveNameAttribute : Attribute {
}
/// <summary>
/// This attribute allows public symbols inside an assembly to be minimized, in addition to non-public ones, when generating release scripts.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
[NonScriptable]
public sealed class MinimizePublicNamesAttribute : Attribute {
}
/// <summary>
/// This attribute allows specifying a script name for an imported method.
/// The method is interpreted as a global method. As a result it this attribute
/// only applies to static methods.
/// </summary>
// REVIEW: Eventually do we want to support this on properties/field and instance methods as well?
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptAliasAttribute : Attribute {
public ScriptAliasAttribute(string alias) {
Alias = alias;
}
public string Alias { get; private set; }
}
/// <summary>
/// This attributes causes a method to not be invoked. The method must either be a static method with one argument (in case Foo.M(x) will become x), or an instance method with no arguments (in which x.M() will become x).
/// Can also be applied to a constructor, in which case the constructor will not be called if used as an initializer (": base()" or ": this()").
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptSkipAttribute : Attribute {
}
/// <summary>
/// The method is implemented as inline code, eg Debugger.Break() => debugger. Can use the parameters {this} (for instance methods), as well as all typenames and argument names in braces (eg. {arg0}, {TArg0}).
/// If a parameter name is preceeded by an @ sign, {@arg0}, that argument must be a literal string during invocation, and the supplied string will be inserted as an identifier into the script (eg '{this}.set_{@arg0}({arg1})' can transform the call 'c.F("MyProp", v)' to 'c.set_MyProp(v)'.
/// If a parameter name is preceeded by an asterisk {*arg} that parameter must be a param array, and all invocations of the method must use the expanded invocation form. The entire array supplied for the parameter will be inserted into the call. Pretend that the parameter is a normal parameter, and commas will be inserted or omitted at the correct locations.
/// The format string can also use identifiers starting with a dollar {$Namespace.Name} to construct type references. The name must be the fully qualified type name in this case.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class InlineCodeAttribute : Attribute {
public InlineCodeAttribute(string code) {
Code = code;
}
public string Code { get; private set; }
/// <summary>
/// If set, a method with this name will be generated from the method source.
/// </summary>
public string GeneratedMethodName { get; set; }
/// <summary>
/// This code is used when the method is invoked non-virtually (eg. in a base.Method() call).
/// </summary>
public string NonVirtualCode { get; set; }
/// <summary>
/// This code is used when the method, which should be a method with a param array parameter, is invoked in non-expanded form. Optional, but can be used to support non-expanded invocation of a method that has a {*param} placeholder in its code.
/// </summary>
public string NonExpandedFormCode { get; set; }
}
/// <summary>
/// This attribute specifies that a static method should be treated as an instance method on its first argument. This means that <c>MyClass.Method(x, a, b)</c> will be transformed to <c>x.Method(a, b)</c>.
/// If no other name-preserving attribute is used on the member, it will be treated as if it were decorated with a [PreserveNameAttribute].
/// Useful for extension methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class InstanceMethodOnFirstArgumentAttribute : Attribute {
}
/// <summary>
/// This attribute specifies that a generic type or method should have script generated as if it was a non-generic one. Any uses of the type arguments inside the method (eg. <c>typeof(T)</c>, or calling another generic method with T as a type argument) will cause runtime errors.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IncludeGenericArgumentsAttribute : Attribute {
public IncludeGenericArgumentsAttribute() {
Include = true;
}
public IncludeGenericArgumentsAttribute(bool include) {
Include = include;
}
public bool Include { get; private set; }
}
/// <summary>
/// This enum defines the possibilities for default values for generic argument handling in an assembly.
/// </summary>
[NonScriptable]
public enum GenericArgumentsDefault {
/// <summary>
/// Include generic arguments for all types that are not [Imported]
/// </summary>
IncludeExceptImported,
/// <summary>
/// Ignore generic arguments by default (this is the default)
/// </summary>
Ignore,
/// <summary>
/// Require an <see cref="IncludeGenericArgumentsAttribute"/> for all generic types/methods, excepts those that are imported, which will default to ignore their generic arguments.
/// </summary>
RequireExplicitSpecification,
}
/// <summary>
/// This attribute indicates whether generic arguments for types and methods are included, but can always be overridden by specifying an <see cref="IncludeGenericArgumentsAttribute"/> on types or methods.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class IncludeGenericArgumentsDefaultAttribute : Attribute {
public GenericArgumentsDefault TypeDefault { get; set; }
public GenericArgumentsDefault MethodDefault { get; set; }
}
/// <summary>
/// This attribute indicates that a user-defined operator should be compiled as if it were builtin (eg. op_Addition(a, b) => a + b). It can only be used on non-conversion operator methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IntrinsicOperatorAttribute : Attribute {
}
/// <summary>
/// This attribute can be applied to a method with a "params" parameter to make the param array be expanded in script (eg. given 'void F(int a, params int[] b)', the invocation 'F(1, 2, 3)' will be translated to 'F(1, [2, 3])' without this attribute, but 'F(1, 2, 3)' with this attribute.
/// Methods with this attribute can only be invoked in the expanded form.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Delegate, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ExpandParamsAttribute : Attribute {
}
/// <summary>
/// Indicates that the Javascript 'this' should appear as the first argument to the delegate.
/// </summary>
[AttributeUsage(AttributeTargets.Delegate)]
[NonScriptable]
public sealed class BindThisToFirstParameterAttribute : Attribute {
}
/// <summary>
/// If this attribute is applied to a constructor for a serializable type, it means that the constructor will not be called, but rather an object initializer will be created. Eg. 'new MyRecord(1, "X")' can become '{ a: 1, b: 'X' }'.
/// All parameters must have a field or property with the same (case-insensitive) name, of the same type.
/// This attribute is implicit on constructors of imported serializable types.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ObjectLiteralAttribute : Attribute {
}
/// <summary>
/// This attribute can be specified on an assembly to specify additional compatibility options to help migrating from Script#.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class ScriptSharpCompatibilityAttribute : Attribute {
/// <summary>
/// If true, code will not be generated for casts of type '(MyClass)someValue'. Code will still be generated for 'someValue is MyClass' and 'someValue as MyClass'.
/// </summary>
public bool OmitDowncasts { get; set; }
/// <summary>
/// If true, code will not be generated to verify that a nullable value is not null before converting it to its underlying type.
/// </summary>
public bool OmitNullableChecks { get; set; }
}
/// <summary>
/// If a constructor for a value type takes an instance of this type as a parameter, any attribute applied to that constructor will instead be applied to the default (undeclarable) constructor.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Imported]
public sealed class DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor {
private DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor() {}
}
/// <summary>
/// Specifies that a type is defined in a module, which should be imported by a require() call.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Assembly)]
[NonScriptable]
public sealed class ModuleNameAttribute : Attribute {
public ModuleNameAttribute(string moduleName) {
this.ModuleName = moduleName;
}
public string ModuleName { get; private set; }
}
/// <summary>
/// When specified on an assembly, Javascript that adheres to the AMD pattern (require/define) will be generated.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class AsyncModuleAttribute : Attribute {
}
/// <summary>
/// When specified on an assembly with an AsyncModule attribute, the module will require this additional dependency in its AMD declaration
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
[NonScriptable]
public sealed class AdditionalDependencyAttribute : Attribute {
public AdditionalDependencyAttribute(string moduleName)
{
ModuleName = moduleName;
InstanceName = moduleName;
}
public AdditionalDependencyAttribute(string moduleName, string instanceName)
{
ModuleName = moduleName;
InstanceName = instanceName;
}
public string ModuleName { get; private set; }
public string InstanceName { get; set; }
}
/// <summary>
/// Can be applied to a GetEnumerator() method to indicate that that array-style enumeration should be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[NonScriptable]
public sealed class EnumerateAsArrayAttribute : Attribute {
}
/// <summary>
/// Can be applied to a const field to indicate that the literal value of the constant should always be used instead of the symbolic field name.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
[NonScriptable]
public sealed class InlineConstantAttribute : Attribute {
}
/// <summary>
/// Can be applied to a member to indicate that metadata for the member should (or should not) be included in the compiled script. By default members are reflectable if they have at least one scriptable attribute. The default reflectability can be changed with the [<see cref="DefaultMemberReflectabilityAttribute"/>].
/// </summary>
[AttributeUsage(AttributeTargets.All)]
[NonScriptable]
public sealed class ReflectableAttribute : Attribute {
public bool Reflectable { get; private set; }
public ReflectableAttribute() {
Reflectable = true;
}
public ReflectableAttribute(bool reflectable) {
Reflectable = reflectable;
}
}
/// <summary>
/// This enum defines the possibilities for default member reflectability.
/// </summary>
[NonScriptable]
public enum MemberReflectability {
/// <summary>
/// Members are not reflectable (unless they are decorated either with any script-usable attributes or a [ReflectableAttribute])
/// </summary>
None,
/// <summary>
/// Public and protected members are reflectable, private/internal members are only reflectable if are decorated either with any script-usable attributes or a [ReflectableAttribute].
/// Members are reflectable even when their enclosing type is not publicly visible.
/// </summary>
PublicAndProtected,
/// <summary>
/// Public, protected and internal members are reflectable, private members are only reflectable if are decorated either with any script-usable attributes or a [ReflectableAttribute].
/// </summary>
NonPrivate,
/// <summary>
/// All members are reflectable by default (can be overridden with [Reflectable(false)]).
/// </summary>
All
}
/// <summary>
/// This attribute can be applied to an assembly or a type to indicate whether members are reflectable by default.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
[NonScriptable]
public sealed class DefaultMemberReflectabilityAttribute : Attribute {
public MemberReflectability DefaultReflectability { get; private set; }
public DefaultMemberReflectabilityAttribute(MemberReflectability defaultReflectability) {
DefaultReflectability = defaultReflectability;
}
}
/// <summary>
/// Can be applied to a constant field to ensure that it will never be inlined, even in minified scripts.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public sealed class NoInlineAttribute : Attribute {
}
/// <summary>
/// Can be applied to a user-defined value type (struct) to instruct the compiler that it can be mutated and therefore needs to be copied whenever .net would create a copy of a value type.
/// </summary>
[AttributeUsage(AttributeTargets.Struct)]
[NonScriptable]
public sealed class MutableAttribute : Attribute {
}
}
| |
//-----------------------------------------------------------------------------
// Control.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace GameStateManagement
{
/// <summary>
/// Control is the base class for a simple UI controls framework.
///
/// Controls are grouped into a heirarchy: each control has a Parent and
/// an optional list of Children. They draw themselves
///
/// Input handling
/// ==============
/// Call HandleInput() once per update on the root control of the heirarchy; it will then call HandleInput() on
/// its children. Controls can override HandleInput() to check for touch events and the like. If you override this
/// function, you need to call base.HandleInput() to let your child controls see input.
///
/// Note that Controls do not have any special system for setting TouchPanel.EnabledGestures; if you're using
/// gesture-sensitive controls, you need to set EnabledGestures as appopriate in each GameScreen.
///
/// Rendering
/// =========
/// Override Control.Draw() to render your control. Control.Draw() takes a 'DrawContext' struct, which contains
/// the GraphicsDevice and other objects useful for drawing. It also contains a SpriteBatch, which will have had
/// Begin() called *before* Control.Draw() is called. This allows batching of sprites across multiple controls
/// to improve rendering speed.
///
/// Layout
/// ======
/// Controls have a Position and Size, which defines a rectangle. By default, Size is computed
/// auotmatically by an internal call to ComputeSize(), which each child control can implement
/// as appropriate. For example, TextControl uses the size of the rendered text.
///
/// If you *write* to the Size property, auto-sizing will be disabled, and the control will
/// retain the written size unless you write to it again.
///
/// There is no dynamic layout system. Instead, container controls (PanelControl in particular)
/// contain methods for positioning their child controls into rows, columns, or other arrangements.
/// Client code should create the controls needed for a screen, then call one or more of these
/// layout functions to position them.
/// </summary>
public class Control
{
#region Private fields
private Vector2 position;
private Vector2 size;
private bool sizeValid = false;
private bool autoSize = true;
private List<Control> children = null;
#endregion
#region Properties
/// <summary>
/// Draw() is not called unless Control.Visible is true (the default).
/// </summary>
public bool Visible = true;
/// <summary>
/// Position of this control within its parent control.
/// </summary>
public Vector2 Position
{
get
{
return position;
}
set
{
position = value;
if (Parent != null)
{
Parent.InvalidateAutoSize();
}
}
}
/// <summary>
/// Size if this control. See above for a discussion of the layout system.
/// </summary>
public Vector2 Size
{
// Default behavior is for ComputeSize() to determine the size, and then cache it.
get
{
if (!sizeValid)
{
size = ComputeSize();
sizeValid = true;
}
return size;
}
// Setting the size overrides whatever ComputeSize() would return, and disables autoSize
set
{
size = value;
sizeValid = true;
autoSize = false;
if (Parent != null)
{
Parent.InvalidateAutoSize();
}
}
}
/// <summary>
/// Call this method when a control's content changes so that its size needs to be recomputed. This has no
/// effect if autoSize has been disabled.
/// </summary>
protected void InvalidateAutoSize()
{
if (autoSize)
{
sizeValid = false;
if (Parent != null)
{
Parent.InvalidateAutoSize();
}
}
}
/// <summary>
/// The control containing this control, if any
/// </summary>
public Control Parent { get; private set; }
/// <summary>
/// Number of child controls of this control
/// </summary>
public int ChildCount { get { return children == null ? 0 : children.Count; } }
/// <summary>
/// Indexed access to the children of this control.
/// </summary>
public Control this[int childIndex]
{
get
{
return children[childIndex];
}
}
#endregion
#region Child control API
public void AddChild(Control child)
{
if (child.Parent != null)
{
child.Parent.RemoveChild(child);
}
AddChild(child, ChildCount);
}
public void AddChild(Control child, int index)
{
if (child.Parent != null)
{
child.Parent.RemoveChild(child);
}
child.Parent = this;
if (children == null)
{
children = new List<Control>();
}
children.Insert(index, child);
OnChildAdded(index, child);
}
public void RemoveChildAt(int index)
{
Control child = children[index];
child.Parent = null;
children.RemoveAt(index);
OnChildRemoved(index, child);
}
/// <summary>
/// Remove the given control from this control's list of children.
/// </summary>
public void RemoveChild(Control child)
{
if(child.Parent != this)
throw new InvalidOperationException();
RemoveChildAt(children.IndexOf(child));
}
#endregion
#region Virtual methods for derived classes to override
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public virtual void Draw(DrawContext context)
{
Vector2 origin = context.DrawOffset;
for(int i=0; i<ChildCount; i++)
{
Control child = children[i];
if (child.Visible)
{
context.DrawOffset = origin + child.Position;
child.Draw(context);
}
}
}
/// <summary>
/// Called once per frame to update the control; override this method if your control requires custom updates.
/// Call base.Update() to update any child controls.
/// </summary>
public virtual void Update(GameTime gametime)
{
for (int i = 0; i < ChildCount; i++)
{
children[i].Update(gametime);
}
}
/// <summary>
/// Called once per frame to update the control; override this method if your control requires custom updates.
/// Call base.Update() to update any child controls.
/// </summary>
public virtual void HandleInput(InputState input)
{
for (int i = 0; i < ChildCount; i++)
{
children[i].HandleInput(input);
}
}
/// <summary>
/// Called when the Size property is read and sizeValid is false. Call base.ComputeSize() to compute the
/// size (actually the lower-right corner) of all child controls.
/// </summary>
public virtual Vector2 ComputeSize()
{
if (children == null || children.Count == 0)
{
return Vector2.Zero;
}
else
{
Vector2 bounds = children[0].Position + children[0].Size;
for (int i = 1; i < children.Count; i++)
{
Vector2 corner = children[i].Position + children[i].Size;
bounds.X = Math.Max(bounds.X, corner.X);
bounds.Y = Math.Max(bounds.Y, corner.Y);
}
return bounds;
}
}
/// <summary>
/// Called after a child control is added to this control. The default behavior is to call InvalidateAutoSize().
/// </summary>
protected virtual void OnChildAdded(int index, Control child)
{
InvalidateAutoSize();
}
/// <summary>
/// Called after a child control is removed from this control. The default behavior is to call InvalidateAutoSize().
/// </summary>
protected virtual void OnChildRemoved(int index, Control child)
{
InvalidateAutoSize();
}
#endregion
#region Static methods
// Call this method once per frame on the root of your control heirarchy to draw all the controls.
// See ControlScreen for an example.
public static void BatchDraw(Control control, GraphicsDevice device, SpriteBatch spriteBatch, Vector2 offset, GameTime gameTime)
{
if (control != null && control.Visible)
{
spriteBatch.Begin();
control.Draw(new DrawContext
{
Device = device,
SpriteBatch = spriteBatch,
DrawOffset = offset + control.Position,
GameTime = gameTime
});
spriteBatch.End();
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ApplicationSettingsBase.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Diagnostics.CodeAnalysis;
// These aren't valid violations - caused by HostProtectionAttribute.
[assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.Configuration.ApplicationSettingsBase.add_PropertyChanged(System.ComponentModel.PropertyChangedEventHandler):System.Void")]
[assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.Configuration.ApplicationSettingsBase.remove_PropertyChanged(System.ComponentModel.PropertyChangedEventHandler):System.Void")]
[assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.TypeDescriptor.GetConverter(System.Type):System.ComponentModel.TypeConverter")]
// Reviewed and found to be safe.
[assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.Configuration.LocalFileSettingsProvider..ctor()")]
namespace System.Configuration {
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
/// <devdoc>
/// Base settings class for client applications.
/// </devdoc>
public abstract class ApplicationSettingsBase : SettingsBase, INotifyPropertyChanged {
private bool _explicitSerializeOnClass = false;
private object[] _classAttributes;
private IComponent _owner;
private PropertyChangedEventHandler _onPropertyChanged;
private SettingsContext _context;
private SettingsProperty _init;
private SettingsPropertyCollection _settings;
private SettingsProviderCollection _providers;
private SettingChangingEventHandler _onSettingChanging;
private SettingsLoadedEventHandler _onSettingsLoaded;
private SettingsSavingEventHandler _onSettingsSaving;
private string _settingsKey = String.Empty;
private bool _firstLoad = true;
private bool _initialized = false;
/// <devdoc>
/// Default constructor without a concept of "owner" component.
/// </devdoc>
protected ApplicationSettingsBase() : base() {
}
/// <devdoc>
/// Constructor that takes an IComponent. The IComponent acts as the "owner" of this settings class. One
/// of the things we do is query the component's site to see if it has a SettingsProvider service. If it
/// does, we allow it to override the providers specified in the metadata.
/// </devdoc>
protected ApplicationSettingsBase(IComponent owner) : this(owner, String.Empty) {
}
/// <devdoc>
/// Convenience overload that takes the settings key
/// </devdoc>
protected ApplicationSettingsBase(string settingsKey) {
_settingsKey = settingsKey;
}
/// <devdoc>
/// Convenience overload that takes the owner component and settings key.
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected ApplicationSettingsBase(IComponent owner, string settingsKey) : this(settingsKey) {
if (owner == null) {
throw new ArgumentNullException("owner");
}
_owner = owner;
if (owner.Site != null) {
ISettingsProviderService provSvc = owner.Site.GetService(typeof(ISettingsProviderService)) as ISettingsProviderService;
if (provSvc != null) {
// The component's site has a settings provider service. We pass each SettingsProperty to it
// to see if it wants to override the current provider.
foreach (SettingsProperty sp in Properties) {
SettingsProvider prov = provSvc.GetSettingsProvider(sp);
if (prov != null) {
sp.Provider = prov;
}
}
ResetProviders();
}
}
}
/// <devdoc>
/// The Context to pass on to the provider. Currently, this will just contain the settings group name.
/// </devdoc>
[Browsable(false)]
public override SettingsContext Context {
get {
if (_context == null) {
if (IsSynchronized) {
lock (this) {
if (_context == null) {
_context = new SettingsContext();
EnsureInitialized();
}
}
}
else {
_context = new SettingsContext();
EnsureInitialized();
}
}
return _context;
}
}
/// <devdoc>
/// The SettingsBase class queries this to get the collection of SettingsProperty objects. We reflect over
/// the properties defined on the current object's type and use the metadata on those properties to form
/// this collection.
/// </devdoc>
[Browsable(false)]
public override SettingsPropertyCollection Properties {
get {
if (_settings == null) {
if (IsSynchronized) {
lock (this) {
if (_settings == null) {
_settings = new SettingsPropertyCollection();
EnsureInitialized();
}
}
}
else {
_settings = new SettingsPropertyCollection();
EnsureInitialized();
}
}
return _settings;
}
}
/// <devdoc>
/// Just overriding to add attributes.
/// </devdoc>
[Browsable(false)]
public override SettingsPropertyValueCollection PropertyValues {
get {
return base.PropertyValues;
}
}
/// <devdoc>
/// Provider collection
/// </devdoc>
[Browsable(false)]
public override SettingsProviderCollection Providers {
get {
if (_providers == null) {
if (IsSynchronized) {
lock (this) {
if (_providers == null) {
_providers = new SettingsProviderCollection();
EnsureInitialized();
}
}
}
else {
_providers = new SettingsProviderCollection();
EnsureInitialized();
}
}
return _providers;
}
}
/// <devdoc>
/// Derived classes should use this to uniquely identify separate instances of settings classes.
/// </devdoc>
[Browsable(false)]
public string SettingsKey {
get {
return _settingsKey;
}
set {
_settingsKey = value;
Context["SettingsKey"] = _settingsKey;
}
}
/// <devdoc>
/// Fires when the value of a setting is changed. (INotifyPropertyChanged implementation.)
/// </devdoc>
public event PropertyChangedEventHandler PropertyChanged {
add {
_onPropertyChanged += value;
}
remove {
_onPropertyChanged -= value;
}
}
/// <devdoc>
/// Fires when the value of a setting is about to change. This is a cancellable event.
/// </devdoc>
public event SettingChangingEventHandler SettingChanging {
add {
_onSettingChanging += value;
}
remove {
_onSettingChanging -= value;
}
}
/// <devdoc>
/// Fires when settings are retrieved from a provider. It fires once for each provider.
/// </devdoc>
public event SettingsLoadedEventHandler SettingsLoaded {
add {
_onSettingsLoaded += value;
}
remove {
_onSettingsLoaded -= value;
}
}
/// <devdoc>
/// Fires when Save() is called. This is a cancellable event.
/// </devdoc>
public event SettingsSavingEventHandler SettingsSaving {
add {
_onSettingsSaving += value;
}
remove {
_onSettingsSaving -= value;
}
}
/// <devdoc>
/// Used in conjunction with Upgrade - retrieves the previous value of a setting from the provider.
/// Provider must implement IApplicationSettingsProvider to support this.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public object GetPreviousVersion(string propertyName) {
if (Properties.Count == 0)
throw new SettingsPropertyNotFoundException();
SettingsProperty sp = Properties[propertyName];
SettingsPropertyValue value = null;
if (sp == null)
throw new SettingsPropertyNotFoundException();
IApplicationSettingsProvider clientProv = sp.Provider as IApplicationSettingsProvider;
if (clientProv != null) {
value = clientProv.GetPreviousVersion(Context, sp);
}
if (value != null) {
return value.PropertyValue;
}
return null;
}
/// <devdoc>
/// Fires the PropertyChanged event.
/// </devdoc>
protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) {
if(_onPropertyChanged != null) {
_onPropertyChanged(this, e);
}
}
/// <devdoc>
/// Fires the SettingChanging event.
/// </devdoc>
protected virtual void OnSettingChanging(object sender, SettingChangingEventArgs e) {
if(_onSettingChanging != null) {
_onSettingChanging(this, e);
}
}
/// <devdoc>
/// Fires the SettingsLoaded event.
/// </devdoc>
protected virtual void OnSettingsLoaded(object sender, SettingsLoadedEventArgs e) {
if(_onSettingsLoaded != null) {
_onSettingsLoaded(this, e);
}
}
/// <devdoc>
/// Fires the SettingsSaving event.
/// </devdoc>
protected virtual void OnSettingsSaving(object sender, CancelEventArgs e) {
if(_onSettingsSaving != null) {
_onSettingsSaving(this, e);
}
}
/// <devdoc>
/// Causes a reload to happen on next setting access, by clearing the cached values.
/// </devdoc>
public void Reload() {
if (PropertyValues != null) {
PropertyValues.Clear();
}
foreach (SettingsProperty sp in Properties) {
PropertyChangedEventArgs pe = new PropertyChangedEventArgs(sp.Name);
OnPropertyChanged(this, pe);
}
}
/// <devdoc>
/// Calls Reset on the providers.
/// Providers must implement IApplicationSettingsProvider to support this.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public void Reset() {
if (Properties != null) {
foreach(SettingsProvider provider in Providers) {
IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider;
if (clientProv != null) {
clientProv.Reset(Context);
}
}
}
Reload();
}
/// <devdoc>
/// Overriden from SettingsBase to support validation event.
/// </devdoc>
public override void Save() {
CancelEventArgs e= new CancelEventArgs(false);
OnSettingsSaving(this, e);
if (!e.Cancel) {
base.Save();
}
}
/// <devdoc>
/// Overriden from SettingsBase to support validation event.
/// </devdoc>
public override object this[string propertyName] {
get {
if (IsSynchronized) {
lock (this) {
return GetPropertyValue(propertyName);
}
}
else {
return GetPropertyValue(propertyName);
}
}
set {
SettingChangingEventArgs e = new SettingChangingEventArgs(propertyName, this.GetType().FullName, SettingsKey, value, false);
OnSettingChanging(this, e);
if (!e.Cancel) {
base[propertyName] = value;
//
PropertyChangedEventArgs pe = new PropertyChangedEventArgs(propertyName);
OnPropertyChanged(this, pe);
}
}
}
/// <devdoc>
/// Called when the app is upgraded so that we can instruct the providers to upgrade their settings.
/// Providers must implement IApplicationSettingsProvider to support this.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public virtual void Upgrade() {
if (Properties != null) {
foreach(SettingsProvider provider in Providers) {
IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider;
if (clientProv != null) {
clientProv.Upgrade(Context, GetPropertiesForProvider(provider));
}
}
}
Reload();
}
/// <devdoc>
/// Creates a SettingsProperty object using the metadata on the given property
/// and returns it.
///
/// Implementation note: Initialization method - be careful not to access properties here
/// to prevent stack overflow.
/// </devdoc>
private SettingsProperty CreateSetting(PropertyInfo propInfo) {
object[] attributes = propInfo.GetCustomAttributes(false);
SettingsProperty sp = new SettingsProperty(Initializer);
bool explicitSerialize = _explicitSerializeOnClass;
sp.Name = propInfo.Name;
sp.PropertyType = propInfo.PropertyType;
for (int i = 0; i < attributes.Length; i ++) {
Attribute attr = attributes[i] as Attribute;
if (attr != null) {
if (attr is DefaultSettingValueAttribute) {
sp.DefaultValue = ((DefaultSettingValueAttribute)attr).Value;
}
else if (attr is ReadOnlyAttribute) {
sp.IsReadOnly = true;
}
else if (attr is SettingsProviderAttribute) {
string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName;
Type providerType = Type.GetType(providerTypeName);
if (providerType != null) {
SettingsProvider spdr = SecurityUtils.SecureCreateInstance(providerType) as SettingsProvider;
if (spdr != null) {
spdr.Initialize(null, null);
spdr.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName;
// See if we already have a provider of the same name in our collection. If so,
// re-use the existing instance, since we cannot have multiple providers of the same name.
SettingsProvider existing = _providers[spdr.Name];
if (existing != null) {
spdr = existing;
}
sp.Provider = spdr;
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.ProviderInstantiationFailed, providerTypeName));
}
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.ProviderTypeLoadFailed, providerTypeName));
}
}
else if (attr is SettingsSerializeAsAttribute) {
sp.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs;
explicitSerialize = true;
}
else {
// This isn't an attribute we care about, so simply pass it on
// to the SettingsProvider.
// NOTE: The key is the type. So if an attribute was found at class
// level and also property level, the latter overrides the former
// for a given setting. This is exactly the behavior we want.
sp.Attributes.Add(attr.GetType(), attr);
}
}
}
if (!explicitSerialize) {
sp.SerializeAs = GetSerializeAs(propInfo.PropertyType);
}
return sp;
}
/// <devdoc>
/// Ensures this class is initialized. Initialization involves reflecting over properties and building
/// a list of SettingsProperty's.
///
/// Implementation note: Initialization method - be careful not to access properties here
/// to prevent stack overflow.
/// </devdoc>
private void EnsureInitialized() {
if (!_initialized) {
_initialized = true;
Type type = this.GetType();
if (_context == null) {
_context = new SettingsContext();
}
_context["GroupName"] = type.FullName;
_context["SettingsKey"] = SettingsKey;
_context["SettingsClassType"] = type;
PropertyInfo[] properties = SettingsFilter(type.GetProperties(BindingFlags.Instance | BindingFlags.Public));
_classAttributes = type.GetCustomAttributes(false);
if (_settings == null) {
_settings = new SettingsPropertyCollection();
}
if (_providers == null) {
_providers = new SettingsProviderCollection();
}
for (int i = 0; i < properties.Length; i++) {
SettingsProperty sp = CreateSetting(properties[i]);
if (sp != null) {
_settings.Add(sp);
if (sp.Provider != null && _providers[sp.Provider.Name] == null) {
_providers.Add(sp.Provider);
}
}
}
}
}
/// <devdoc>
/// Returns a SettingsProperty used to initialize settings. We initialize a setting with values
/// derived from class level attributes, if present. Otherwise, we initialize to
/// reasonable defaults.
///
/// Implementation note: Initialization method - be careful not to access properties here
/// to prevent stack overflow.
/// </devdoc>
private SettingsProperty Initializer {
get {
if (_init == null) {
_init = new SettingsProperty("");
_init.DefaultValue = null;
_init.IsReadOnly = false;
_init.PropertyType = null;
SettingsProvider provider = new LocalFileSettingsProvider();
if (_classAttributes != null) {
for (int i = 0; i < _classAttributes.Length; i ++) {
Attribute attr = _classAttributes[i] as Attribute;
if (attr != null) {
if (attr is ReadOnlyAttribute) {
_init.IsReadOnly = true;
}
else if (attr is SettingsGroupNameAttribute) {
if (_context == null) {
_context = new SettingsContext();
}
_context["GroupName"] = ((SettingsGroupNameAttribute)attr).GroupName;
}
else if (attr is SettingsProviderAttribute) {
string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName;
Type providerType = Type.GetType(providerTypeName);
if (providerType != null) {
SettingsProvider spdr = SecurityUtils.SecureCreateInstance(providerType) as SettingsProvider;
if (spdr != null) {
provider = spdr;
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.ProviderInstantiationFailed, providerTypeName));
}
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.ProviderTypeLoadFailed, providerTypeName));
}
}
else if (attr is SettingsSerializeAsAttribute) {
_init.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs;
_explicitSerializeOnClass = true;
}
else {
// This isn't an attribute we care about, so simply pass it on
// to the SettingsProvider.
// NOTE: The key is the type. So if an attribute was found at class
// level and also property level, the latter overrides the former
// for a given setting. This is exactly the behavior we want.
_init.Attributes.Add(attr.GetType(), attr);
}
}
}
}
//Initialize the SettingsProvider
provider.Initialize(null, null);
provider.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName;
_init.Provider = provider;
}
return _init;
}
}
/// <devdoc>
/// Gets all the settings properties for this provider.
/// </devdoc>
private SettingsPropertyCollection GetPropertiesForProvider(SettingsProvider provider) {
SettingsPropertyCollection properties = new SettingsPropertyCollection();
foreach (SettingsProperty sp in Properties) {
if (sp.Provider == provider) {
properties.Add(sp);
}
}
return properties;
}
/// <devdoc>
/// Retrieves the value of a setting. We need this method so we can fire the SettingsLoaded event
/// when settings are loaded from the providers.Ideally, this should be fired from SettingsBase,
/// but unfortunately that will not happen in Whidbey. Instead, we check to see if the value has already
/// been retrieved. If not, we fire the load event, since we expect SettingsBase to load all the settings
/// from this setting's provider.
/// </devdoc>
private object GetPropertyValue(string propertyName) {
if (PropertyValues[propertyName] == null) {
// If this is our first load and we are part of a Clickonce app, call Upgrade.
if (_firstLoad) {
_firstLoad = false;
if (IsFirstRunOfClickOnceApp()) {
Upgrade();
}
}
object temp = base[propertyName];
SettingsProperty setting = Properties[propertyName];
SettingsProvider provider = setting != null ? setting.Provider : null;
Debug.Assert(provider != null, "Could not determine provider from which settings were loaded");
SettingsLoadedEventArgs e = new SettingsLoadedEventArgs(provider);
OnSettingsLoaded(this, e);
// Note: we need to requery the value here in case someone changed it while
// handling SettingsLoaded.
return base[propertyName];
}
else {
return base[propertyName];
}
}
/// <devdoc>
/// When no explicit SerializeAs attribute is provided, this routine helps to decide how to
/// serialize.
/// </devdoc>
private SettingsSerializeAs GetSerializeAs(Type type) {
//First check whether this type has a TypeConverter that can convert to/from string
//If so, that's our first choice
TypeConverter tc = TypeDescriptor.GetConverter(type);
bool toString = tc.CanConvertTo(typeof(string));
bool fromString = tc.CanConvertFrom(typeof(string));
if (toString && fromString) {
return SettingsSerializeAs.String;
}
//Else fallback to Xml Serialization
return SettingsSerializeAs.Xml;
}
/// <devdoc>
/// Returns true if this is a clickonce deployed app and this is the first run of the app
/// since deployment or last upgrade.
/// </devdoc>
private bool IsFirstRunOfClickOnceApp() {
// NOTE: For perf & servicing reasons, we don't want to introduce a dependency on
// System.Deployment.dll here. The following code is an alternative to calling
// ApplicationDeployment.CurrentDeployment.IsFirstRun.
// First check if the app is ClickOnce deployed
ActivationContext actCtx = AppDomain.CurrentDomain.ActivationContext;
if (IsClickOnceDeployed(AppDomain.CurrentDomain)) {
// Now check if this is the first run since deployment or last upgrade
return System.Deployment.Internal.InternalActivationContextHelper.IsFirstRun(actCtx);
}
return false;
}
/// <devdoc>
/// Returns true if this is a clickonce deployed app.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts")]
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
internal static bool IsClickOnceDeployed(AppDomain appDomain) {
// NOTE: For perf & servicing reasons, we don't want to introduce a dependency on
// System.Deployment.dll here. The following code is an alternative to calling
// ApplicationDeployment.IsNetworkDeployed.
// Security Note: This is also why we need the security assert above.
ActivationContext actCtx = appDomain.ActivationContext;
// Ensures the app is running with a context from the store.
if (actCtx != null && actCtx.Form == ActivationContext.ContextForm.StoreBounded) {
string fullAppId = actCtx.Identity.FullName;
if (!String.IsNullOrEmpty(fullAppId)) {
return true;
}
}
return false;
}
/// <devdoc>
/// Only those settings class properties that have a SettingAttribute on them are
/// treated as settings. This routine filters out other properties.
/// </devdoc>
private PropertyInfo[] SettingsFilter(PropertyInfo[] allProps) {
ArrayList settingProps = new ArrayList();
object[] attributes;
Attribute attr;
for (int i = 0; i < allProps.Length; i ++) {
attributes = allProps[i].GetCustomAttributes(false);
for (int j = 0; j < attributes.Length; j ++) {
attr = attributes[j] as Attribute;
if (attr is SettingAttribute) {
settingProps.Add(allProps[i]);
break;
}
}
}
return (PropertyInfo[]) settingProps.ToArray(typeof(PropertyInfo));
}
/// <devdoc>
/// Resets the provider collection. This needs to be called when providers change after
/// first being set.
/// </devdoc>
private void ResetProviders() {
Providers.Clear();
foreach (SettingsProperty sp in Properties) {
if (Providers[sp.Provider.Name] == null) {
Providers.Add(sp.Provider);
}
}
}
}
/// <devdoc>
/// Event handler for the SettingsLoaded event.
/// </devdoc>
public delegate void SettingsLoadedEventHandler(object sender, SettingsLoadedEventArgs e);
/// <devdoc>
/// Event handler for the SettingsSaving event.
/// </devdoc>
public delegate void SettingsSavingEventHandler(object sender, CancelEventArgs e);
/// <devdoc>
/// Event handler for the SettingChanging event.
/// </devdoc>
public delegate void SettingChangingEventHandler(object sender, SettingChangingEventArgs e);
/// <devdoc>
/// Event args for the SettingChanging event.
/// </devdoc>
public class SettingChangingEventArgs : CancelEventArgs {
private string _settingClass;
private string _settingName;
private string _settingKey;
private object _newValue;
public SettingChangingEventArgs(string settingName, string settingClass, string settingKey, object newValue, bool cancel) : base(cancel) {
_settingName = settingName;
_settingClass = settingClass;
_settingKey = settingKey;
_newValue = newValue;
}
public object NewValue {
get {
return _newValue;
}
}
public string SettingClass {
get {
return _settingClass;
}
}
public string SettingName {
get {
return _settingName;
}
}
public string SettingKey {
get {
return _settingKey;
}
}
}
/// <devdoc>
/// Event args for the SettingLoaded event.
/// </devdoc>
public class SettingsLoadedEventArgs : EventArgs {
private SettingsProvider _provider;
public SettingsLoadedEventArgs(SettingsProvider provider) {
_provider = provider;
}
public SettingsProvider Provider {
get {
return _provider;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
// File derived from http://www.c-sharpcorner.com/uploadfile/nschan/shapefile02252007134834pm/shapefile.aspx
// Filename: ShapeFile.cs
// Description: Classes for reading ESRI shapefiles.
// Reference: ESRI Shapefile Technical Description, July 1998.
// http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
// 2007-01-22 nschan Initial revision.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Windows;
using System.Drawing;
using RdlMapFile.Resources;
namespace fyiReporting.RdlMapFile
{
/// <summary>
/// Enumeration defining the various shape types. Each shapefile
/// contains only one type of shape (e.g., all polygons or all
/// polylines).
/// </summary>
public enum ShapeType
{
/// <summary>
/// Nullshape / placeholder record.
/// </summary>
NullShape = 0,
/// <summary>
/// Point record, for defining point locations such as a city.
/// </summary>
Point = 1,
/// <summary>
/// One or more sets of connected points. Used to represent roads,
/// hydrography, etc.
/// </summary>
PolyLine = 3,
/// <summary>
/// One or more sets of closed figures. Used to represent political
/// boundaries for countries, lakes, etc.
/// </summary>
Polygon = 5,
/// <summary>
/// A cluster of points represented by a single shape record.
/// </summary>
Multipoint = 8
// Unsupported types:
// PointZ = 11,
// PolyLineZ = 13,
// PolygonZ = 15,
// MultiPointZ = 18,
// PointM = 21,
// PolyLineM = 23,
// PolygonM = 25,
// MultiPointM = 28,
// MultiPatch = 31
}
/// <summary>
/// The ShapeFileHeader class represents the contents
/// of the fixed length, 100-byte file header at the
/// beginning of every shapefile.
/// </summary>
public class ShapeFileHeader
{
#region Private fields
private int fileCode;
private int fileLength;
private int version;
private int shapeType;
// Bounding box.
private double xMin;
private double yMin;
private double xMax;
private double yMax;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileHeader class.
/// </summary>
public ShapeFileHeader()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Indicate the fixed-length of this header in bytes.
/// </summary>
public static int Length
{
get { return 100; }
}
/// <summary>
/// Specifies the file code for an ESRI shapefile, which
/// should be the value, 9994.
/// </summary>
public int FileCode
{
get { return this.fileCode; }
set { this.fileCode = value; }
}
/// <summary>
/// Specifies the length of the shapefile, expressed
/// as the number of 16-bit words in the file.
/// </summary>
public int FileLength
{
get { return this.fileLength; }
set { this.fileLength = value; }
}
/// <summary>
/// Specifies the shapefile version number.
/// </summary>
public int Version
{
get { return this.version; }
set { this.version = value; }
}
/// <summary>
/// Specifies the shape type for the file. A shapefile
/// contains only one type of shape.
/// </summary>
public int ShapeType
{
get { return this.shapeType; }
set { this.shapeType = value; }
}
/// <summary>
/// Indicates the minimum x-position of the bounding
/// box for the shapefile (expressed in degrees longitude).
/// </summary>
public double XMin
{
get { return this.xMin; }
set { this.xMin = value; }
}
/// <summary>
/// Indicates the minimum y-position of the bounding
/// box for the shapefile (expressed in degrees latitude).
/// </summary>
public double YMin
{
get { return this.yMin; }
set { this.yMin = value; }
}
/// <summary>
/// Indicates the maximum x-position of the bounding
/// box for the shapefile (expressed in degrees longitude).
/// </summary>
public double XMax
{
get { return this.xMax; }
set { this.xMax = value; }
}
/// <summary>
/// Indicates the maximum y-position of the bounding
/// box for the shapefile (expressed in degrees latitude).
/// </summary>
public double YMax
{
get { return this.yMax; }
set { this.yMax = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the fields of the file header.
/// </summary>
/// <returns>A string representation of the file header.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileHeader: FileCode={0}, FileLength={1}, Version={2}, ShapeType={3}",
this.fileCode, this.fileLength, this.version, this.shapeType);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFileRecord class represents the contents of
/// a shape record, which is of variable length.
/// </summary>
public class ShapeFileRecord
{
#region Private fields
// Record Header.
private int recordNumber;
private int contentLength;
// Shape type.
private int shapeType;
// Bounding box for shape.
private double xMin;
private double yMin;
private double xMax;
private double yMax;
// Part indices and points array.
private Collection<int> parts = new Collection<int>();
private Collection<PointF> points = new Collection<PointF>();
// Shape attributes from a row in the dBASE file.
private DataRow attributes;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileRecord class.
/// </summary>
public ShapeFileRecord()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Indicates the record number (or index) which starts at 1.
/// </summary>
public int RecordNumber
{
get { return this.recordNumber; }
set { this.recordNumber = value; }
}
/// <summary>
/// Specifies the length of this shape record in 16-bit words.
/// </summary>
public int ContentLength
{
get { return this.contentLength; }
set { this.contentLength = value; }
}
/// <summary>
/// Specifies the shape type for this record.
/// </summary>
public int ShapeType
{
get { return this.shapeType; }
set { this.shapeType = value; }
}
/// <summary>
/// Indicates the minimum x-position of the bounding
/// box for the shape (expressed in degrees longitude).
/// </summary>
public double XMin
{
get { return this.xMin; }
set { this.xMin = value; }
}
/// <summary>
/// Indicates the minimum y-position of the bounding
/// box for the shape (expressed in degrees latitude).
/// </summary>
public double YMin
{
get { return this.yMin; }
set { this.yMin = value; }
}
/// <summary>
/// Indicates the maximum x-position of the bounding
/// box for the shape (expressed in degrees longitude).
/// </summary>
public double XMax
{
get { return this.xMax; }
set { this.xMax = value; }
}
/// <summary>
/// Indicates the maximum y-position of the bounding
/// box for the shape (expressed in degrees latitude).
/// </summary>
public double YMax
{
get { return this.yMax; }
set { this.yMax = value; }
}
/// <summary>
/// Indicates the number of parts for this shape.
/// A part is a connected set of points, analogous to
/// a PathFigure in WPF.
/// </summary>
public int NumberOfParts
{
get { return this.parts.Count; }
}
/// <summary>
/// Specifies the total number of points defining
/// this shape record.
/// </summary>
public int NumberOfPoints
{
get { return this.points.Count; }
}
/// <summary>
/// A collection of indices for the points array.
/// Each index identifies the starting point of the
/// corresponding part (or PathFigure using WPF
/// terminology).
/// </summary>
public Collection<int> Parts
{
get { return this.parts; }
}
/// <summary>
/// A collection of all of the points defining the
/// shape record.
/// </summary>
public Collection<PointF> Points
{
get { return this.points; }
}
/// <summary>
/// Access the (dBASE) attribute values associated
/// with this shape record.
/// </summary>
public DataRow Attributes
{
get { return this.attributes; }
set { this.attributes = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the fields of the shapefile record.
/// </summary>
/// <returns>A string representation of the record.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileRecord: RecordNumber={0}, ContentLength={1}, ShapeType={2}",
this.recordNumber, this.contentLength, this.shapeType);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFileReadInfo class stores information about a shapefile
/// that can be used by external clients during a shapefile read.
/// </summary>
public class ShapeFileReadInfo
{
#region Private fields
private string fileName;
private ShapeFile shapeFile;
private Stream stream;
private int numBytesRead;
private int recordIndex;
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFileReadInfo class.
/// </summary>
public ShapeFileReadInfo()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// The full pathname of the shapefile.
/// </summary>
public string FileName
{
get { return this.fileName; }
set { this.fileName = value; }
}
/// <summary>
/// A reference to the shapefile instance.
/// </summary>
public ShapeFile ShapeFile
{
get { return this.shapeFile; }
set { this.shapeFile = value; }
}
/// <summary>
/// An opened file stream for a shapefile.
/// </summary>
public Stream Stream
{
get { return this.stream; }
set { this.stream = value; }
}
/// <summary>
/// The number of bytes read from a shapefile so far.
/// Can be used to compute a progress value.
/// </summary>
public int NumberOfBytesRead
{
get { return this.numBytesRead; }
set { this.numBytesRead = value; }
}
/// <summary>
/// A general-purpose record index.
/// </summary>
public int RecordIndex
{
get { return this.recordIndex; }
set { this.recordIndex = value; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Output some of the field values in the form of a string.
/// </summary>
/// <returns>A string representation of the field values.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("ShapeFileReadInfo: FileName={0}, ", this.fileName);
sb.AppendFormat("NumberOfBytesRead={0}, RecordIndex={1}", this.numBytesRead, this.recordIndex);
return sb.ToString();
}
#endregion Public methods
}
/// <summary>
/// The ShapeFile class represents the contents of a single
/// ESRI shapefile. This is the class which contains functionality
/// for reading shapefiles and their corresponding dBASE attribute
/// files.
/// </summary>
/// <remarks>
/// You can call the Read() method to import both shapes and attributes
/// at once. Or, you can open the file stream yourself and read the file
/// header or individual records one at a time. The advantage of this is
/// that it allows you to implement your own progress reporting functionality,
/// for example.
/// </remarks>
public class ShapeFile
{
#region Constants
private const int expectedFileCode = 9994;
#endregion Constants
#region Private static fields
private static byte[] intBytes = new byte[4];
private static byte[] doubleBytes = new byte[8];
#endregion Private static fields
#region Private fields
// File Header.
private ShapeFileHeader fileHeader = new ShapeFileHeader();
// Collection of Shapefile Records.
private Collection<ShapeFileRecord> records = new Collection<ShapeFileRecord>();
#endregion Private fields
#region Constructor
/// <summary>
/// Constructor for the ShapeFile class.
/// </summary>
public ShapeFile()
{
}
#endregion Constructor
#region Properties
/// <summary>
/// Access the file header of this shapefile.
/// </summary>
public ShapeFileHeader FileHeader
{
get { return this.fileHeader; }
}
/// <summary>
/// Access the collection of records for this shapefile.
/// </summary>
public Collection<ShapeFileRecord> Records
{
get { return this.records; }
}
#endregion Properties
#region Public methods
/// <summary>
/// Read both shapes and attributes from the given
/// shapefile (and its corresponding dBASE file).
/// This is the top-level method for reading an ESRI
/// shapefile.
/// </summary>
/// <param name="fileName">Full pathname of the shapefile.</param>
public void Read(string fileName)
{
if ( string.IsNullOrEmpty(fileName) )
throw new ArgumentNullException("fileName");
// Read shapes first (geometry).
this.ReadShapes(fileName);
// Construct name and path of dBASE file. It's basically
// the same name as the shapefile except with a .dbf extension.
string dbaseFile = fileName.Replace(".shp", ".dbf");
dbaseFile = dbaseFile.Replace(".SHP", ".DBF");
// Read the attributes.
this.ReadAttributes(dbaseFile);
}
/// <summary>
/// Read shapes (geometry) from the given shapefile.
/// </summary>
/// <param name="fileName">Full pathname of the shapefile.</param>
public void ReadShapes(string fileName)
{
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
this.ReadShapes(stream);
}
}
/// <summary>
/// Read shapes (geometry) from the given stream.
/// </summary>
/// <param name="stream">Input stream for a shapefile.</param>
public void ReadShapes(Stream stream)
{
// Read the File Header.
this.ReadShapeFileHeader(stream);
// Read the shape records.
this.records.Clear();
while (true)
{
try
{
this.ReadShapeFileRecord(stream);
}
catch(IOException)
{
// Stop reading when EOF exception occurs.
break;
}
}
}
/// <summary>
/// Read the file header of the shapefile.
/// </summary>
/// <param name="stream">Input stream.</param>
public void ReadShapeFileHeader(Stream stream)
{
// File Code.
this.fileHeader.FileCode = ShapeFile.ReadInt32_BE(stream);
if ( this.fileHeader.FileCode != ShapeFile.expectedFileCode )
{
string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, Strings.ShapeFile_ErrorA_InvalidFileCode, ShapeFile.expectedFileCode);
throw new ApplicationException(msg);
}
// 5 unused values.
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
ShapeFile.ReadInt32_BE(stream);
// File Length.
this.fileHeader.FileLength = ShapeFile.ReadInt32_BE(stream);
// Version.
this.fileHeader.Version = ShapeFile.ReadInt32_LE(stream);
// Shape Type.
this.fileHeader.ShapeType = ShapeFile.ReadInt32_LE(stream);
// Bounding Box.
this.fileHeader.XMin = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.YMin = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.XMax = ShapeFile.ReadDouble64_LE(stream);
this.fileHeader.YMax = ShapeFile.ReadDouble64_LE(stream);
// Adjust the bounding box in case it is too small.
if ( Math.Abs(this.fileHeader.XMax - this.fileHeader.XMin) < 1 )
{
this.fileHeader.XMin -= 5;
this.fileHeader.XMax += 5;
}
if ( Math.Abs(this.fileHeader.YMax - this.fileHeader.YMin) < 1 )
{
this.fileHeader.YMin -= 5;
this.fileHeader.YMax += 5;
}
// Skip the rest of the file header.
stream.Seek(100, SeekOrigin.Begin);
}
/// <summary>
/// Read a shapefile record.
/// </summary>
/// <param name="stream">Input stream.</param>
public ShapeFileRecord ReadShapeFileRecord(Stream stream)
{
ShapeFileRecord record = new ShapeFileRecord();
// Record Header.
record.RecordNumber = ShapeFile.ReadInt32_BE(stream);
record.ContentLength = ShapeFile.ReadInt32_BE(stream);
// Shape Type.
record.ShapeType = ShapeFile.ReadInt32_LE(stream);
// Read the shape geometry, depending on its type.
switch (record.ShapeType)
{
case (int)ShapeType.NullShape:
// Do nothing.
break;
case (int)ShapeType.Point:
ShapeFile.ReadPoint(stream, record);
break;
case (int)ShapeType.PolyLine:
// PolyLine has exact same structure as Polygon in shapefile.
ShapeFile.ReadPolygon(stream, record);
break;
case (int)ShapeType.Polygon:
ShapeFile.ReadPolygon(stream, record);
break;
case (int)ShapeType.Multipoint:
ShapeFile.ReadMultipoint(stream, record);
break;
default:
{
string msg = String.Format(System.Globalization.CultureInfo.InvariantCulture, Strings.ShapeFile_ErrorA_ShapeTypeNotSupported, (int)record.ShapeType);
throw new ApplicationException(msg);
}
}
// Add the record to our internal list.
this.records.Add(record);
return record;
}
/// <summary>
/// Read the table from specified dBASE (DBF) file and
/// merge the rows with shapefile records.
/// </summary>
/// <remarks>
/// The filename of the dBASE file is expected to follow 8.3 naming
/// conventions. If it doesn't follow the convention, we try to
/// determine the 8.3 short name ourselves (but the name we come up
/// with may not be correct in all cases).
/// </remarks>
/// <param name="dbaseFile">Full file path of the dBASE (DBF) file.</param>
public void ReadAttributes(string dbaseFile)
{
if ( string.IsNullOrEmpty(dbaseFile) )
throw new ArgumentNullException("dbaseFile");
// Check if the file exists. If it doesn't exist,
// this is not an error.
if ( !File.Exists(dbaseFile) )
return;
// Get the directory in which the dBASE (DBF) file resides.
FileInfo fi = new FileInfo(dbaseFile);
string directory = fi.DirectoryName;
// Get the filename minus the extension.
string fileNameNoExt = fi.Name.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
if ( fileNameNoExt.EndsWith(".DBF") )
fileNameNoExt = fileNameNoExt.Substring(0, fileNameNoExt.Length - 4);
// Convert to a short filename (may not work in every case!).
if ( fileNameNoExt.Length > 8 )
{
if ( fileNameNoExt.Contains(" ") )
{
string noSpaces = fileNameNoExt.Replace(" ", "");
if ( noSpaces.Length > 8 )
fileNameNoExt = noSpaces;
}
fileNameNoExt = fileNameNoExt.Substring(0, 6) + "~1";
}
// Set the connection string.
string connectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + directory + ";Extended Properties=dBASE 5.0";
// Set the select query.
string selectQuery = "SELECT * FROM [" + fileNameNoExt + "#DBF];";
// Create a database connection object using the connection string.
OleDbConnection connection = new OleDbConnection(connectionString);
// Create a database command on the connection using the select query.
OleDbCommand command = new OleDbCommand(selectQuery, connection);
try
{
// Open the connection.
connection.Open();
// Create a data adapter to fill a dataset.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = command;
DataSet dataSet = new DataSet();
dataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(dataSet);
// Merge attributes into the shape file.
if ( dataSet.Tables.Count > 0 )
this.MergeAttributes(dataSet.Tables[0]);
}
catch ( OleDbException )
{
// Note: An exception will occur if the filename of the dBASE
// file does not follow 8.3 naming conventions. In this case,
// you must use its short (MS-DOS) filename.
// Rethrow the exception.
throw;
}
finally
{
// Dispose of connection.
((IDisposable)connection).Dispose();
}
}
/// <summary>
/// Output the File Header in the form of a string.
/// </summary>
/// <returns>A string representation of the file header.</returns>
public override string ToString()
{
return "ShapeFile: " + this.fileHeader.ToString();
}
#endregion Public methods
#region Private methods
/// <summary>
/// Read a 4-byte integer using little endian (Intel)
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The integer value.</returns>
private static int ReadInt32_LE(Stream stream)
{
for (int i = 0; i < 4; i++)
{
int b = stream.ReadByte();
if ( b == -1 )
throw new EndOfStreamException();
intBytes[i] = (byte)b;
}
return BitConverter.ToInt32(intBytes, 0);
}
/// <summary>
/// Read a 4-byte integer using big endian
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The integer value.</returns>
private static int ReadInt32_BE(Stream stream)
{
for (int i = 3; i >= 0; i--)
{
int b = stream.ReadByte();
if ( b == -1 )
throw new EndOfStreamException();
intBytes[i] = (byte)b;
}
return BitConverter.ToInt32(intBytes, 0);
}
/// <summary>
/// Read an 8-byte double using little endian (Intel)
/// byte ordering.
/// </summary>
/// <param name="stream">Input stream to read.</param>
/// <returns>The double value.</returns>
private static double ReadDouble64_LE(Stream stream)
{
for (int i = 0; i < 8; i++)
{
int b = stream.ReadByte();
if ( b == -1 )
throw new EndOfStreamException();
doubleBytes[i] = (byte)b;
}
return BitConverter.ToDouble(doubleBytes, 0);
}
/// <summary>
/// Read a shapefile Point record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadPoint(Stream stream, ShapeFileRecord record)
{
// Points - add a single point.
PointF p = new PointF();
p.X = (float)ShapeFile.ReadDouble64_LE(stream);
p.Y = (float)ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
// Bounding Box.
record.XMin = p.X;
record.YMin = p.Y;
record.XMax = record.XMin;
record.YMax = record.YMin;
}
/// <summary>
/// Read a shapefile MultiPoint record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadMultipoint(Stream stream, ShapeFileRecord record)
{
// Bounding Box.
record.XMin = ShapeFile.ReadDouble64_LE(stream);
record.YMin = ShapeFile.ReadDouble64_LE(stream);
record.XMax = ShapeFile.ReadDouble64_LE(stream);
record.YMax = ShapeFile.ReadDouble64_LE(stream);
// Num Points.
int numPoints = ShapeFile.ReadInt32_LE(stream);
// Points.
for (int i = 0; i < numPoints; i++)
{
PointF p = new PointF();
p.X = (float)ShapeFile.ReadDouble64_LE(stream);
p.Y = (float)ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
}
}
/// <summary>
/// Read a shapefile Polygon record.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <param name="record">Shapefile record to be updated.</param>
private static void ReadPolygon(Stream stream, ShapeFileRecord record)
{
// Bounding Box.
record.XMin = ShapeFile.ReadDouble64_LE(stream);
record.YMin = ShapeFile.ReadDouble64_LE(stream);
record.XMax = ShapeFile.ReadDouble64_LE(stream);
record.YMax = ShapeFile.ReadDouble64_LE(stream);
// Num Parts and Points.
int numParts = ShapeFile.ReadInt32_LE(stream);
int numPoints = ShapeFile.ReadInt32_LE(stream);
// Parts.
for (int i = 0; i < numParts; i++)
{
record.Parts.Add(ShapeFile.ReadInt32_LE(stream));
}
// Points.
for (int i = 0; i < numPoints; i++)
{
PointF p = new PointF();
p.X = (float)ShapeFile.ReadDouble64_LE(stream);
p.Y = (float)ShapeFile.ReadDouble64_LE(stream);
record.Points.Add(p);
}
}
/// <summary>
/// Merge data rows from the given table with
/// the shapefile records.
/// </summary>
/// <param name="table">Attributes table.</param>
private void MergeAttributes(DataTable table)
{
// For each data row, assign it to a shapefile record.
int index = 0;
foreach (DataRow row in table.Rows)
{
if ( index >= this.records.Count )
break;
this.records[index].Attributes = row;
++index;
}
}
#endregion Private methods
}
}
// END
| |
using System;
using System.Globalization;
// CoreFX creates SR in the System namespace. While putting the CoreCLR SR adapter in the root
// may be unconventional, it allows us to keep the shared code identical.
internal static class SR
{
public static string Arg_ArrayZeroError
{
get { return Environment.GetResourceString("Arg_ArrayZeroError"); }
}
public static string Arg_ExternalException
{
get { return Environment.GetResourceString("Arg_ExternalException"); }
}
public static string Arg_HexStyleNotSupported
{
get { return Environment.GetResourceString("Arg_HexStyleNotSupported"); }
}
public static string Arg_InvalidHexStyle
{
get { return Environment.GetResourceString("Arg_InvalidHexStyle"); }
}
public static string ArgumentNull_Array
{
get { return Environment.GetResourceString("ArgumentNull_Array"); }
}
public static string ArgumentNull_ArrayValue
{
get { return Environment.GetResourceString("ArgumentNull_ArrayValue"); }
}
public static string ArgumentNull_Obj
{
get { return Environment.GetResourceString("ArgumentNull_Obj"); }
}
public static string ArgumentNull_String
{
get { return Environment.GetResourceString("ArgumentNull_String"); }
}
public static string ArgumentOutOfRange_AddValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_AddValue"); }
}
public static string ArgumentOutOfRange_BadHourMinuteSecond
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); }
}
public static string ArgumentOutOfRange_BadYearMonthDay
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); }
}
public static string ArgumentOutOfRange_Bounds_Lower_Upper
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); }
}
public static string ArgumentOutOfRange_CalendarRange
{
get { return Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"); }
}
public static string ArgumentOutOfRange_Count
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Count"); }
}
public static string ArgumentOutOfRange_Day
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Day"); }
}
public static string ArgumentOutOfRange_Enum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Enum"); }
}
public static string ArgumentOutOfRange_Era
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Era"); }
}
public static string ArgumentOutOfRange_Index
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Index"); }
}
public static string ArgumentOutOfRange_IndexCountBuffer
{
get { return Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); }
}
public static string ArgumentOutOfRange_InvalidEraValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"); }
}
public static string ArgumentOutOfRange_Month
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Month"); }
}
public static string ArgumentOutOfRange_NeedNonNegNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); }
}
public static string ArgumentOutOfRange_NeedPosNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"); }
}
public static string Arg_ArgumentOutOfRangeException
{
get { return Environment.GetResourceString("Arg_ArgumentOutOfRangeException"); }
}
public static string ArgumentOutOfRange_OffsetLength
{
get { return Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"); }
}
public static string ArgumentOutOfRange_Range
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Range"); }
}
public static string Argument_CompareOptionOrdinal
{
get { return Environment.GetResourceString("Argument_CompareOptionOrdinal"); }
}
public static string Argument_ConflictingDateTimeRoundtripStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); }
}
public static string Argument_ConflictingDateTimeStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeStyles"); }
}
public static string Argument_CultureIetfNotSupported
{
get { return Environment.GetResourceString("Argument_CultureIetfNotSupported"); }
}
public static string Argument_CultureInvalidIdentifier
{
get { return Environment.GetResourceString("Argument_CultureInvalidIdentifier"); }
}
public static string Argument_CultureNotSupported
{
get { return Environment.GetResourceString("Argument_CultureNotSupported"); }
}
public static string Argument_CultureIsNeutral
{
get { return Environment.GetResourceString("Argument_CultureIsNeutral"); }
}
public static string Argument_CustomCultureCannotBePassedByNumber
{
get { return Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber"); }
}
public static string Argument_EmptyDecString
{
get { return Environment.GetResourceString("Argument_EmptyDecString"); }
}
public static string Argument_IdnBadLabelSize
{
get { return Environment.GetResourceString("Argument_IdnBadLabelSize"); }
}
public static string Argument_IdnBadPunycode
{
get { return Environment.GetResourceString("Argument_IdnBadPunycode"); }
}
public static string Argument_IdnIllegalName
{
get { return Environment.GetResourceString("Argument_IdnIllegalName"); }
}
public static string Argument_InvalidArrayLength
{
get { return Environment.GetResourceString("Argument_InvalidArrayLength"); }
}
public static string Argument_InvalidCalendar
{
get { return Environment.GetResourceString("Argument_InvalidCalendar"); }
}
public static string Argument_InvalidCharSequence
{
get { return Environment.GetResourceString("Argument_InvalidCharSequence"); }
}
public static string Argument_InvalidCultureName
{
get { return Environment.GetResourceString("Argument_InvalidCultureName"); }
}
public static string Argument_InvalidDateTimeStyles
{
get { return Environment.GetResourceString("Argument_InvalidDateTimeStyles"); }
}
public static string Argument_InvalidDigitSubstitution
{
get { return Environment.GetResourceString("Argument_InvalidDigitSubstitution"); }
}
public static string Argument_InvalidFlag
{
get { return Environment.GetResourceString("Argument_InvalidFlag"); }
}
public static string Argument_InvalidGroupSize
{
get { return Environment.GetResourceString("Argument_InvalidGroupSize"); }
}
public static string Argument_InvalidNativeDigitCount
{
get { return Environment.GetResourceString("Argument_InvalidNativeDigitCount"); }
}
public static string Argument_InvalidNativeDigitValue
{
get { return Environment.GetResourceString("Argument_InvalidNativeDigitValue"); }
}
public static string Argument_InvalidNeutralRegionName
{
get { return Environment.GetResourceString("Argument_InvalidNeutralRegionName"); }
}
public static string Argument_InvalidNumberStyles
{
get { return Environment.GetResourceString("Argument_InvalidNumberStyles"); }
}
public static string Argument_InvalidResourceCultureName
{
get { return Environment.GetResourceString("Argument_InvalidResourceCultureName"); }
}
public static string Argument_NoEra
{
get { return Environment.GetResourceString("Argument_NoEra"); }
}
public static string Argument_NoRegionInvariantCulture
{
get { return Environment.GetResourceString("Argument_NoRegionInvariantCulture"); }
}
public static string Argument_OneOfCulturesNotSupported
{
get { return Environment.GetResourceString("Argument_OneOfCulturesNotSupported"); }
}
public static string Argument_OnlyMscorlib
{
get { return Environment.GetResourceString("Argument_OnlyMscorlib"); }
}
public static string Argument_ResultCalendarRange
{
get { return Environment.GetResourceString("Argument_ResultCalendarRange"); }
}
public static string Format_BadFormatSpecifier
{
get { return Environment.GetResourceString("Format_BadFormatSpecifier"); }
}
public static string InvalidOperation_DateTimeParsing
{
get { return Environment.GetResourceString("InvalidOperation_DateTimeParsing"); }
}
public static string InvalidOperation_EnumEnded
{
get { return Environment.GetResourceString("InvalidOperation_EnumEnded"); }
}
public static string InvalidOperation_EnumNotStarted
{
get { return Environment.GetResourceString("InvalidOperation_EnumNotStarted"); }
}
public static string InvalidOperation_ReadOnly
{
get { return Environment.GetResourceString("InvalidOperation_ReadOnly"); }
}
public static string Overflow_TimeSpanTooLong
{
get { return Environment.GetResourceString("Overflow_TimeSpanTooLong"); }
}
public static string Serialization_MemberOutOfRange
{
get { return Environment.GetResourceString("Serialization_MemberOutOfRange"); }
}
public static string Arg_InvalidHandle
{
get { return Environment.GetResourceString("Arg_InvalidHandle"); }
}
public static string ObjectDisposed_FileClosed
{
get { return Environment.GetResourceString("ObjectDisposed_FileClosed"); }
}
public static string Arg_HandleNotAsync
{
get { return Environment.GetResourceString("Arg_HandleNotAsync"); }
}
public static string ArgumentNull_Path
{
get { return Environment.GetResourceString("ArgumentNull_Path"); }
}
public static string Argument_EmptyPath
{
get { return Environment.GetResourceString("Argument_EmptyPath"); }
}
public static string Argument_InvalidFileModeAndAccessCombo
{
get { return Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo"); }
}
public static string Argument_InvalidAppendMode
{
get { return Environment.GetResourceString("Argument_InvalidAppendMode"); }
}
public static string ArgumentNull_Buffer
{
get { return Environment.GetResourceString("ArgumentNull_Buffer"); }
}
public static string Argument_InvalidOffLen
{
get { return Environment.GetResourceString("Argument_InvalidOffLen"); }
}
public static string IO_UnknownFileName
{
get { return Environment.GetResourceString("IO_UnknownFileName"); }
}
public static string IO_FileStreamHandlePosition
{
get { return Environment.GetResourceString("IO.IO_FileStreamHandlePosition"); }
}
public static string NotSupported_FileStreamOnNonFiles
{
get { return Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"); }
}
public static string IO_BindHandleFailed
{
get { return Environment.GetResourceString("IO.IO_BindHandleFailed"); }
}
public static string Arg_HandleNotSync
{
get { return Environment.GetResourceString("Arg_HandleNotSync"); }
}
public static string IO_SetLengthAppendTruncate
{
get { return Environment.GetResourceString("IO.IO_SetLengthAppendTruncate"); }
}
public static string ArgumentOutOfRange_FileLengthTooBig
{
get { return Environment.GetResourceString("ArgumentOutOfRange_FileLengthTooBig"); }
}
public static string Argument_InvalidSeekOrigin
{
get { return Environment.GetResourceString("Argument_InvalidSeekOrigin"); }
}
public static string IO_SeekAppendOverwrite
{
get { return Environment.GetResourceString("IO.IO_SeekAppendOverwrite"); }
}
public static string IO_FileTooLongOrHandleNotSync
{
get { return Environment.GetResourceString("IO_FileTooLongOrHandleNotSync"); }
}
public static string IndexOutOfRange_IORaceCondition
{
get { return Environment.GetResourceString("IndexOutOfRange_IORaceCondition"); }
}
public static string IO_FileNotFound
{
get { return Environment.GetResourceString("IO.FileNotFound"); }
}
public static string IO_FileNotFound_FileName
{
get { return Environment.GetResourceString("IO.FileNotFound_FileName"); }
}
public static string IO_PathNotFound_NoPathName
{
get { return Environment.GetResourceString("IO.PathNotFound_NoPathName"); }
}
public static string IO_PathNotFound_Path
{
get { return Environment.GetResourceString("IO.PathNotFound_Path"); }
}
public static string UnauthorizedAccess_IODenied_NoPathName
{
get { return Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"); }
}
public static string UnauthorizedAccess_IODenied_Path
{
get { return Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"); }
}
public static string IO_AlreadyExists_Name
{
get { return Environment.GetResourceString("IO.IO_AlreadyExists_Name"); }
}
public static string IO_PathTooLong
{
get { return Environment.GetResourceString("IO.PathTooLong"); }
}
public static string IO_SharingViolation_NoFileName
{
get { return Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"); }
}
public static string IO_SharingViolation_File
{
get { return Environment.GetResourceString("IO.IO_SharingViolation_File"); }
}
public static string IO_FileExists_Name
{
get { return Environment.GetResourceString("IO.IO_FileExists_Name"); }
}
public static string NotSupported_UnwritableStream
{
get { return Environment.GetResourceString("NotSupported_UnwritableStream"); }
}
public static string NotSupported_UnreadableStream
{
get { return Environment.GetResourceString("NotSupported_UnreadableStream"); }
}
public static string NotSupported_UnseekableStream
{
get { return Environment.GetResourceString("NotSupported_UnseekableStream"); }
}
public static string IO_EOF_ReadBeyondEOF
{
get { return Environment.GetResourceString("IO.EOF_ReadBeyondEOF"); }
}
public static string Argument_InvalidHandle
{
get { return Environment.GetResourceString("Argument_InvalidHandle"); }
}
public static string Argument_AlreadyBoundOrSyncHandle
{
get { return Environment.GetResourceString("Argument_AlreadyBoundOrSyncHandle"); }
}
public static string Argument_PreAllocatedAlreadyAllocated
{
get { return Environment.GetResourceString("Argument_PreAllocatedAlreadyAllocated"); }
}
public static string Argument_NativeOverlappedAlreadyFree
{
get { return Environment.GetResourceString("Argument_NativeOverlappedAlreadyFree"); }
}
public static string Argument_NativeOverlappedWrongBoundHandle
{
get { return Environment.GetResourceString("Argument_NativeOverlappedWrongBoundHandle"); }
}
public static string InvalidOperation_NativeOverlappedReused
{
get { return Environment.GetResourceString("InvalidOperation_NativeOverlappedReused"); }
}
public static string ArgumentOutOfRange_Length
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Length"); }
}
public static string ArgumentOutOfRange_IndexString
{
get { return Environment.GetResourceString("ArgumentOutOfRange_IndexString"); }
}
public static string ArgumentOutOfRange_Capacity
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Capacity"); }
}
public static string Arg_CryptographyException
{
get { return Environment.GetResourceString("Arg_CryptographyException"); }
}
public static string ArgumentException_BufferNotFromPool
{
get { return Environment.GetResourceString("ArgumentException_BufferNotFromPool"); }
}
public static string Argument_InvalidPathChars
{
get { return Environment.GetResourceString("Argument_InvalidPathChars"); }
}
public static string Argument_PathFormatNotSupported
{
get { return Environment.GetResourceString("Argument_PathFormatNotSupported"); }
}
public static string Arg_PathIllegal
{
get { return Environment.GetResourceString("Arg_PathIllegal"); }
}
public static string Arg_PathIllegalUNC
{
get { return Environment.GetResourceString("Arg_PathIllegalUNC"); }
}
public static string Arg_InvalidSearchPattern
{
get { return Environment.GetResourceString("Arg_InvalidSearchPattern"); }
}
public static string InvalidOperation_Cryptography
{
get { return Environment.GetResourceString("InvalidOperation_Cryptography"); }
}
public static string Format(string formatString, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, formatString, args);
}
internal static string ArgumentException_ValueTupleIncorrectType
{
get { return Environment.GetResourceString("ArgumentException_ValueTupleIncorrectType"); }
}
internal static string ArgumentException_ValueTupleLastArgumentNotATuple
{
get { return Environment.GetResourceString("ArgumentException_ValueTupleLastArgumentNotATuple"); }
}
internal static string SpinLock_TryEnter_ArgumentOutOfRange
{
get { return Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"); }
}
internal static string SpinLock_TryReliableEnter_ArgumentException
{
get { return Environment.GetResourceString("SpinLock_TryReliableEnter_ArgumentException"); }
}
internal static string SpinLock_TryEnter_LockRecursionException
{
get { return Environment.GetResourceString("SpinLock_TryEnter_LockRecursionException"); }
}
internal static string SpinLock_Exit_SynchronizationLockException
{
get { return Environment.GetResourceString("SpinLock_Exit_SynchronizationLockException"); }
}
internal static string SpinLock_IsHeldByCurrentThread
{
get { return Environment.GetResourceString("SpinLock_IsHeldByCurrentThread"); }
}
internal static string ObjectDisposed_StreamIsClosed
{
get { return Environment.GetResourceString("ObjectDisposed_StreamIsClosed"); }
}
internal static string Arg_SystemException
{
get { return Environment.GetResourceString("Arg_SystemException"); }
}
internal static string Arg_StackOverflowException
{
get { return Environment.GetResourceString("Arg_StackOverflowException"); }
}
internal static string Arg_DataMisalignedException
{
get { return Environment.GetResourceString("Arg_DataMisalignedException"); }
}
internal static string Arg_ExecutionEngineException
{
get { return Environment.GetResourceString("Arg_ExecutionEngineException"); }
}
internal static string Arg_AccessException
{
get { return Environment.GetResourceString("Arg_AccessException"); }
}
internal static string Arg_AccessViolationException
{
get { return Environment.GetResourceString("Arg_AccessViolationException"); }
}
internal static string Arg_ApplicationException
{
get { return Environment.GetResourceString("Arg_ApplicationException"); }
}
internal static string Arg_ArgumentException
{
get { return Environment.GetResourceString("Arg_ArgumentException"); }
}
internal static string Arg_ParamName_Name
{
get { return Environment.GetResourceString("Arg_ParamName_Name"); }
}
internal static string ArgumentNull_Generic
{
get { return Environment.GetResourceString("ArgumentNull_Generic"); }
}
internal static string Arg_ArithmeticException
{
get { return Environment.GetResourceString("Arg_ArithmeticException"); }
}
internal static string Arg_ArrayTypeMismatchException
{
get { return Environment.GetResourceString("Arg_ArrayTypeMismatchException"); }
}
internal static string Arg_DivideByZero
{
get { return Environment.GetResourceString("Arg_DivideByZero"); }
}
internal static string Arg_DuplicateWaitObjectException
{
get { return Environment.GetResourceString("Arg_DuplicateWaitObjectException"); }
}
internal static string Arg_EntryPointNotFoundException
{
get { return Environment.GetResourceString("Arg_EntryPointNotFoundException"); }
}
internal static string Arg_FieldAccessException
{
get { return Environment.GetResourceString("Arg_FieldAccessException"); }
}
internal static string Arg_FormatException
{
get { return Environment.GetResourceString("Arg_FormatException"); }
}
internal static string Arg_IndexOutOfRangeException
{
get { return Environment.GetResourceString("Arg_IndexOutOfRangeException"); }
}
internal static string Arg_InsufficientExecutionStackException
{
get { return Environment.GetResourceString("Arg_InsufficientExecutionStackException"); }
}
internal static string Arg_InvalidCastException
{
get { return Environment.GetResourceString("Arg_InvalidCastException"); }
}
internal static string Arg_InvalidOperationException
{
get { return Environment.GetResourceString("Arg_InvalidOperationException"); }
}
internal static string InvalidProgram_Default
{
get { return Environment.GetResourceString("InvalidProgram_Default"); }
}
internal static string Arg_MethodAccessException
{
get { return Environment.GetResourceString("Arg_MethodAccessException"); }
}
internal static string Arg_MulticastNotSupportedException
{
get { return Environment.GetResourceString("Arg_MulticastNotSupportedException"); }
}
internal static string Arg_NotFiniteNumberException
{
get { return Environment.GetResourceString("Arg_NotFiniteNumberException"); }
}
internal static string Arg_NotImplementedException
{
get { return Environment.GetResourceString("Arg_NotImplementedException"); }
}
internal static string Arg_NotSupportedException
{
get { return Environment.GetResourceString("Arg_NotSupportedException"); }
}
internal static string Arg_NullReferenceException
{
get { return Environment.GetResourceString("Arg_NullReferenceException"); }
}
internal static string ObjectDisposed_Generic
{
get { return Environment.GetResourceString("ObjectDisposed_Generic"); }
}
internal static string ObjectDisposed_ObjectName_Name
{
get { return Environment.GetResourceString("ObjectDisposed_ObjectName_Name"); }
}
internal static string Arg_OverflowException
{
get { return Environment.GetResourceString("Arg_OverflowException"); }
}
internal static string Arg_PlatformNotSupported
{
get { return Environment.GetResourceString("Arg_PlatformNotSupported"); }
}
internal static string Arg_RankException
{
get { return Environment.GetResourceString("Arg_RankException"); }
}
internal static string Arg_TimeoutException
{
get { return Environment.GetResourceString("Arg_TimeoutException"); }
}
internal static string Arg_TypeAccessException
{
get { return Environment.GetResourceString("Arg_TypeAccessException"); }
}
internal static string TypeInitialization_Default
{
get { return Environment.GetResourceString("TypeInitialization_Default"); }
}
internal static string TypeInitialization_Type
{
get { return Environment.GetResourceString("TypeInitialization_Type"); }
}
internal static string Arg_UnauthorizedAccessException
{
get { return Environment.GetResourceString("Arg_UnauthorizedAccessException"); }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Vici.Core.StringExtensions;
namespace Vici.Core.Json
{
public class JsonObject : IFormattable, IEnumerable<JsonObject>
{
private static readonly JsonObject _emptyInstance = new JsonObject(empty:true);
private readonly object _value;
private readonly bool _empty;
internal JsonObject(object value = null, bool empty = false)
{
_value = value;
_empty = empty;
}
public bool IsObject { get { return _value is Dictionary<string, JsonObject>; }}
public bool IsArray { get { return _value is JsonObject[]; } }
public bool IsValue { get { return !IsObject && !IsArray; }}
public bool IsEmpty { get { return _empty; }}
public bool IsNull { get { return _value == null && !_empty; } }
public bool IsNullOrEmpty { get { return _value == null; } }
internal object Value { get { return _value; } }
public object As(Type type)
{
return _value.Convert(type);
}
public T As<T>()
{
return _value.Convert<T>();
}
public static implicit operator string(JsonObject jsonObject)
{
return jsonObject.As<string>();
}
public static implicit operator int(JsonObject jsonObject)
{
return jsonObject.As<int>();
}
public static implicit operator long(JsonObject jsonObject)
{
return jsonObject.As<long>();
}
public static implicit operator double(JsonObject jsonObject)
{
return jsonObject.As<double>();
}
public static implicit operator decimal(JsonObject jsonObject)
{
return jsonObject.As<decimal>();
}
public JsonObject[] AsArray()
{
return _value as JsonObject[];
}
public T[] AsArray<T>()
{
if (!IsArray)
return null;
return AsArray().Select(x => x.As<T>()).ToArray();
}
public Dictionary<string, JsonObject> AsDictionary()
{
return _value as Dictionary<string,JsonObject>;
}
public string[] Keys
{
get { return IsObject ? AsDictionary().Keys.ToArray() : new string[0]; }
}
public JsonObject this[string key]
{
get
{
return ValueForExpression(this, key);
}
}
public JsonObject this[int index]
{
get
{
if (!IsArray || index >= AsArray().Length)
return _emptyInstance;
return AsArray()[index];
}
}
private static IEnumerable<string> AllKeyParts(string key)
{
int index = 0;
for (; ; )
{
int dotIndex = key.IndexOf('.', index);
if (dotIndex < 0)
{
yield return key;
break;
}
yield return key.Substring(0, dotIndex);
index = dotIndex + 1;
}
}
private static JsonObject ValueForExpression(JsonObject obj, string key)
{
if (!obj.IsObject)
return _emptyInstance;
foreach (var keyPart in AllKeyParts(key).Reverse().ToArray())
{
var dic = obj.AsDictionary();
if (dic.ContainsKey(keyPart))
{
var value = dic[keyPart];
if (keyPart.Length == key.Length)
return value;
string key2 = key.Substring(keyPart.Length + 1);
return ValueForExpression(value,key2);
}
}
return null;
}
public IEnumerator<JsonObject> GetEnumerator()
{
if (IsObject)
{
return AsDictionary().Values.GetEnumerator();
}
else if (IsArray)
{
return (from obj in AsArray() select obj).GetEnumerator();
}
else
{
return (IEnumerator<JsonObject>) (new[] {this}).GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string format, IFormatProvider formatProvider)
{
#if DEBUG
if (IsArray)
return "[" + AsArray().Length + " items]";
if (IsObject)
return "{...}";
if (_value == null)
return "(null)";
if (_value is IFormattable && format != null)
return ((IFormattable) _value).ToString(format, formatProvider);
#endif
return _value.ToString();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// STACC Holding Table
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TRSTACC : EduHubEntity
{
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Sequence no
/// </summary>
public int STACCKEY { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD01 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD02 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD03 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD04 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD05 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD06 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD07 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD08 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD09 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD10 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD11 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD12 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD13 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD14 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD15 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD16 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD17 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD18 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD19 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD20 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD21 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD22 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD23 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD24 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD25 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD26 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD27 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD28 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD29 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD30 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD31 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD32 { get; internal set; }
/// <summary>
/// Data Fields
/// [Alphanumeric (60)]
/// </summary>
public string FIELD33 { get; internal set; }
/// <summary>
/// Error with data row
/// </summary>
public short? ERR_FIELD { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? AM_UMKEY { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public int? PM_UMKEY { 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
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.VR;
using System.Linq;
using UnityEngine.Events;
namespace NewtonVR
{
public class NVRPlayer : MonoBehaviour
{
public const decimal NewtonVRVersion = 1.4m;
public const float NewtonVRExpectedDeltaTime = 0.0111f;
public static List<NVRPlayer> Instances = new List<NVRPlayer>();
public static NVRPlayer Instance
{
get
{
return Instances.First(player => player != null && player.gameObject != null);
}
}
[HideInInspector]
public bool SteamVREnabled = false;
[HideInInspector]
public bool OculusSDKEnabled = false;
[HideInInspector]
public bool WindowsMREnabled = false;
public InterationStyle InteractionStyle;
public bool PhysicalHands = true;
public bool MakeControllerInvisibleOnInteraction = false;
public bool AutomaticallySetControllerTransparency = true;
public bool VibrateOnHover = true;
public int VelocityHistorySteps = 3;
public UnityEvent OnInitialized;
[Space]
public bool EnableEditorPlayerPreview = true;
public Mesh EditorPlayerPreview;
public Mesh EditorPlayspacePreview;
public bool EditorPlayspaceOverride = false;
public Vector2 EditorPlayspaceDefault = new Vector2(2, 1.5f);
public Vector3 PlayspaceSize
{
get
{
#if !UNITY_5_5_OR_NEWER
if (Application.isPlaying == false)
{
return Vector3.zero; //not supported in unity below 5.5.
}
#endif
if (Integration != null)
{
return Integration.GetPlayspaceBounds();
}
else
{
if (OculusSDKEnabled == true)
{
Integration = new NVROculusIntegration();
if (Integration.IsHmdPresent() == true)
{
return Integration.GetPlayspaceBounds();
}
else
{
Integration = null;
}
}
if (SteamVREnabled == true)
{
Integration = new NVRSteamVRIntegration();
if (Integration.IsHmdPresent() == true)
{
return Integration.GetPlayspaceBounds();
}
else
{
Integration = null;
}
}
if (WindowsMREnabled == true)
{
Integration = new NVRWindowsMRIntegration();
if (Integration.IsHmdPresent() == true)
{
return Integration.GetPlayspaceBounds();
}
else
{
Integration = null;
}
}
return Vector3.zero;
}
}
}
[Space]
[HideInInspector]
public bool OverrideAll;
[HideInInspector]
public GameObject OverrideAllLeftHand;
[HideInInspector]
public GameObject OverrideAllLeftHandPhysicalColliders;
[HideInInspector]
public GameObject OverrideAllRightHand;
[HideInInspector]
public GameObject OverrideAllRightHandPhysicalColliders;
[HideInInspector]
public bool OverrideSteamVR;
[HideInInspector]
public GameObject OverrideSteamVRLeftHand;
[HideInInspector]
public GameObject OverrideSteamVRLeftHandPhysicalColliders;
[HideInInspector]
public GameObject OverrideSteamVRRightHand;
[HideInInspector]
public GameObject OverrideSteamVRRightHandPhysicalColliders;
[HideInInspector]
public bool OverrideOculus;
[HideInInspector]
public GameObject OverrideOculusLeftHand;
[HideInInspector]
public GameObject OverrideOculusLeftHandPhysicalColliders;
[HideInInspector]
public GameObject OverrideOculusRightHand;
[HideInInspector]
public GameObject OverrideOculusRightHandPhysicalColliders;
[Space]
public NVRHead Head;
public NVRHand LeftHand;
public NVRHand RightHand;
[HideInInspector]
public NVRHand[] Hands;
[HideInInspector]
public NVRSDKIntegrations CurrentIntegrationType = NVRSDKIntegrations.None;
private NVRIntegration Integration;
private Dictionary<Collider, NVRHand> ColliderToHandMapping;
[Space]
public bool DEBUGEnableFallback2D = false;
public bool DEBUGDropFrames = false;
public int DEBUGSleepPerFrame = 13;
public bool AutoSetFixedDeltaTime = true;
public bool NotifyOnVersionUpdate = true;
private void Awake()
{
if (AutoSetFixedDeltaTime)
{
Time.fixedDeltaTime = NewtonVRExpectedDeltaTime;
}
Instances.Add(this);
NVRInteractables.Initialize();
if (Head == null)
{
Head = this.GetComponentInChildren<NVRHead>();
}
Head.Initialize();
if (LeftHand == null || RightHand == null)
{
Debug.LogError("[FATAL ERROR] Please set the left and right hand to an NVRHand.");
}
ColliderToHandMapping = new Dictionary<Collider, NVRHand>();
SetupIntegration();
if (Hands == null || Hands.Length == 0)
{
Hands = new NVRHand[] { LeftHand, RightHand };
for (int index = 0; index < Hands.Length; index++)
{
Hands[index].PreInitialize(this);
}
}
if (Integration != null)
{
Integration.Initialize(this);
}
if (OnInitialized != null)
{
OnInitialized.Invoke();
}
}
private void SetupIntegration(bool logOutput = true)
{
CurrentIntegrationType = DetermineCurrentIntegration(logOutput);
if (CurrentIntegrationType == NVRSDKIntegrations.Oculus)
{
Integration = new NVROculusIntegration();
}
else if (CurrentIntegrationType == NVRSDKIntegrations.SteamVR)
{
Integration = new NVRSteamVRIntegration();
}
else if (CurrentIntegrationType == NVRSDKIntegrations.WindowsMR)
{
Integration = new NVRWindowsMRIntegration();
}
else if (CurrentIntegrationType == NVRSDKIntegrations.FallbackNonVR)
{
if (logOutput == true)
{
Debug.LogError("[NewtonVR] Fallback non-vr not yet implemented.");
}
return;
}
else
{
if (logOutput == true)
{
Debug.LogError("[NewtonVR] Critical Error: Oculus / SteamVR not setup properly or no headset found.");
}
return;
}
}
private NVRSDKIntegrations DetermineCurrentIntegration(bool logOutput = true)
{
NVRSDKIntegrations currentIntegration = NVRSDKIntegrations.None;
string resultLog = "[NewtonVR] Version : " + NewtonVRVersion + ". ";
string deviceName = null;
#if UNITY_2017_2_OR_NEWER
if (UnityEngine.XR.XRDevice.isPresent == true)
deviceName = UnityEngine.XR.XRDevice.model;
#else
if (UnityEngine.VR.VRDevice.isPresent == true)
deviceName = UnityEngine.VR.VRDevice.model;
#endif
if (deviceName != null)
{
resultLog += "Found VRDevice: " + deviceName + ". ";
#if NVR_Oculus
if (VRDevice.model.IndexOf("oculus", System.StringComparison.CurrentCultureIgnoreCase) != -1)
{
currentIntegration = NVRSDKIntegrations.Oculus;
resultLog += "Using Oculus SDK";
}
#endif
#if NVR_SteamVR
if (currentIntegration == NVRSDKIntegrations.None)
{
currentIntegration = NVRSDKIntegrations.SteamVR;
resultLog += "Using SteamVR SDK";
}
#endif
#if NVR_WindowsMR
if (currentIntegration == NVRSDKIntegrations.None)
{
currentIntegration = NVRSDKIntegrations.WindowsMR;
resultLog += "Using WindowsMR SDK";
}
#endif
}
if (currentIntegration == NVRSDKIntegrations.None)
{
if (DEBUGEnableFallback2D == true)
{
currentIntegration = NVRSDKIntegrations.FallbackNonVR;
}
else
{
resultLog += "Did not find supported VR device. Or no integrations enabled.";
}
}
#if !NVR_Oculus && !NVR_SteamVR && !NVR_WindowsMR
string warning = "No VR SDk has been enabled in the NVRPlayer. Please check the \"Enable SteamVR\" / \"Enable Oculus SDK\" / \"Enable Windows MR\" checkbox in the NVRPlayer script in the NVRPlayer GameObject.";
Debug.LogWarning(warning);
#endif
if (logOutput == true)
{
Debug.Log(resultLog);
}
return currentIntegration;
}
public void RegisterHand(NVRHand hand)
{
Collider[] colliders = hand.GetComponentsInChildren<Collider>();
for (int index = 0; index < colliders.Length; index++)
{
if (ColliderToHandMapping.ContainsKey(colliders[index]) == false)
{
ColliderToHandMapping.Add(colliders[index], hand);
}
}
}
public NVRHand GetHand(Collider collider)
{
return ColliderToHandMapping[collider];
}
public static void DeregisterInteractable(NVRInteractable interactable)
{
for (int instanceIndex = 0; instanceIndex < Instances.Count; instanceIndex++)
{
if (Instances[instanceIndex] != null && Instances[instanceIndex].Hands != null)
{
for (int index = 0; index < Instances[instanceIndex].Hands.Length; index++)
{
if (Instances[instanceIndex].Hands[index] != null)
{
Instances[instanceIndex].Hands[index].DeregisterInteractable(interactable);
}
}
}
}
}
private void OnDestroy()
{
Instances.Remove(this);
}
private void Update()
{
if (DEBUGDropFrames == true)
{
System.Threading.Thread.Sleep(DEBUGSleepPerFrame);
}
}
#if UNITY_EDITOR
private static System.DateTime LastRequestedSize;
private static Vector3 CachedPlayspaceScale;
private void OnDrawGizmos()
{
if (EnableEditorPlayerPreview == false)
return;
if (Application.isPlaying == true)
return;
System.TimeSpan lastRequested = System.DateTime.Now - LastRequestedSize;
Vector3 playspaceScale;
if (lastRequested.TotalSeconds > 1)
{
if (EditorPlayspaceOverride == false)
{
Vector3 returnedPlayspaceSize = PlayspaceSize;
if (returnedPlayspaceSize == Vector3.zero)
{
playspaceScale = EditorPlayspaceDefault;
playspaceScale.z = playspaceScale.y;
}
else
{
playspaceScale = returnedPlayspaceSize;
}
}
else
{
playspaceScale = EditorPlayspaceDefault;
playspaceScale.z = playspaceScale.y;
}
playspaceScale.y = 1f;
LastRequestedSize = System.DateTime.Now;
}
else
{
playspaceScale = CachedPlayspaceScale;
}
CachedPlayspaceScale = playspaceScale;
Color drawColor = Color.green;
drawColor.a = 0.075f;
Gizmos.color = drawColor;
Gizmos.DrawWireMesh(EditorPlayerPreview, this.transform.position, this.transform.rotation, this.transform.localScale);
drawColor.a = 0.5f;
Gizmos.color = drawColor;
Gizmos.DrawWireMesh(EditorPlayspacePreview, this.transform.position, this.transform.rotation, playspaceScale * this.transform.localScale.x);
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// PartitionedDataSource.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// Contiguous range chunk partitioning attempts to improve data locality by keeping
/// data close together in the incoming data stream together in the outgoing partitions.
/// There are really three types of partitions that are used internally:
///
/// 1. If the data source is indexable--like an array or List_T--we can actually
/// just compute the range indexes and avoid doing any copying whatsoever. Each
/// "partition" is just an enumerator that will walk some subset of the data.
/// 2. If the data source has an index (different than being indexable!), we can
/// turn this into a range scan of the index. We can roughly estimate distribution
/// and ensure an evenly balanced set of partitions.
/// 3. If we can't use 1 or 2, we instead partition "on demand" by chunking the contents
/// of the source enumerator as they are requested. The unfortunate thing is that
/// this requires synchronization, since consumers may be running in parallel. We
/// amortize the cost of this by giving chunks of items when requested instead of
/// one element at a time. Note that this approach also works for infinite streams.
///
/// In all cases, the caller can request that enumerators walk elements in striped
/// contiguous chunks. If striping is requested, then each partition j will yield elements
/// in the data source for which ((i / s)%p) == j, where i is the element's index, s is
/// a chunk size calculated by the system with the intent of aligning on cache lines, and
/// p is the number of partitions. If striping is not requested, we use the same algorithm,
/// only, instead of aligning on cache lines, we use a chunk size of l / p, where l
/// is the length of the input and p is the number of partitions.
///
/// Notes:
/// This is used as the default partitioning strategy by much of the PLINQ infrastructure.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class PartitionedDataSource<T> : PartitionedStream<T, int>
{
//---------------------------------------------------------------------------------------
// Just constructs a new partition stream.
//
internal PartitionedDataSource(IEnumerable<T> source, int partitionCount, bool useStriping)
: base(
partitionCount,
Util.GetDefaultComparer<int>(),
source is IList<T> ? OrdinalIndexState.Indexable : OrdinalIndexState.Correct)
{
InitializePartitions(source, partitionCount, useStriping);
}
//---------------------------------------------------------------------------------------
// This method just creates the individual partitions given a data source.
//
// Notes:
// We check whether the data source is an IList<T> and, if so, we can partition
// "in place" by calculating a set of indexes. Otherwise, we return an enumerator that
// performs partitioning lazily. Depending on which case it is, the enumerator may
// contain synchronization (i.e. the latter case), meaning callers may occasionally
// block when enumerating it.
//
private void InitializePartitions(IEnumerable<T> source, int partitionCount, bool useStriping)
{
Debug.Assert(source != null);
Debug.Assert(partitionCount > 0);
// If this is a wrapper, grab the internal wrapped data source so we can uncover its real type.
ParallelEnumerableWrapper<T> wrapper = source as ParallelEnumerableWrapper<T>;
if (wrapper != null)
{
source = wrapper.WrappedEnumerable;
Debug.Assert(source != null);
}
// Check whether we have an indexable data source.
IList<T> sourceAsList = source as IList<T>;
if (sourceAsList != null)
{
QueryOperatorEnumerator<T, int>[] partitions = new QueryOperatorEnumerator<T, int>[partitionCount];
// We use this below to specialize enumerators when possible.
T[] sourceAsArray = source as T[];
// If range partitioning is used, chunk size will be unlimited, i.e. -1.
int maxChunkSize = -1;
if (useStriping)
{
maxChunkSize = Scheduling.GetDefaultChunkSize<T>();
// The minimum chunk size is 1.
if (maxChunkSize < 1)
{
maxChunkSize = 1;
}
}
// Calculate indexes and construct enumerators that walk a subset of the input.
for (int i = 0; i < partitionCount; i++)
{
if (sourceAsArray != null)
{
// If the source is an array, we can use a fast path below to index using
// 'ldelem' instructions rather than making interface method calls.
if (useStriping)
{
partitions[i] = new ArrayIndexRangeEnumerator(sourceAsArray, partitionCount, i, maxChunkSize);
}
else
{
partitions[i] = new ArrayContiguousIndexRangeEnumerator(sourceAsArray, partitionCount, i);
}
TraceHelpers.TraceInfo("ContiguousRangePartitionExchangeStream::MakePartitions - (array) #{0} {1}", i, maxChunkSize);
}
else
{
// Create a general purpose list enumerator object.
if (useStriping)
{
partitions[i] = new ListIndexRangeEnumerator(sourceAsList, partitionCount, i, maxChunkSize);
}
else
{
partitions[i] = new ListContiguousIndexRangeEnumerator(sourceAsList, partitionCount, i);
}
TraceHelpers.TraceInfo("ContiguousRangePartitionExchangeStream::MakePartitions - (list) #{0} {1})", i, maxChunkSize);
}
}
Debug.Assert(partitions.Length == partitionCount);
_partitions = partitions;
}
else
{
// We couldn't use an in-place partition. Shucks. Defer to the other overload which
// accepts an enumerator as input instead.
_partitions = MakePartitions(source.GetEnumerator(), partitionCount);
}
}
//---------------------------------------------------------------------------------------
// This method just creates the individual partitions given a data source. See the base
// class for more details on this method's contracts. This version takes an enumerator,
// and so it can't actually do an in-place partition. We'll instead create enumerators
// that coordinate with one another to lazily (on demand) grab chunks from the enumerator.
// This clearly is much less efficient than the fast path above since it requires
// synchronization. We try to amortize that cost by retrieving many elements at once
// instead of just one-at-a-time.
//
private static QueryOperatorEnumerator<T, int>[] MakePartitions(IEnumerator<T> source, int partitionCount)
{
Debug.Assert(source != null);
Debug.Assert(partitionCount > 0);
// At this point we were unable to efficiently partition the data source. Instead, we
// will return enumerators that lazily partition the data source.
QueryOperatorEnumerator<T, int>[] partitions = new QueryOperatorEnumerator<T, int>[partitionCount];
// The following is used for synchronization between threads.
object sharedSyncLock = new object();
Shared<int> sharedCurrentIndex = new Shared<int>(0);
Shared<int> sharedPartitionCount = new Shared<int>(partitionCount);
Shared<bool> sharedExceptionTracker = new Shared<bool>(false);
// Create a new lazy chunking enumerator per partition, sharing the same lock.
for (int i = 0; i < partitionCount; i++)
{
partitions[i] = new ContiguousChunkLazyEnumerator(
source, sharedExceptionTracker, sharedSyncLock, sharedCurrentIndex, sharedPartitionCount);
}
return partitions;
}
//---------------------------------------------------------------------------------------
// This enumerator walks a range within an indexable data type. It's abstract. We assume
// callers have validated that the ranges are legal given the data. IndexRangeEnumerator
// handles both striped and range partitioning.
//
// PLINQ creates one IndexRangeEnumerator per partition. Together, the enumerators will
// cover the entire list or array.
//
// In this context, the term "range" represents the entire array or list. The range is
// split up into one or more "sections". Each section is split up into as many "chunks" as
// we have partitions. i-th chunk in each section is assigned to partition i.
//
// All sections but the last one contain partitionCount * maxChunkSize elements, except
// for the last section which may contain fewer.
//
// For example, if the input is an array with 2,101 elements, maxChunkSize is 128
// and partitionCount is 4, all sections except the last one will contain 128*4 = 512
// elements. The last section will contain 2,101 - 4*512 = 53 elements.
//
// All sections but the last one will be evenly divided among partitions: the first 128
// elements will go into partition 0, the next 128 elements into partition 1, etc.
//
// The last section is divided as evenly as possible. In the above example, the split would
// be 14-13-13-13.
//
// A copy of the index enumerator specialized for array indexing. It uses 'ldelem'
// instructions for element retrieval, rather than using a method call.
internal sealed class ArrayIndexRangeEnumerator : QueryOperatorEnumerator<T, int>
{
private readonly T[] _data; // The elements to iterate over.
private readonly int _elementCount; // The number of elements to iterate over.
private readonly int _partitionCount; // The number of partitions.
private readonly int _partitionIndex; // The index of the current partition.
private readonly int _maxChunkSize; // The maximum size of a chunk. -1 if unlimited.
private readonly int _sectionCount; // Precomputed in ctor: the number of sections the range is split into.
private Mutables _mutables; // Lazily allocated mutable variables.
class Mutables
{
internal Mutables()
{
// Place the enumerator just before the first element
_currentSection = -1;
}
internal int _currentSection; // 0-based index of the current section.
internal int _currentChunkSize; // The number of elements in the current chunk.
internal int _currentPositionInChunk; // 0-based position within the current chunk.
internal int _currentChunkOffset; // The offset of the current chunk from the beginning of the range.
}
internal ArrayIndexRangeEnumerator(T[] data, int partitionCount, int partitionIndex, int maxChunkSize)
{
Debug.Assert(data != null, "data mustn't be null");
Debug.Assert(partitionCount > 0, "partitionCount must be positive");
Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative");
Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount");
Debug.Assert(maxChunkSize > 0, "maxChunkSize must be positive or -1");
_data = data;
_elementCount = data.Length;
_partitionCount = partitionCount;
_partitionIndex = partitionIndex;
_maxChunkSize = maxChunkSize;
int sectionSize = maxChunkSize * partitionCount;
Debug.Assert(sectionSize > 0);
// Section count is ceiling(elementCount / sectionSize)
_sectionCount = _elementCount / sectionSize +
((_elementCount % sectionSize) == 0 ? 0 : 1);
}
internal override bool MoveNext(ref T currentElement, ref int currentKey)
{
// Lazily allocate the mutable holder.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
}
// If we are aren't within the chunk, we need to find another.
if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath())
{
currentKey = mutables._currentChunkOffset + mutables._currentPositionInChunk;
currentElement = _data[currentKey];
return true;
}
return false;
}
private bool MoveNextSlowPath()
{
Mutables mutables = _mutables;
Debug.Assert(mutables != null);
Debug.Assert(mutables._currentPositionInChunk >= mutables._currentChunkSize);
// Move on to the next section.
int currentSection = ++mutables._currentSection;
int sectionsRemaining = _sectionCount - currentSection;
// If empty, return right away.
if (sectionsRemaining <= 0)
{
return false;
}
// Compute the offset of the current section from the beginning of the range
int currentSectionOffset = currentSection * _partitionCount * _maxChunkSize;
mutables._currentPositionInChunk = 0;
// Now do something different based on how many chunks remain.
if (sectionsRemaining > 1)
{
// We are not on the last section. The size of this chunk is simply _maxChunkSize.
mutables._currentChunkSize = _maxChunkSize;
mutables._currentChunkOffset = currentSectionOffset + _partitionIndex * _maxChunkSize;
}
else
{
// We are on the last section. Compute the size of the chunk to ensure even distribution
// of elements.
int lastSectionElementCount = _elementCount - currentSectionOffset;
int smallerChunkSize = lastSectionElementCount / _partitionCount;
int biggerChunkCount = lastSectionElementCount % _partitionCount;
mutables._currentChunkSize = smallerChunkSize;
if (_partitionIndex < biggerChunkCount)
{
mutables._currentChunkSize++;
}
if (mutables._currentChunkSize == 0)
{
return false;
}
mutables._currentChunkOffset =
currentSectionOffset // The beginning of this section
+ _partitionIndex * smallerChunkSize // + the start of this chunk if all chunks were "smaller"
+ (_partitionIndex < biggerChunkCount ? _partitionIndex : biggerChunkCount); // + the number of "bigger" chunks before this chunk
}
return true;
}
}
// A contiguous index enumerator specialized for array indexing. It uses 'ldelem'
// instructions for element retrieval, rather than using a method call.
internal sealed class ArrayContiguousIndexRangeEnumerator : QueryOperatorEnumerator<T, int>
{
private readonly T[] _data; // The elements to iterate over.
private readonly int _startIndex; // Where to begin iterating.
private readonly int _maximumIndex; // The maximum index to iterate over.
private Shared<int> _currentIndex; // The current index (lazily allocated).
internal ArrayContiguousIndexRangeEnumerator(T[] data, int partitionCount, int partitionIndex)
{
Debug.Assert(data != null, "data must not be null");
Debug.Assert(partitionCount > 0, "partitionCount must be positive");
Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative");
Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount");
_data = data;
// Compute the size of the chunk to ensure even distribution of elements.
int smallerChunkSize = data.Length / partitionCount;
int biggerChunkCount = data.Length % partitionCount;
// Our start index is our index times the small chunk size, plus the number
// of "bigger" chunks before this one.
int startIndex = partitionIndex * smallerChunkSize +
(partitionIndex < biggerChunkCount ? partitionIndex : biggerChunkCount);
_startIndex = startIndex - 1; // Subtract one for the first call.
_maximumIndex = startIndex + smallerChunkSize + // And add one if we're responsible for part of the
(partitionIndex < biggerChunkCount ? 1 : 0); // leftover chunks.
Debug.Assert(_currentIndex == null, "Expected deferred allocation to ensure it happens on correct thread");
}
internal override bool MoveNext(ref T currentElement, ref int currentKey)
{
// Lazily allocate the current index if needed.
if (_currentIndex == null)
{
_currentIndex = new Shared<int>(_startIndex);
}
// Now increment the current index, check bounds, and so on.
int current = ++_currentIndex.Value;
if (current < _maximumIndex)
{
currentKey = current;
currentElement = _data[current];
return true;
}
return false;
}
}
// A copy of the index enumerator specialized for IList<T> indexing. It calls through
// the IList<T> interface for element retrieval.
internal sealed class ListIndexRangeEnumerator : QueryOperatorEnumerator<T, int>
{
private readonly IList<T> _data; // The elements to iterate over.
private readonly int _elementCount; // The number of elements to iterate over.
private readonly int _partitionCount; // The number of partitions.
private readonly int _partitionIndex; // The index of the current partition.
private readonly int _maxChunkSize; // The maximum size of a chunk. -1 if unlimited.
private readonly int _sectionCount; // Precomputed in ctor: the number of sections the range is split into.
private Mutables _mutables; // Lazily allocated mutable variables.
class Mutables
{
internal Mutables()
{
// Place the enumerator just before the first element
_currentSection = -1;
}
internal int _currentSection; // 0-based index of the current section.
internal int _currentChunkSize; // The number of elements in the current chunk.
internal int _currentPositionInChunk; // 0-based position within the current chunk.
internal int _currentChunkOffset; // The offset of the current chunk from the beginning of the range.
}
internal ListIndexRangeEnumerator(IList<T> data, int partitionCount, int partitionIndex, int maxChunkSize)
{
Debug.Assert(data != null, "data must not be null");
Debug.Assert(partitionCount > 0, "partitionCount must be positive");
Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative");
Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount");
Debug.Assert(maxChunkSize > 0, "maxChunkSize must be positive or -1");
_data = data;
_elementCount = data.Count;
_partitionCount = partitionCount;
_partitionIndex = partitionIndex;
_maxChunkSize = maxChunkSize;
int sectionSize = maxChunkSize * partitionCount;
Debug.Assert(sectionSize > 0);
// Section count is ceiling(elementCount / sectionSize)
_sectionCount = _elementCount / sectionSize +
((_elementCount % sectionSize) == 0 ? 0 : 1);
}
internal override bool MoveNext(ref T currentElement, ref int currentKey)
{
// Lazily allocate the mutable holder.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
}
// If we are aren't within the chunk, we need to find another.
if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath())
{
currentKey = mutables._currentChunkOffset + mutables._currentPositionInChunk;
currentElement = _data[currentKey];
return true;
}
return false;
}
private bool MoveNextSlowPath()
{
Mutables mutables = _mutables;
Debug.Assert(mutables != null);
Debug.Assert(mutables._currentPositionInChunk >= mutables._currentChunkSize);
// Move on to the next section.
int currentSection = ++mutables._currentSection;
int sectionsRemaining = _sectionCount - currentSection;
// If empty, return right away.
if (sectionsRemaining <= 0)
{
return false;
}
// Compute the offset of the current section from the beginning of the range
int currentSectionOffset = currentSection * _partitionCount * _maxChunkSize;
mutables._currentPositionInChunk = 0;
// Now do something different based on how many chunks remain.
if (sectionsRemaining > 1)
{
// We are not on the last section. The size of this chunk is simply _maxChunkSize.
mutables._currentChunkSize = _maxChunkSize;
mutables._currentChunkOffset = currentSectionOffset + _partitionIndex * _maxChunkSize;
}
else
{
// We are on the last section. Compute the size of the chunk to ensure even distribution
// of elements.
int lastSectionElementCount = _elementCount - currentSectionOffset;
int smallerChunkSize = lastSectionElementCount / _partitionCount;
int biggerChunkCount = lastSectionElementCount % _partitionCount;
mutables._currentChunkSize = smallerChunkSize;
if (_partitionIndex < biggerChunkCount)
{
mutables._currentChunkSize++;
}
if (mutables._currentChunkSize == 0)
{
return false;
}
mutables._currentChunkOffset =
currentSectionOffset // The beginning of this section
+ _partitionIndex * smallerChunkSize // + the start of this chunk if all chunks were "smaller"
+ (_partitionIndex < biggerChunkCount ? _partitionIndex : biggerChunkCount); // + the number of "bigger" chunks before this chunk
}
return true;
}
}
// A contiguous index enumerator specialized for IList<T> indexing. It calls through
// the IList<T> interface for element retrieval.
internal sealed class ListContiguousIndexRangeEnumerator : QueryOperatorEnumerator<T, int>
{
private readonly IList<T> _data; // The elements to iterate over.
private readonly int _startIndex; // Where to begin iterating.
private readonly int _maximumIndex; // The maximum index to iterate over.
private Shared<int> _currentIndex; // The current index (lazily allocated).
internal ListContiguousIndexRangeEnumerator(IList<T> data, int partitionCount, int partitionIndex)
{
Debug.Assert(data != null, "data must not be null");
Debug.Assert(partitionCount > 0, "partitionCount must be positive");
Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative");
Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount");
_data = data;
// Compute the size of the chunk to ensure even distribution of elements.
int smallerChunkSize = data.Count / partitionCount;
int biggerChunkCount = data.Count % partitionCount;
// Our start index is our index times the small chunk size, plus the number
// of "bigger" chunks before this one.
int startIndex = partitionIndex * smallerChunkSize +
(partitionIndex < biggerChunkCount ? partitionIndex : biggerChunkCount);
_startIndex = startIndex - 1; // Subtract one for the first call.
_maximumIndex = startIndex + smallerChunkSize + // And add one if we're responsible for part of the
(partitionIndex < biggerChunkCount ? 1 : 0); // leftover chunks.
Debug.Assert(_currentIndex == null, "Expected deferred allocation to ensure it happens on correct thread");
}
internal override bool MoveNext(ref T currentElement, ref int currentKey)
{
// Lazily allocate the current index if needed.
if (_currentIndex == null)
{
_currentIndex = new Shared<int>(_startIndex);
}
// Now increment the current index, check bounds, and so on.
int current = ++_currentIndex.Value;
if (current < _maximumIndex)
{
currentKey = current;
currentElement = _data[current];
return true;
}
return false;
}
}
//---------------------------------------------------------------------------------------
// This enumerator lazily grabs chunks of data from the underlying data source. It is
// safe for this data source to be enumerated by multiple such enumerators, since it has
// been written to perform proper synchronization.
//
private class ContiguousChunkLazyEnumerator : QueryOperatorEnumerator<T, int>
{
private const int chunksPerChunkSize = 7; // the rate at which to double the chunksize (double chunksize every 'r' chunks). MUST BE == (2^n)-1 for some n.
private readonly IEnumerator<T> _source; // Data source to enumerate.
private readonly object _sourceSyncLock; // Lock to use for all synchronization.
private readonly Shared<int> _currentIndex; // The index shared by all.
private readonly Shared<int> _activeEnumeratorsCount; // How many enumerators over the same source have not been disposed yet?
private readonly Shared<bool> _exceptionTracker;
private Mutables _mutables; // Any mutable fields on this enumerator. These mutables are local and persistent
class Mutables
{
internal Mutables()
{
_nextChunkMaxSize = 1; // We start the chunk size at 1 and grow it later.
_chunkBuffer = new T[Scheduling.GetDefaultChunkSize<T>()]; // Pre-allocate the array at the maximum size.
_currentChunkSize = 0; // The chunk begins life begins empty.
_currentChunkIndex = -1;
_chunkBaseIndex = 0;
_chunkCounter = 0;
}
internal readonly T[] _chunkBuffer; // Buffer array for the current chunk being enumerated.
internal int _nextChunkMaxSize; // The max. chunk size to use for the next chunk.
internal int _currentChunkSize; // The element count for our current chunk.
internal int _currentChunkIndex; // Our current index within the temporary chunk.
internal int _chunkBaseIndex; // The start index from which the current chunk was taken.
internal int _chunkCounter;
}
//---------------------------------------------------------------------------------------
// Constructs a new enumerator that lazily retrieves chunks from the provided source.
//
internal ContiguousChunkLazyEnumerator(
IEnumerator<T> source, Shared<bool> exceptionTracker, object sourceSyncLock, Shared<int> currentIndex, Shared<int> degreeOfParallelism)
{
Debug.Assert(source != null);
Debug.Assert(sourceSyncLock != null);
Debug.Assert(currentIndex != null);
_source = source;
_sourceSyncLock = sourceSyncLock;
_currentIndex = currentIndex;
_activeEnumeratorsCount = degreeOfParallelism;
_exceptionTracker = exceptionTracker;
}
//---------------------------------------------------------------------------------------
// Just retrieves the current element from our current chunk.
//
internal override bool MoveNext(ref T currentElement, ref int currentKey)
{
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
}
Debug.Assert(mutables._chunkBuffer != null);
// Loop until we've exhausted our data source.
while (true)
{
// If we have elements remaining in the current chunk, return right away.
T[] chunkBuffer = mutables._chunkBuffer;
int currentChunkIndex = ++mutables._currentChunkIndex;
if (currentChunkIndex < mutables._currentChunkSize)
{
Debug.Assert(_source != null);
Debug.Assert(chunkBuffer != null);
Debug.Assert(mutables._currentChunkSize > 0);
Debug.Assert(0 <= currentChunkIndex && currentChunkIndex < chunkBuffer.Length);
currentElement = chunkBuffer[currentChunkIndex];
currentKey = mutables._chunkBaseIndex + currentChunkIndex;
return true;
}
// Else, it could be the first time enumerating this object, or we may have
// just reached the end of the current chunk and need to grab another one? In either
// case, we will look for more data from the underlying enumerator. Because we
// share the same enumerator object, we have to do this under a lock.
lock (_sourceSyncLock)
{
Debug.Assert(0 <= mutables._nextChunkMaxSize && mutables._nextChunkMaxSize <= chunkBuffer.Length);
// Accumulate a chunk of elements from the input.
int i = 0;
if (_exceptionTracker.Value)
{
return false;
}
try
{
for (; i < mutables._nextChunkMaxSize && _source.MoveNext(); i++)
{
// Read the current entry into our buffer.
chunkBuffer[i] = _source.Current;
}
}
catch
{
_exceptionTracker.Value = true;
throw;
}
// Store the number of elements we fetched from the data source.
mutables._currentChunkSize = i;
// If we've emptied the enumerator, return immediately.
if (i == 0)
{
return false;
}
// Increment the shared index for all to see. Throw an exception on overflow.
mutables._chunkBaseIndex = _currentIndex.Value;
checked
{
_currentIndex.Value += i;
}
}
// Each time we access the data source, we grow the chunk size for the next go-round.
// We grow the chunksize once per 'chunksPerChunkSize'.
if (mutables._nextChunkMaxSize < chunkBuffer.Length)
{
if ((mutables._chunkCounter++ & chunksPerChunkSize) == chunksPerChunkSize)
{
mutables._nextChunkMaxSize = mutables._nextChunkMaxSize * 2;
if (mutables._nextChunkMaxSize > chunkBuffer.Length)
{
mutables._nextChunkMaxSize = chunkBuffer.Length;
}
}
}
// Finally, reset our index to the beginning; loop around and we'll return the right values.
mutables._currentChunkIndex = -1;
}
}
protected override void Dispose(bool disposing)
{
if (Interlocked.Decrement(ref _activeEnumeratorsCount.Value) == 0)
{
_source.Dispose();
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
namespace DefaultCluster.Tests
{
using Microsoft.Extensions.DependencyInjection;
public class GrainReferenceCastTests : HostedTestClusterEnsureDefaultStarted
{
private readonly IInternalGrainFactory internalGrainFactory;
public GrainReferenceCastTests(DefaultClusterFixture fixture) : base(fixture)
{
var client = this.HostedCluster.Client;
this.internalGrainFactory = client.ServiceProvider.GetRequiredService<IInternalGrainFactory>();
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefCastFromMyType()
{
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix);
GrainReference cast = (GrainReference)grain.AsReference<ISimpleGrain>();
Assert.IsAssignableFrom(grain.GetType(), cast);
Assert.IsAssignableFrom<ISimpleGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefCastFromMyTypePolymorphic()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
IAddressable grain = this.GrainFactory.GetGrain<IMultifacetTestGrain>(0);
Assert.IsAssignableFrom<IMultifacetWriter>(grain);
Assert.IsAssignableFrom<IMultifacetReader>(grain);
IAddressable cast = grain.AsReference<IMultifacetReader>();
Assert.IsAssignableFrom(grain.GetType(), cast);
Assert.IsAssignableFrom<IMultifacetWriter>(cast);
Assert.IsAssignableFrom<IMultifacetReader>(grain);
IAddressable cast2 = grain.AsReference<IMultifacetWriter>();
Assert.IsAssignableFrom(grain.GetType(), cast2);
Assert.IsAssignableFrom<IMultifacetReader>(cast2);
Assert.IsAssignableFrom<IMultifacetWriter>(grain);
}
// Test case currently fails intermittently
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastMultifacetRWReference()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
int newValue = 3;
IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(1);
// No Wait in this test case
IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case intermittently fails here
// Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/b198f19f]
writer.SetValue(newValue).Wait();
Task<int> readAsync = reader.GetValue();
readAsync.Wait();
int result = readAsync.Result;
Assert.Equal(newValue, result);
}
// Test case currently fails
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastMultifacetRWReferenceWaitForResolve()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
//Interface Id values for debug:
// IMultifacetWriter = 62435819
// IMultifacetReader = 1947430462
// IMultifacetTestGrain = 222717230 (also compatable with 1947430462 or 62435819)
int newValue = 4;
IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(2);
IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case fails here
// Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/8408c2bc]
writer.SetValue(newValue).Wait();
int result = reader.GetValue().Result;
Assert.Equal(newValue, result);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void ConfirmServiceInterfacesListContents()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
Type t1 = typeof(IGeneratorTestDerivedDerivedGrain);
Type t2 = typeof(IGeneratorTestDerivedGrain2);
Type t3 = typeof(IGeneratorTestGrain);
int id1 = GrainInterfaceUtils.GetGrainInterfaceId(t1);
int id2 = GrainInterfaceUtils.GetGrainInterfaceId(t2);
int id3 = GrainInterfaceUtils.GetGrainInterfaceId(t3);
var interfaces = GrainInterfaceUtils.GetRemoteInterfaces(typeof(IGeneratorTestDerivedDerivedGrain));
Assert.NotNull(interfaces);
Assert.Equal(3, interfaces.Keys.Count);
Assert.True(interfaces.Keys.Contains(id1), "id1 is present");
Assert.True(interfaces.Keys.Contains(id2), "id2 is present");
Assert.True(interfaces.Keys.Contains(id3), "id3 is present");
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastCheckExpectedCompatIds()
{
Type t = typeof(ISimpleGrain);
int expectedInterfaceId = GrainInterfaceUtils.GetGrainInterfaceId(t);
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix);
Assert.True(grain.IsCompatible(expectedInterfaceId));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastCheckExpectedCompatIds2()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
Type t1 = typeof(IGeneratorTestDerivedDerivedGrain);
Type t2 = typeof(IGeneratorTestDerivedGrain2);
Type t3 = typeof(IGeneratorTestGrain);
int id1 = GrainInterfaceUtils.GetGrainInterfaceId(t1);
int id2 = GrainInterfaceUtils.GetGrainInterfaceId(t2);
int id3 = GrainInterfaceUtils.GetGrainInterfaceId(t3);
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
Assert.True(grain.IsCompatible(id1));
Assert.True(grain.IsCompatible(id2));
Assert.True(grain.IsCompatible(id3));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastFailInternalCastFromBadType()
{
var grain = this.GrainFactory.GetGrain<ISimpleGrain>(
random.Next(),
SimpleGrain.SimpleGrainNamePrefix);
// Attempting to cast a grain to a non-grain type should fail.
Assert.Throws<InvalidCastException>(() => this.internalGrainFactory.Cast(grain, typeof(bool)));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastInternalCastFromMyType()
{
var serviceName = typeof(SimpleGrain).FullName;
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix);
// This cast should be a no-op, since the interface matches the initial reference's exactly.
IAddressable cast = grain.Cast<ISimpleGrain>();
Assert.Same(grain, cast);
Assert.IsAssignableFrom<ISimpleGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastInternalCastUpFromChild()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
// This cast should be a no-op, since the interface is implemented by the initial reference's interface.
IAddressable cast = grain.Cast<IGeneratorTestGrain>();
Assert.Same(grain, cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromChild()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>();
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain1>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public async Task FailSideCastAfterResolve()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
Assert.True(grain.StringIsNullOrEmpty().Result);
// Fails the next line as grain reference is already resolved
IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c"));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public async Task FailOperationAfterSideCast()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
// Cast works optimistically when the grain reference is not already resolved
IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
// Operation fails when grain reference is completely resolved
await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c"));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void FailSideCastAfterContinueWith()
{
Assert.Throws<InvalidCastException>(() =>
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
try
{
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
IGeneratorTestDerivedGrain2 cast = null;
Task<bool> av = grain.StringIsNullOrEmpty();
Task<bool> av2 = av.ContinueWith((Task<bool> t) => Assert.True(t.Result)).ContinueWith((_AppDomain) =>
{
cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
}).ContinueWith((_) => cast.StringConcat("a", "b", "c")).ContinueWith((_) => cast.StringIsNullOrEmpty().Result);
Assert.False(av2.Result);
}
catch (AggregateException ae)
{
Exception ex = ae.InnerException;
while (ex is AggregateException) ex = ex.InnerException;
throw ex;
}
Assert.True(false, "Exception should have been raised");
});
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
GrainReference cast;
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
// Parent
cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
// Cross-cast outside the inheritance hierarchy should not work
Assert.False(cast is IGeneratorTestDerivedGrain1);
// Grandparent
cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
// Cross-cast outside the inheritance hierarchy should not work
Assert.False(cast is IGeneratorTestDerivedGrain1);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromDerivedDerivedChild()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
Assert.False(cast is IGeneratorTestDerivedGrain1);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastAsyncGrainRefCastFromSelf()
{
IAddressable grain = this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); ;
ISimpleGrain cast = grain.AsReference<ISimpleGrain>();
Task<int> successfulCallPromise = cast.GetA();
successfulCallPromise.Wait();
Assert.Equal(TaskStatus.RanToCompletion, successfulCallPromise.Status);
}
// todo: implement white box access
#if TODO
[Fact]
public void CastAsyncGrainRefUpCastFromChild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedGrain1" );
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain);
Assert.NotNull(cast);
//Assert.Same(typeof(IGeneratorTestGrain), cast.GetType());
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(cast.IsResolved);
Assert.True(grain.IsResolved);
}
[Fact]
public void CastAsyncGrainRefUpCastFromGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedDerivedGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedDerivedGrain"
);
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain);
Assert.NotNull(cast);
//Assert.Same(typeof(IGeneratorTestGrain), cast.GetType());
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(cast.IsResolved);
Assert.True(grain.IsResolved);
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailSideCastToPeer()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedGrain1"
);
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedGrain2Factory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailDownCastToChild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestGrain");
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedGrain1Factory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailDownCastToGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestGrain");
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedDerivedGrainFactory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
#endif
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastCallMethodInheritedFromBaseClass()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
Task<bool> isNullStr;
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
isNullStr = grain.StringIsNullOrEmpty();
Assert.True(isNullStr.Result, "Value should be null initially");
isNullStr = grain.StringSet("a").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.False(isNullStr.Result, "Value should not be null after SetString(a)");
isNullStr = grain.StringSet(null).ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.True(isNullStr.Result, "Value should be null after SetString(null)");
IGeneratorTestGrain cast = grain.AsReference<IGeneratorTestGrain>();
isNullStr = cast.StringSet("b").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.False(isNullStr.Result, "Value should not be null after cast.SetString(b)");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FormsAuthenticationConfiguration.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*****************************************************************************
From machine.config
<!--
authentication Attributes:
mode="[Windows|Forms|Passport|None]"
-->
<authentication mode="Windows">
<!--
forms Attributes:
name="[cookie name]" - Name of the cookie used for Forms Authentication
loginUrl="[url]" - Url to redirect client to for Authentication
protection="[All|None|Encryption|Validation]" - Protection mode for data in cookie
timeout="[minutes]" - Duration of time for cookie to be valid (reset on each request)
path="/" - Sets the path for the cookie
requireSSL="[true|false]" - Should the forms-authentication cookie be sent only over SSL
slidingExpiration="[true|false]" - Should the forms-authentication-cookie and ticket be re-issued if they are about to expire
defaultUrl="string" - Page to redirect to after login, if none has been specified
cookieless="[UseCookies|UseUri|AutoDetect|UseDeviceProfile]" - Use Cookies or the URL path to store the forms authentication ticket
domain="string" - Domain of the cookie
-->
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" >
<!--
credentials Attributes:
passwordFormat="[Clear|SHA1|MD5]" - format of user password value stored in <user>
-->
<credentials passwordFormat="SHA1">
<!-- <user name="UserName" password="password" /> -->
</credentials>
</forms>
<!--
passport Attributes:
redirectUrl=["url"] - Specifies the page to redirect to, if the page requires authentication, and the user has not signed on with passport
-->
<passport redirectUrl="internal" />
</authentication>
<authentication mode="Windows">
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" >
<credentials passwordFormat="SHA1">
</credentials>
</forms>
<passport redirectUrl="internal" />
</authentication>
******************************************************************************/
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Util;
using System.ComponentModel;
using System.Security.Permissions;
public sealed class FormsAuthenticationConfiguration : ConfigurationElement {
private static readonly ConfigurationElementProperty s_elemProperty =
new ConfigurationElementProperty(new CallbackValidator(typeof(FormsAuthenticationConfiguration), Validate));
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propCredentials =
new ConfigurationProperty("credentials",
typeof(FormsAuthenticationCredentials),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty("name",
typeof(string),
".ASPXAUTH",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propLoginUrl =
new ConfigurationProperty("loginUrl",
typeof(string),
"login.aspx",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDefaultUrl =
new ConfigurationProperty("defaultUrl",
typeof(string),
"default.aspx",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propProtection =
new ConfigurationProperty("protection",
typeof(FormsProtectionEnum),
FormsProtectionEnum.All,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propTimeout =
new ConfigurationProperty("timeout",
typeof(TimeSpan),
TimeSpan.FromMinutes(30.0),
StdValidatorsAndConverters.TimeSpanMinutesConverter,
new TimeSpanValidator(TimeSpan.FromMinutes(1), TimeSpan.MaxValue),
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propPath =
new ConfigurationProperty("path",
typeof(string),
"/",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propRequireSSL =
new ConfigurationProperty("requireSSL",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propSlidingExpiration =
new ConfigurationProperty("slidingExpiration",
typeof(bool),
true,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieless =
new ConfigurationProperty("cookieless",
typeof(HttpCookieMode),
HttpCookieMode.UseDeviceProfile,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDomain =
new ConfigurationProperty("domain",
typeof(string),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEnableCrossAppRedirects =
new ConfigurationProperty("enableCrossAppRedirects",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propTicketCompatibilityMode =
new ConfigurationProperty("ticketCompatibilityMode",
typeof(TicketCompatibilityMode),
TicketCompatibilityMode.Framework20,
ConfigurationPropertyOptions.None);
static FormsAuthenticationConfiguration() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propCredentials);
_properties.Add(_propName);
_properties.Add(_propLoginUrl);
_properties.Add(_propDefaultUrl);
_properties.Add(_propProtection);
_properties.Add(_propTimeout);
_properties.Add(_propPath);
_properties.Add(_propRequireSSL);
_properties.Add(_propSlidingExpiration);
_properties.Add(_propCookieless);
_properties.Add(_propDomain);
_properties.Add(_propEnableCrossAppRedirects);
_properties.Add(_propTicketCompatibilityMode);
}
public FormsAuthenticationConfiguration() {
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("credentials")]
public FormsAuthenticationCredentials Credentials {
get {
return (FormsAuthenticationCredentials)base[_propCredentials];
}
}
[ConfigurationProperty("name", DefaultValue = ".ASPXAUTH")]
[StringValidator(MinLength = 1)]
public string Name {
get {
return (string)base[_propName];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propName] = _propName.DefaultValue;
}
else {
base[_propName] = value;
}
}
}
[ConfigurationProperty("loginUrl", DefaultValue = "login.aspx")]
[StringValidator(MinLength = 1)]
public string LoginUrl {
get {
return (string)base[_propLoginUrl];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propLoginUrl] = _propLoginUrl.DefaultValue;
}
else {
base[_propLoginUrl] = value;
}
}
}
[ConfigurationProperty("defaultUrl", DefaultValue = "default.aspx")]
[StringValidator(MinLength = 1)]
public string DefaultUrl {
get {
return (string)base[_propDefaultUrl];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propDefaultUrl] = _propDefaultUrl.DefaultValue;
}
else {
base[_propDefaultUrl] = value;
}
}
}
[ConfigurationProperty("protection", DefaultValue = FormsProtectionEnum.All)]
public FormsProtectionEnum Protection {
get {
return (FormsProtectionEnum)base[_propProtection];
}
set {
base[_propProtection] = value;
}
}
[ConfigurationProperty("timeout", DefaultValue = "00:30:00")]
[TimeSpanValidator(MinValueString="00:01:00", MaxValueString=TimeSpanValidatorAttribute.TimeSpanMaxValue)]
[TypeConverter(typeof(TimeSpanMinutesConverter))]
public TimeSpan Timeout {
get {
return (TimeSpan)base[_propTimeout];
}
set {
base[_propTimeout] = value;
}
}
[ConfigurationProperty("path", DefaultValue = "/")]
[StringValidator(MinLength = 1)]
public string Path {
get {
return (string)base[_propPath];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propPath] = _propPath.DefaultValue;
}
else {
base[_propPath] = value;
}
}
}
[ConfigurationProperty("requireSSL", DefaultValue = false)]
public bool RequireSSL {
get {
return (bool)base[_propRequireSSL];
}
set {
base[_propRequireSSL] = value;
}
}
[ConfigurationProperty("slidingExpiration", DefaultValue = true)]
public bool SlidingExpiration {
get {
return (bool)base[_propSlidingExpiration];
}
set {
base[_propSlidingExpiration] = value;
}
}
[ConfigurationProperty("enableCrossAppRedirects", DefaultValue = false)]
public bool EnableCrossAppRedirects {
get {
return (bool)base[_propEnableCrossAppRedirects];
}
set {
base[_propEnableCrossAppRedirects] = value;
}
}
[ConfigurationProperty("cookieless", DefaultValue = HttpCookieMode.UseDeviceProfile)]
public HttpCookieMode Cookieless {
get {
return (HttpCookieMode)base[_propCookieless];
}
set {
base[_propCookieless] = value;
}
}
[ConfigurationProperty("domain", DefaultValue = "")]
public string Domain {
get {
return (string)base[_propDomain];
}
set {
base[_propDomain] = value;
}
}
[ConfigurationProperty("ticketCompatibilityMode", DefaultValue = TicketCompatibilityMode.Framework20)]
public TicketCompatibilityMode TicketCompatibilityMode {
get {
return (TicketCompatibilityMode)base[_propTicketCompatibilityMode];
}
set {
base[_propTicketCompatibilityMode] = value;
}
}
protected override ConfigurationElementProperty ElementProperty {
get {
return s_elemProperty;
}
}
private static void Validate(object value) {
if (value == null) {
throw new ArgumentNullException("forms");
}
FormsAuthenticationConfiguration elem = (FormsAuthenticationConfiguration)value;
if (StringUtil.StringStartsWith(elem.LoginUrl, "\\\\") ||
(elem.LoginUrl.Length > 1 && elem.LoginUrl[1] == ':')) {
throw new ConfigurationErrorsException(SR.GetString(SR.Auth_bad_url),
elem.ElementInformation.Properties["loginUrl"].Source,
elem.ElementInformation.Properties["loginUrl"].LineNumber);
}
if (StringUtil.StringStartsWith(elem.DefaultUrl, "\\\\") ||
(elem.DefaultUrl.Length > 1 && elem.DefaultUrl[1] == ':')) {
throw new ConfigurationErrorsException(SR.GetString(SR.Auth_bad_url),
elem.ElementInformation.Properties["defaultUrl"].Source,
elem.ElementInformation.Properties["defaultUrl"].LineNumber);
}
}
} // class FormsAuthenticationConfiguration
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal sealed partial class RenameTrackingTaggerProvider
{
private class RenameTrackingCommitter : ForegroundThreadAffinitizedObject
{
private readonly StateMachine _stateMachine;
private readonly SnapshotSpan _snapshotSpan;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly string _displayText;
private readonly AsyncLazy<RenameTrackingSolutionSet> _renameSymbolResultGetter;
public RenameTrackingCommitter(
StateMachine stateMachine,
SnapshotSpan snapshotSpan,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
ITextUndoHistoryRegistry undoHistoryRegistry,
string displayText)
{
_stateMachine = stateMachine;
_snapshotSpan = snapshotSpan;
_refactorNotifyServices = refactorNotifyServices;
_undoHistoryRegistry = undoHistoryRegistry;
_displayText = displayText;
_renameSymbolResultGetter = new AsyncLazy<RenameTrackingSolutionSet>(c => RenameSymbolWorkerAsync(c), cacheResult: true);
}
public void Commit(CancellationToken cancellationToken)
{
AssertIsForeground();
bool clearTrackingSession = ApplyChangesToWorkspace(cancellationToken);
// Clear the state machine so that future updates to the same token work,
// and any text changes caused by this update are not interpreted as
// potential renames
if (clearTrackingSession)
{
_stateMachine.ClearTrackingSession();
}
}
public async Task<RenameTrackingSolutionSet> RenameSymbolAsync(CancellationToken cancellationToken)
{
return await _renameSymbolResultGetter.GetValueAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<RenameTrackingSolutionSet> RenameSymbolWorkerAsync(CancellationToken cancellationToken)
{
var document = _snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
var newName = _snapshotSpan.GetText();
if (document == null)
{
Contract.Fail("Invoked rename tracking smart tag but cannot find the document for the snapshot span.");
}
// Get copy of solution with the original name in the place of the renamed name
var solutionWithOriginalName = CreateSolutionWithOriginalName(document, cancellationToken);
var symbol = await TryGetSymbolAsync(solutionWithOriginalName, document.Id, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
Contract.Fail("Invoked rename tracking smart tag but cannot find the symbol.");
}
var optionSet = document.Project.Solution.Workspace.Options;
if (_stateMachine.TrackingSession.ForceRenameOverloads)
{
optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, true);
}
var renamedSolution = await Renamer.RenameSymbolAsync(solutionWithOriginalName, symbol, newName, optionSet, cancellationToken).ConfigureAwait(false);
return new RenameTrackingSolutionSet(symbol, solutionWithOriginalName, renamedSolution);
}
private bool ApplyChangesToWorkspace(CancellationToken cancellationToken)
{
AssertIsForeground();
// Now that the necessary work has been done to create the intermediate and final
// solutions during PreparePreview, check one more time for cancellation before making all of the
// workspace changes.
cancellationToken.ThrowIfCancellationRequested();
// Undo must backtrack to the state with the original identifier before the state
// with the user-edited identifier. For example,
//
// 1. Original: void M() { M(); }
// 2. User types: void Method() { M(); }
// 3. Invoke rename: void Method() { Method(); }
//
// The undo process should be as follows
// 1. Back to original name everywhere: void M() { M(); } // No tracking session
// 2. Back to state 2 above: void Method() { M(); } // Resume tracking session
// 3. Finally, start undoing typing: void M() { M(); }
//
// As far as the user can see, undo state 1 never actually existed so we must insert
// a state here to facilitate the undo. Do the work to obtain the intermediate and
// final solution without updating the workspace, and then finally disallow
// cancellation and update the workspace twice.
var renameTrackingSolutionSet = RenameSymbolAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var document = _snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
var newName = _snapshotSpan.GetText();
var workspace = document.Project.Solution.Workspace;
// Since the state machine is only watching buffer changes, it will interpret the
// text changes caused by undo and redo actions as potential renames, so carefully
// update the state machine after undo/redo actions.
var changedDocuments = renameTrackingSolutionSet.RenamedSolution.GetChangedDocuments(renameTrackingSolutionSet.OriginalSolution);
// When this action is undone (the user has undone twice), restore the state
// machine to so that they can continue their original rename tracking session.
var trackingSessionId = _stateMachine.StoreCurrentTrackingSessionAndGenerateId();
UpdateWorkspaceForResetOfTypedIdentifier(workspace, renameTrackingSolutionSet.OriginalSolution, trackingSessionId);
// Now that the solution is back in its original state, notify third parties about
// the coming rename operation.
if (!_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, renameTrackingSolutionSet.Symbol, newName, throwOnFailure: false))
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(
EditorFeaturesResources.RenameOperationWasCancelled,
EditorFeaturesResources.RenameSymbol,
NotificationSeverity.Error);
return true;
}
// move all changes to final solution based on the workspace's current solution, since the current solution
// got updated when we reset it above.
var finalSolution = workspace.CurrentSolution;
foreach (var docId in changedDocuments)
{
// because changes have already been made to the workspace (UpdateWorkspaceForResetOfTypedIdentifier() above),
// these calls can't be cancelled and must be allowed to complete.
var root = renameTrackingSolutionSet.RenamedSolution.GetDocument(docId).GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
finalSolution = finalSolution.WithDocumentSyntaxRoot(docId, root);
}
// Undo/redo on this action must always clear the state machine
UpdateWorkspaceForGlobalIdentifierRename(
workspace,
finalSolution,
workspace.CurrentSolution,
_displayText,
changedDocuments,
renameTrackingSolutionSet.Symbol,
newName,
trackingSessionId);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
return true;
}
private Solution CreateSolutionWithOriginalName(Document document, CancellationToken cancellationToken)
{
var syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var fullText = syntaxTree.GetText(cancellationToken);
var textChange = new TextChange(new TextSpan(_snapshotSpan.Start, _snapshotSpan.Length), _stateMachine.TrackingSession.OriginalName);
var newFullText = fullText.WithChanges(textChange);
#if DEBUG
var syntaxTreeWithOriginalName = syntaxTree.WithChangedText(newFullText);
var documentWithOriginalName = document.WithSyntaxRoot(syntaxTreeWithOriginalName.GetRoot(cancellationToken));
Contract.Requires(newFullText.ToString() == documentWithOriginalName.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString());
#endif
// Apply the original name to all linked documents to construct a consistent solution
var solution = document.Project.Solution;
foreach (var documentId in document.GetLinkedDocumentIds().Add(document.Id))
{
solution = solution.WithDocumentText(documentId, newFullText);
}
return solution;
}
private async Task<ISymbol> TryGetSymbolAsync(Solution solutionWithOriginalName, DocumentId documentId, CancellationToken cancellationToken)
{
var documentWithOriginalName = solutionWithOriginalName.GetDocument(documentId);
var syntaxTreeWithOriginalName = await documentWithOriginalName.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = documentWithOriginalName.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = documentWithOriginalName.GetLanguageService<ISemanticFactsService>();
var semanticModel = await documentWithOriginalName.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTreeWithOriginalName.GetTouchingWord(_snapshotSpan.Start, syntaxFacts, cancellationToken);
var tokenRenameInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, cancellationToken);
return tokenRenameInfo.HasSymbols ? tokenRenameInfo.Symbols.First() : null;
}
private void UpdateWorkspaceForResetOfTypedIdentifier(Workspace workspace, Solution newSolution, int trackingSessionId)
{
AssertIsForeground();
// Update document in an ITextUndoTransaction with custom behaviors on undo/redo to
// deal with the state machine.
var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer);
using (var localUndoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.TextBufferChange))
{
var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: true);
localUndoTransaction.AddUndo(undoPrimitiveBefore);
if (!workspace.TryApplyChanges(newSolution))
{
Contract.Fail("Rename Tracking could not update solution.");
}
// Never resume tracking session on redo
var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false);
localUndoTransaction.AddUndo(undoPrimitiveAfter);
localUndoTransaction.Complete();
}
}
private void UpdateWorkspaceForGlobalIdentifierRename(
Workspace workspace,
Solution newSolution,
Solution oldSolution,
string undoName,
IEnumerable<DocumentId> changedDocuments,
ISymbol symbol,
string newName,
int trackingSessionId)
{
AssertIsForeground();
// Perform rename in a workspace undo action so that undo will revert all
// references. It should also be performed in an ITextUndoTransaction to handle
var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer);
using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoName))
using (var localUndoTransaction = undoHistory.CreateTransaction(undoName))
{
var undoPrimitiveBefore = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false);
localUndoTransaction.AddUndo(undoPrimitiveBefore);
if (!workspace.TryApplyChanges(newSolution))
{
Contract.Fail("Rename Tracking could not update solution.");
}
if (!_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: false))
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(
EditorFeaturesResources.RenameOperationWasNotProperlyCompleted,
EditorFeaturesResources.RenameSymbol,
NotificationSeverity.Information);
}
// Never resume tracking session on redo
var undoPrimitiveAfter = new UndoPrimitive(_stateMachine.Buffer, trackingSessionId, shouldRestoreStateOnUndo: false);
localUndoTransaction.AddUndo(undoPrimitiveAfter);
localUndoTransaction.Complete();
workspaceUndoTransaction.Commit();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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 vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
using rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.Runtime
{
public partial class ScriptBaseClass
{
// LSL CONSTANTS
public static readonly LSL_Types.LSLInteger TRUE = new LSL_Types.LSLInteger(1);
public static readonly LSL_Types.LSLInteger FALSE = new LSL_Types.LSLInteger(0);
public static readonly LSL_Types.LSLInteger STATUS_PHYSICS = 1;
public static readonly LSL_Types.LSLInteger STATUS_ROTATE_X = 2;
public static readonly LSL_Types.LSLInteger STATUS_ROTATE_Y = 4;
public static readonly LSL_Types.LSLInteger STATUS_ROTATE_Z = 8;
public static readonly LSL_Types.LSLInteger STATUS_PHANTOM = 16;
public static readonly LSL_Types.LSLInteger STATUS_SANDBOX = 32;
public static readonly LSL_Types.LSLInteger STATUS_BLOCK_GRAB = 64;
public static readonly LSL_Types.LSLInteger STATUS_DIE_AT_EDGE = 128;
public static readonly LSL_Types.LSLInteger STATUS_RETURN_AT_EDGE = 256;
public static readonly LSL_Types.LSLInteger STATUS_CAST_SHADOWS = 512;
public static readonly LSL_Types.LSLInteger STATUS_BLOCK_GRAB_OBJECT = 1024;
public static readonly LSL_Types.LSLInteger AGENT = 1;
public static readonly LSL_Types.LSLInteger AGENT_BY_LEGACY_NAME = 1;
public static readonly LSL_Types.LSLInteger AGENT_BY_USERNAME = 0x10;
public static readonly LSL_Types.LSLInteger ACTIVE = 2;
public static readonly LSL_Types.LSLInteger PASSIVE = 4;
public static readonly LSL_Types.LSLInteger SCRIPTED = 8;
public static readonly LSL_Types.LSLInteger CONTROL_FWD = 1;
public static readonly LSL_Types.LSLInteger CONTROL_BACK = 2;
public static readonly LSL_Types.LSLInteger CONTROL_LEFT = 4;
public static readonly LSL_Types.LSLInteger CONTROL_RIGHT = 8;
public static readonly LSL_Types.LSLInteger CONTROL_UP = 16;
public static readonly LSL_Types.LSLInteger CONTROL_DOWN = 32;
public static readonly LSL_Types.LSLInteger CONTROL_ROT_LEFT = 256;
public static readonly LSL_Types.LSLInteger CONTROL_ROT_RIGHT = 512;
public static readonly LSL_Types.LSLInteger CONTROL_LBUTTON = 268435456;
public static readonly LSL_Types.LSLInteger CONTROL_ML_LBUTTON = 1073741824;
//Permissions
public static readonly LSL_Types.LSLInteger PERMISSION_DEBIT = 2;
public static readonly LSL_Types.LSLInteger PERMISSION_TAKE_CONTROLS = 4;
public static readonly LSL_Types.LSLInteger PERMISSION_REMAP_CONTROLS = 8;
public static readonly LSL_Types.LSLInteger PERMISSION_TRIGGER_ANIMATION = 16;
public static readonly LSL_Types.LSLInteger PERMISSION_ATTACH = 32;
public static readonly LSL_Types.LSLInteger PERMISSION_RELEASE_OWNERSHIP = 64;
public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_LINKS = 128;
public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_JOINTS = 256;
public static readonly LSL_Types.LSLInteger PERMISSION_CHANGE_PERMISSIONS = 512;
public static readonly LSL_Types.LSLInteger PERMISSION_TRACK_CAMERA = 1024;
public static readonly LSL_Types.LSLInteger PERMISSION_CONTROL_CAMERA = 2048;
public static readonly LSL_Types.LSLInteger PERMISSION_TELEPORT = 4096;
public static readonly LSL_Types.LSLInteger PERMISSION_COMBAT = 8196;
public static readonly LSL_Types.LSLInteger AGENT_FLYING = 1;
public static readonly LSL_Types.LSLInteger AGENT_ATTACHMENTS = 2;
public static readonly LSL_Types.LSLInteger AGENT_SCRIPTED = 4;
public static readonly LSL_Types.LSLInteger AGENT_MOUSELOOK = 8;
public static readonly LSL_Types.LSLInteger AGENT_SITTING = 16;
public static readonly LSL_Types.LSLInteger AGENT_ON_OBJECT = 32;
public static readonly LSL_Types.LSLInteger AGENT_AWAY = 64;
public static readonly LSL_Types.LSLInteger AGENT_WALKING = 128;
public static readonly LSL_Types.LSLInteger AGENT_IN_AIR = 256;
public static readonly LSL_Types.LSLInteger AGENT_TYPING = 512;
public static readonly LSL_Types.LSLInteger AGENT_CROUCHING = 1024;
public static readonly LSL_Types.LSLInteger AGENT_BUSY = 2048;
public static readonly LSL_Types.LSLInteger AGENT_ALWAYS_RUN = 4096;
//Particle Systems
public static readonly LSL_Types.LSLInteger PSYS_PART_INTERP_COLOR_MASK = 1;
public static readonly LSL_Types.LSLInteger PSYS_PART_INTERP_SCALE_MASK = 2;
public static readonly LSL_Types.LSLInteger PSYS_PART_BOUNCE_MASK = 4;
public static readonly LSL_Types.LSLInteger PSYS_PART_WIND_MASK = 8;
public static readonly LSL_Types.LSLInteger PSYS_PART_FOLLOW_SRC_MASK = 16;
public static readonly LSL_Types.LSLInteger PSYS_PART_FOLLOW_VELOCITY_MASK = 32;
public static readonly LSL_Types.LSLInteger PSYS_PART_TARGET_POS_MASK = 64;
public static readonly LSL_Types.LSLInteger PSYS_PART_TARGET_LINEAR_MASK = 128;
public static readonly LSL_Types.LSLInteger PSYS_PART_EMISSIVE_MASK = 256;
public static readonly LSL_Types.LSLInteger PSYS_PART_FLAGS = 0;
public static readonly LSL_Types.LSLInteger PSYS_PART_START_COLOR = 1;
public static readonly LSL_Types.LSLInteger PSYS_PART_START_ALPHA = 2;
public static readonly LSL_Types.LSLInteger PSYS_PART_END_COLOR = 3;
public static readonly LSL_Types.LSLInteger PSYS_PART_END_ALPHA = 4;
public static readonly LSL_Types.LSLInteger PSYS_PART_START_SCALE = 5;
public static readonly LSL_Types.LSLInteger PSYS_PART_END_SCALE = 6;
public static readonly LSL_Types.LSLInteger PSYS_PART_MAX_AGE = 7;
public static readonly LSL_Types.LSLInteger PSYS_SRC_ACCEL = 8;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN = 9;
public static readonly LSL_Types.LSLInteger PSYS_SRC_INNERANGLE = 10;
public static readonly LSL_Types.LSLInteger PSYS_SRC_OUTERANGLE = 11;
public static readonly LSL_Types.LSLInteger PSYS_SRC_TEXTURE = 12;
public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_RATE = 13;
public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_PART_COUNT = 15;
public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_RADIUS = 16;
public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_SPEED_MIN = 17;
public static readonly LSL_Types.LSLInteger PSYS_SRC_BURST_SPEED_MAX = 18;
public static readonly LSL_Types.LSLInteger PSYS_SRC_MAX_AGE = 19;
public static readonly LSL_Types.LSLInteger PSYS_SRC_TARGET_KEY = 20;
public static readonly LSL_Types.LSLInteger PSYS_SRC_OMEGA = 21;
public static readonly LSL_Types.LSLInteger PSYS_SRC_ANGLE_BEGIN = 22;
public static readonly LSL_Types.LSLInteger PSYS_SRC_ANGLE_END = 23;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_DROP = 1;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_EXPLODE = 2;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE = 4;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE = 8;
public static readonly LSL_Types.LSLInteger PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_NONE = 0;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_SLED = 1;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_CAR = 2;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_BOAT = 3;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_AIRPLANE = 4;
public static readonly LSL_Types.LSLInteger VEHICLE_TYPE_BALLOON = 5;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_FRICTION_TIMESCALE = 16;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_DIRECTION = 18;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_OFFSET = 20;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_DIRECTION = 19;
public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_HEIGHT = 24;
public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_EFFICIENCY = 25;
public static readonly LSL_Types.LSLInteger VEHICLE_HOVER_TIMESCALE = 26;
public static readonly LSL_Types.LSLInteger VEHICLE_BUOYANCY = 27;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_TIMESCALE = 30;
public static readonly LSL_Types.LSLInteger VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34;
public static readonly LSL_Types.LSLInteger VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35;
public static readonly LSL_Types.LSLInteger VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36;
public static readonly LSL_Types.LSLInteger VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37;
public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_EFFICIENCY = 38;
public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_MIX = 39;
public static readonly LSL_Types.LSLInteger VEHICLE_BANKING_TIMESCALE = 40;
public static readonly LSL_Types.LSLInteger VEHICLE_REFERENCE_FRAME = 44;
public static readonly LSL_Types.LSLInteger VEHICLE_RANGE_BLOCK = 45;
public static readonly LSL_Types.LSLInteger VEHICLE_ROLL_FRAME = 46;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_DEFLECTION_UP = 1;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_FLY_UP = 1; //Old name for NO_DEFLECTION_UP
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_WATER_ONLY = 4;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_HOVER_UP_ONLY = 32;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LIMIT_MOTOR_UP = 64;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_MOUSELOOK_STEER = 128;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_MOUSELOOK_BANK = 256;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_CAMERA_DECOUPLED = 512;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_X = 1024;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_Y = 2048;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_Z = 4096;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_NO_DEFLECTION = 16392;
public static readonly LSL_Types.LSLInteger VEHICLE_FLAG_LOCK_ROTATION = 32784;
public static readonly LSL_Types.LSLInteger INVENTORY_ALL = -1;
public static readonly LSL_Types.LSLInteger INVENTORY_NONE = -1;
public static readonly LSL_Types.LSLInteger INVENTORY_TEXTURE = 0;
public static readonly LSL_Types.LSLInteger INVENTORY_SOUND = 1;
public static readonly LSL_Types.LSLInteger INVENTORY_LANDMARK = 3;
public static readonly LSL_Types.LSLInteger INVENTORY_CLOTHING = 5;
public static readonly LSL_Types.LSLInteger INVENTORY_OBJECT = 6;
public static readonly LSL_Types.LSLInteger INVENTORY_NOTECARD = 7;
public static readonly LSL_Types.LSLInteger INVENTORY_SCRIPT = 10;
public static readonly LSL_Types.LSLInteger INVENTORY_BODYPART = 13;
public static readonly LSL_Types.LSLInteger INVENTORY_ANIMATION = 20;
public static readonly LSL_Types.LSLInteger INVENTORY_GESTURE = 21;
public static readonly LSL_Types.LSLInteger ATTACH_CHEST = 1;
public static readonly LSL_Types.LSLInteger ATTACH_HEAD = 2;
public static readonly LSL_Types.LSLInteger ATTACH_LSHOULDER = 3;
public static readonly LSL_Types.LSLInteger ATTACH_RSHOULDER = 4;
public static readonly LSL_Types.LSLInteger ATTACH_LHAND = 5;
public static readonly LSL_Types.LSLInteger ATTACH_RHAND = 6;
public static readonly LSL_Types.LSLInteger ATTACH_LFOOT = 7;
public static readonly LSL_Types.LSLInteger ATTACH_RFOOT = 8;
public static readonly LSL_Types.LSLInteger ATTACH_BACK = 9;
public static readonly LSL_Types.LSLInteger ATTACH_PELVIS = 10;
public static readonly LSL_Types.LSLInteger ATTACH_MOUTH = 11;
public static readonly LSL_Types.LSLInteger ATTACH_CHIN = 12;
public static readonly LSL_Types.LSLInteger ATTACH_LEAR = 13;
public static readonly LSL_Types.LSLInteger ATTACH_REAR = 14;
public static readonly LSL_Types.LSLInteger ATTACH_LEYE = 15;
public static readonly LSL_Types.LSLInteger ATTACH_REYE = 16;
public static readonly LSL_Types.LSLInteger ATTACH_NOSE = 17;
public static readonly LSL_Types.LSLInteger ATTACH_RUARM = 18;
public static readonly LSL_Types.LSLInteger ATTACH_RLARM = 19;
public static readonly LSL_Types.LSLInteger ATTACH_LUARM = 20;
public static readonly LSL_Types.LSLInteger ATTACH_LLARM = 21;
public static readonly LSL_Types.LSLInteger ATTACH_RHIP = 22;
public static readonly LSL_Types.LSLInteger ATTACH_RULEG = 23;
public static readonly LSL_Types.LSLInteger ATTACH_RLLEG = 24;
public static readonly LSL_Types.LSLInteger ATTACH_LHIP = 25;
public static readonly LSL_Types.LSLInteger ATTACH_LULEG = 26;
public static readonly LSL_Types.LSLInteger ATTACH_LLLEG = 27;
public static readonly LSL_Types.LSLInteger ATTACH_BELLY = 28;
public static readonly LSL_Types.LSLInteger ATTACH_LPEC = 29;
public static readonly LSL_Types.LSLInteger ATTACH_RPEC = 30;
public static readonly LSL_Types.LSLInteger ATTACH_LEFT_PEC = 29;
public static readonly LSL_Types.LSLInteger ATTACH_RIGHT_PEC = 30;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_CENTER_2 = 31;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_RIGHT = 32;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_CENTER = 33;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_TOP_LEFT = 34;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_CENTER_1 = 35;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM_LEFT = 36;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM = 37;
public static readonly LSL_Types.LSLInteger ATTACH_HUD_BOTTOM_RIGHT = 38;
public static readonly LSL_Types.LSLInteger LAND_LEVEL = 0;
public static readonly LSL_Types.LSLInteger LAND_RAISE = 1;
public static readonly LSL_Types.LSLInteger LAND_LOWER = 2;
public static readonly LSL_Types.LSLInteger LAND_SMOOTH = 3;
public static readonly LSL_Types.LSLInteger LAND_NOISE = 4;
public static readonly LSL_Types.LSLInteger LAND_REVERT = 5;
public static readonly LSL_Types.LSLInteger LAND_SMALL_BRUSH = 1;
public static readonly LSL_Types.LSLInteger LAND_MEDIUM_BRUSH = 2;
public static readonly LSL_Types.LSLInteger LAND_LARGE_BRUSH = 3;
// llGetAgentList
public static readonly LSL_Types.LSLInteger AGENT_LIST_PARCEL = 1;
public static readonly LSL_Types.LSLInteger AGENT_LIST_PARCEL_OWNER = 2;
public static readonly LSL_Types.LSLInteger AGENT_LIST_REGION = 4;
//Agent Dataserver
public static readonly LSL_Types.LSLInteger DATA_ONLINE = 1;
public static readonly LSL_Types.LSLInteger DATA_NAME = 2;
public static readonly LSL_Types.LSLInteger DATA_BORN = 3;
public static readonly LSL_Types.LSLInteger DATA_RATING = 4;
public static readonly LSL_Types.LSLInteger DATA_SIM_POS = 5;
public static readonly LSL_Types.LSLInteger DATA_SIM_STATUS = 6;
public static readonly LSL_Types.LSLInteger DATA_SIM_RATING = 7;
public static readonly LSL_Types.LSLInteger DATA_PAYINFO = 8;
public static readonly LSL_Types.LSLInteger DATA_SIM_RELEASE = 128;
public static readonly LSL_Types.LSLInteger ANIM_ON = 1;
public static readonly LSL_Types.LSLInteger LOOP = 2;
public static readonly LSL_Types.LSLInteger REVERSE = 4;
public static readonly LSL_Types.LSLInteger PING_PONG = 8;
public static readonly LSL_Types.LSLInteger SMOOTH = 16;
public static readonly LSL_Types.LSLInteger ROTATE = 32;
public static readonly LSL_Types.LSLInteger SCALE = 64;
public static readonly LSL_Types.LSLInteger ALL_SIDES = -1;
public static readonly LSL_Types.LSLInteger LINK_SET = -1;
public static readonly LSL_Types.LSLInteger LINK_ROOT = 1;
public static readonly LSL_Types.LSLInteger LINK_ALL_OTHERS = -2;
public static readonly LSL_Types.LSLInteger LINK_ALL_CHILDREN = -3;
public static readonly LSL_Types.LSLInteger LINK_THIS = -4;
public static readonly LSL_Types.LSLInteger CHANGED_INVENTORY = 1;
public static readonly LSL_Types.LSLInteger CHANGED_COLOR = 2;
public static readonly LSL_Types.LSLInteger CHANGED_SHAPE = 4;
public static readonly LSL_Types.LSLInteger CHANGED_SCALE = 8;
public static readonly LSL_Types.LSLInteger CHANGED_TEXTURE = 16;
public static readonly LSL_Types.LSLInteger CHANGED_LINK = 32;
public static readonly LSL_Types.LSLInteger CHANGED_ALLOWED_DROP = 64;
public static readonly LSL_Types.LSLInteger CHANGED_OWNER = 128;
public static readonly LSL_Types.LSLInteger CHANGED_REGION = 256;
public static readonly LSL_Types.LSLInteger CHANGED_TELEPORT = 512;
public static readonly LSL_Types.LSLInteger CHANGED_REGION_RESTART = 1024;
public static readonly LSL_Types.LSLInteger CHANGED_REGION_START = 1024;
//LL Changed the constant from CHANGED_REGION_RESTART
public static readonly LSL_Types.LSLInteger CHANGED_MEDIA = 2048;
public static readonly LSL_Types.LSLInteger CHANGED_ANIMATION = 16384;
public static readonly LSL_Types.LSLInteger CHANGED_STATE = 32768;
public static readonly LSL_Types.LSLInteger TYPE_INVALID = 0;
public static readonly LSL_Types.LSLInteger TYPE_INTEGER = 1;
public static readonly LSL_Types.LSLInteger TYPE_FLOAT = 2;
public static readonly LSL_Types.LSLInteger TYPE_STRING = 3;
public static readonly LSL_Types.LSLInteger TYPE_KEY = 4;
public static readonly LSL_Types.LSLInteger TYPE_VECTOR = 5;
public static readonly LSL_Types.LSLInteger TYPE_ROTATION = 6;
//XML RPC Remote Data Channel
public static readonly LSL_Types.LSLInteger REMOTE_DATA_CHANNEL = 1;
public static readonly LSL_Types.LSLInteger REMOTE_DATA_REQUEST = 2;
public static readonly LSL_Types.LSLInteger REMOTE_DATA_REPLY = 3;
//llHTTPRequest
public static readonly LSL_Types.LSLInteger HTTP_METHOD = 0;
public static readonly LSL_Types.LSLInteger HTTP_MIMETYPE = 1;
public static readonly LSL_Types.LSLInteger HTTP_BODY_MAXLENGTH = 2;
public static readonly LSL_Types.LSLInteger HTTP_VERIFY_CERT = 3;
public static readonly LSL_Types.LSLInteger CONTENT_TYPE_TEXT = 0;
public static readonly LSL_Types.LSLInteger CONTENT_TYPE_HTML = 1;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL = 2;
public static readonly LSL_Types.LSLInteger PRIM_PHYSICS = 3;
public static readonly LSL_Types.LSLInteger PRIM_TEMP_ON_REZ = 4;
public static readonly LSL_Types.LSLInteger PRIM_PHANTOM = 5;
public static readonly LSL_Types.LSLInteger PRIM_POSITION = 6;
public static readonly LSL_Types.LSLInteger PRIM_SIZE = 7;
public static readonly LSL_Types.LSLInteger PRIM_ROTATION = 8;
public static readonly LSL_Types.LSLInteger PRIM_TYPE = 9;
public static readonly LSL_Types.LSLInteger PRIM_TEXTURE = 17;
public static readonly LSL_Types.LSLInteger PRIM_COLOR = 18;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_SHINY = 19;
public static readonly LSL_Types.LSLInteger PRIM_FULLBRIGHT = 20;
public static readonly LSL_Types.LSLInteger PRIM_FLEXIBLE = 21;
public static readonly LSL_Types.LSLInteger PRIM_TEXGEN = 22;
public static readonly LSL_Types.LSLInteger PRIM_POINT_LIGHT = 23;
public static readonly LSL_Types.LSLInteger PRIM_CAST_SHADOWS = 24;
// Not implemented, here for completeness sake
public static readonly LSL_Types.LSLInteger PRIM_GLOW = 25;
public static readonly LSL_Types.LSLInteger PRIM_TEXT = 26;
public static readonly LSL_Types.LSLInteger PRIM_NAME = 27;
public static readonly LSL_Types.LSLInteger PRIM_DESC = 28;
public static readonly LSL_Types.LSLInteger PRIM_ROT_LOCAL = 29;
public static readonly LSL_Types.LSLInteger PRIM_OMEGA = 32;
public static readonly LSL_Types.LSLInteger PRIM_POS_LOCAL = 33;
public static readonly LSL_Types.LSLInteger PRIM_LINK_TARGET = 34;
public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_TYPE = 35;
public static readonly LSL_Types.LSLInteger PRIM_TEXGEN_DEFAULT = 0;
public static readonly LSL_Types.LSLInteger PRIM_TEXGEN_PLANAR = 1;
public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_PRIM = 0;
public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_CONVEX = 2;
public static readonly LSL_Types.LSLInteger PRIM_PHYSICS_SHAPE_NONE = 1;
public static readonly LSL_Types.LSLInteger DENSITY = 0;
public static readonly LSL_Types.LSLInteger FRICTION = 1;
public static readonly LSL_Types.LSLInteger RESTITUTION = 2;
public static readonly LSL_Types.LSLInteger GRAVITY_MULTIPLIER = 3;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_BOX = 0;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_CYLINDER = 1;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_PRISM = 2;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_SPHERE = 3;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_TORUS = 4;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_TUBE = 5;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_RING = 6;
public static readonly LSL_Types.LSLInteger PRIM_TYPE_SCULPT = 7;
public static readonly LSL_Types.LSLInteger PRIM_HOLE_DEFAULT = 0;
public static readonly LSL_Types.LSLInteger PRIM_HOLE_CIRCLE = 16;
public static readonly LSL_Types.LSLInteger PRIM_HOLE_SQUARE = 32;
public static readonly LSL_Types.LSLInteger PRIM_HOLE_TRIANGLE = 48;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_STONE = 0;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_METAL = 1;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_GLASS = 2;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_WOOD = 3;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_FLESH = 4;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_PLASTIC = 5;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_RUBBER = 6;
public static readonly LSL_Types.LSLInteger PRIM_MATERIAL_LIGHT = 7;
public static readonly LSL_Types.LSLInteger PRIM_SHINY_NONE = 0;
public static readonly LSL_Types.LSLInteger PRIM_SHINY_LOW = 1;
public static readonly LSL_Types.LSLInteger PRIM_SHINY_MEDIUM = 2;
public static readonly LSL_Types.LSLInteger PRIM_SHINY_HIGH = 3;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_NONE = 0;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_BRIGHT = 1;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_DARK = 2;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_WOOD = 3;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_BARK = 4;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_BRICKS = 5;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_CHECKER = 6;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_CONCRETE = 7;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_TILE = 8;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_STONE = 9;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_DISKS = 10;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_GRAVEL = 11;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_BLOBS = 12;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_SIDING = 13;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_LARGETILE = 14;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_STUCCO = 15;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_SUCTION = 16;
public static readonly LSL_Types.LSLInteger PRIM_BUMP_WEAVE = 17;
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_SPHERE = 1;
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_TORUS = 2;
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_PLANE = 3;
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_CYLINDER = 4;
//Aurora-Sim const only
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_TYPE_MESH = 5;
//???
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_FLAG_INVERT = 64;
public static readonly LSL_Types.LSLInteger PRIM_SCULPT_FLAG_MIRROR = 128;
public static readonly LSL_Types.LSLInteger MASK_BASE = 0;
public static readonly LSL_Types.LSLInteger MASK_OWNER = 1;
public static readonly LSL_Types.LSLInteger MASK_GROUP = 2;
public static readonly LSL_Types.LSLInteger MASK_EVERYONE = 3;
public static readonly LSL_Types.LSLInteger MASK_NEXT = 4;
public static readonly LSL_Types.LSLInteger PERM_TRANSFER = 8192;
public static readonly LSL_Types.LSLInteger PERM_MODIFY = 16384;
public static readonly LSL_Types.LSLInteger PERM_COPY = 32768;
public static readonly LSL_Types.LSLInteger PERM_MOVE = 524288;
public static readonly LSL_Types.LSLInteger PERM_ALL = 2147483647;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_STOP = 0;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_PAUSE = 1;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_PLAY = 2;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_LOOP = 3;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TEXTURE = 4;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_URL = 5;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TIME = 6;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_AGENT = 7;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_UNLOAD = 8;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_TYPE = 10;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_SIZE = 11;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_DESC = 12;
public static readonly LSL_Types.LSLInteger PARCEL_MEDIA_COMMAND_LOOP_SET = 13;
// constants for llGetPrimMediaParams/llSetPrimMediaParams
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_ALT_IMAGE_ENABLE = 0;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS = 1;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CURRENT_URL = 2;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_HOME_URL = 3;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_LOOP = 4;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_PLAY = 5;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_SCALE = 6;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_AUTO_ZOOM = 7;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_FIRST_CLICK_INTERACT = 8;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WIDTH_PIXELS = 9;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_HEIGHT_PIXELS = 10;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WHITELIST_ENABLE = 11;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_WHITELIST = 12;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERMS_INTERACT = 13;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERMS_CONTROL = 14;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS_STANDARD = 0;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_CONTROLS_MINI = 1;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_NONE = 0;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_OWNER = 1;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_GROUP = 2;
public static readonly LSL_Types.LSLInteger PRIM_MEDIA_PERM_ANYONE = 4;
// extra constants for llSetPrimMediaParams
public static readonly LSL_Types.LSLInteger LSL_STATUS_OK = new LSL_Types.LSLInteger(0);
public static readonly LSL_Types.LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSL_Types.LSLInteger(1000);
public static readonly LSL_Types.LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSL_Types.LSLInteger(1001);
public static readonly LSL_Types.LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSL_Types.LSLInteger(1002);
public static readonly LSL_Types.LSLInteger LSL_STATUS_NOT_FOUND = new LSL_Types.LSLInteger(1003);
public static readonly LSL_Types.LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSL_Types.LSLInteger(1004);
public static readonly LSL_Types.LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSL_Types.LSLInteger(1999);
public static readonly LSL_Types.LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSL_Types.LSLInteger(2001);
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_LANDMARK = 0x8;
// parcel allows landmarks to be created
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_TERRAFORM = 0x10;
// parcel allows anyone to terraform the land
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40;
// parcel allows anyone to create objects
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_ACCESS_GROUP = 0x100;
// parcel limits access to a group
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_ACCESS_LIST = 0x200;
// parcel limits access to a list of residents
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_BAN_LIST = 0x400;
// parcel uses a ban list, including restricting access based on payment info
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800;
// parcel allows passes to be purchased
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000;
// parcel restricts spatialized sound to the parcel
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000;
// parcel restricts llPushObject
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000;
// parcel allows scripts owned by group
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000;
// parcel allows group object creation
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000;
// parcel allows objects owned by any user to enter
public static readonly LSL_Types.LSLInteger PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000;
// parcel allows with the same group to enter
public static readonly LSL_Types.LSLInteger REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled
public static readonly LSL_Types.LSLInteger REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position
public static readonly LSL_Types.LSLInteger REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled
public static readonly LSL_Types.LSLInteger REGION_FLAG_SANDBOX = 0x100; // region is a sandbox
public static readonly LSL_Types.LSLInteger REGION_FLAG_DISABLE_COLLISIONS = 0x1000;
// region has disabled collisions
public static readonly LSL_Types.LSLInteger REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics
public static readonly LSL_Types.LSLInteger REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying
public static readonly LSL_Types.LSLInteger REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000;
// region allows direct teleports
public static readonly LSL_Types.LSLInteger REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000;
// region restricts llPushObject
public static readonly LSL_Types.LSLInteger PAY_HIDE = new LSL_Types.LSLInteger(-1);
public static readonly LSL_Types.LSLInteger PAY_DEFAULT = new LSL_Types.LSLInteger(-2);
public static readonly LSL_Types.LSLInteger PAYMENT_INFO_ON_FILE = 0x1;
public static readonly LSL_Types.LSLInteger PAYMENT_INFO_USED = 0x2;
public static readonly LSL_Types.LSLString NULL_KEY = "00000000-0000-0000-0000-000000000000";
public static readonly LSL_Types.LSLString EOF = "\n\n\n";
public static readonly LSL_Types.LSLFloat PI = 3.1415926535897932384626433832795;
public static readonly LSL_Types.LSLFloat TWO_PI = 6.283185307179586476925286766559;
public static readonly LSL_Types.LSLFloat PI_BY_TWO = 1.5707963267948966192313216916398;
public static readonly LSL_Types.LSLFloat DEG_TO_RAD = 0.01745329238f;
public static readonly LSL_Types.LSLFloat RAD_TO_DEG = 57.29578f;
public static readonly LSL_Types.LSLFloat SQRT2 = 1.4142135623730950488016887242097;
public static readonly LSL_Types.LSLInteger STRING_TRIM_HEAD = 1;
public static readonly LSL_Types.LSLInteger STRING_TRIM_TAIL = 2;
public static readonly LSL_Types.LSLInteger STRING_TRIM = 3;
public static readonly LSL_Types.LSLInteger LIST_STAT_RANGE = 0;
public static readonly LSL_Types.LSLInteger LIST_STAT_MIN = 1;
public static readonly LSL_Types.LSLInteger LIST_STAT_MAX = 2;
public static readonly LSL_Types.LSLInteger LIST_STAT_MEAN = 3;
public static readonly LSL_Types.LSLInteger LIST_STAT_MEDIAN = 4;
public static readonly LSL_Types.LSLInteger LIST_STAT_STD_DEV = 5;
public static readonly LSL_Types.LSLInteger LIST_STAT_SUM = 6;
public static readonly LSL_Types.LSLInteger LIST_STAT_SUM_SQUARES = 7;
public static readonly LSL_Types.LSLInteger LIST_STAT_NUM_COUNT = 8;
public static readonly LSL_Types.LSLInteger LIST_STAT_GEOMETRIC_MEAN = 9;
public static readonly LSL_Types.LSLInteger LIST_STAT_HARMONIC_MEAN = 100;
//ParcelPrim Categories
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_TOTAL = 0;
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_OWNER = 1;
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_GROUP = 2;
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_OTHER = 3;
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_SELECTED = 4;
public static readonly LSL_Types.LSLInteger PARCEL_COUNT_TEMP = 5;
public static readonly LSL_Types.LSLInteger DEBUG_CHANNEL = 0x7FFFFFFF;
public static readonly LSL_Types.LSLInteger PUBLIC_CHANNEL = 0x00000000;
public static readonly LSL_Types.LSLInteger OBJECT_UNKNOWN_DETAIL = -1;
public static readonly LSL_Types.LSLInteger OBJECT_NAME = 1;
public static readonly LSL_Types.LSLInteger OBJECT_DESC = 2;
public static readonly LSL_Types.LSLInteger OBJECT_POS = 3;
public static readonly LSL_Types.LSLInteger OBJECT_ROT = 4;
public static readonly LSL_Types.LSLInteger OBJECT_VELOCITY = 5;
public static readonly LSL_Types.LSLInteger OBJECT_OWNER = 6;
public static readonly LSL_Types.LSLInteger OBJECT_GROUP = 7;
public static readonly LSL_Types.LSLInteger OBJECT_CREATOR = 8;
public static readonly LSL_Types.LSLInteger OBJECT_RUNNING_SCRIPT_COUNT = 9;
public static readonly LSL_Types.LSLInteger OBJECT_TOTAL_SCRIPT_COUNT = 10;
public static readonly LSL_Types.LSLInteger OBJECT_SCRIPT_MEMORY = 11;
public static readonly LSL_Types.LSLInteger OBJECT_SCRIPT_TIME = 12;
public static readonly LSL_Types.LSLInteger OBJECT_PRIM_EQUIVALENCE = 13;
public static readonly LSL_Types.LSLInteger OBJECT_SERVER_COST = 14;
public static readonly LSL_Types.LSLInteger OBJECT_STREAMING_COST = 15;
public static readonly LSL_Types.LSLInteger OBJECT_PHYSICS_COST = 16;
public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0);
public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0);
// constants for llSetCameraParams
public static readonly LSL_Types.LSLInteger CAMERA_PITCH = 0;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET = 1;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_X = 2;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_Y = 3;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_OFFSET_Z = 4;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_LAG = 5;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_LAG = 6;
public static readonly LSL_Types.LSLInteger CAMERA_DISTANCE = 7;
public static readonly LSL_Types.LSLInteger CAMERA_BEHINDNESS_ANGLE = 8;
public static readonly LSL_Types.LSLInteger CAMERA_BEHINDNESS_LAG = 9;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_THRESHOLD = 10;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_THRESHOLD = 11;
public static readonly LSL_Types.LSLInteger CAMERA_ACTIVE = 12;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION = 13;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_X = 14;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_Y = 15;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_Z = 16;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS = 17;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_X = 18;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_Y = 19;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_Z = 20;
public static readonly LSL_Types.LSLInteger CAMERA_POSITION_LOCKED = 21;
public static readonly LSL_Types.LSLInteger CAMERA_FOCUS_LOCKED = 22;
// constants for llGetParcelDetails
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_NAME = 0;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_DESC = 1;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_OWNER = 2;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_GROUP = 3;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_AREA = 4;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_ID = 5;
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_PRIVACY = 6; //Old name
public static readonly LSL_Types.LSLInteger PARCEL_DETAILS_SEE_AVATARS = 6;
// constants for llSetClickAction
public static readonly LSL_Types.LSLInteger CLICK_ACTION_NONE = 0;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_TOUCH = 0;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_SIT = 1;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_BUY = 2;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_PAY = 3;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_OPEN = 4;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_PLAY = 5;
public static readonly LSL_Types.LSLInteger CLICK_ACTION_OPEN_MEDIA = 6;
// constants for the llDetectedTouch* functions
public static readonly LSL_Types.LSLInteger TOUCH_INVALID_FACE = -1;
public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0);
public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR;
// Constants for default textures
public static readonly LSL_Types.LSLString TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f";
public static readonly LSL_Types.LSLString TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f";
public static readonly LSL_Types.LSLString TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f";
public static readonly LSL_Types.LSLString TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903";
public static readonly LSL_Types.LSLString TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361";
// Constants for osGetRegionStats
public static readonly LSL_Types.LSLInteger STATS_TIME_DILATION = 0;
public static readonly LSL_Types.LSLInteger STATS_SIM_FPS = 1;
public static readonly LSL_Types.LSLInteger STATS_PHYSICS_FPS = 2;
public static readonly LSL_Types.LSLInteger STATS_AGENT_UPDATES = 3;
public static readonly LSL_Types.LSLInteger STATS_FRAME_MS = 4;
public static readonly LSL_Types.LSLInteger STATS_NET_MS = 5;
public static readonly LSL_Types.LSLInteger STATS_OTHER_MS = 6;
public static readonly LSL_Types.LSLInteger STATS_PHYSICS_MS = 7;
public static readonly LSL_Types.LSLInteger STATS_AGENT_MS = 8;
public static readonly LSL_Types.LSLInteger STATS_IMAGE_MS = 9;
public static readonly LSL_Types.LSLInteger STATS_SCRIPT_MS = 10;
public static readonly LSL_Types.LSLInteger STATS_TOTAL_PRIMS = 11;
public static readonly LSL_Types.LSLInteger STATS_ACTIVE_PRIMS = 12;
public static readonly LSL_Types.LSLInteger STATS_ROOT_AGENTS = 13;
public static readonly LSL_Types.LSLInteger STATS_CHILD_AGENTS = 14;
public static readonly LSL_Types.LSLInteger STATS_ACTIVE_SCRIPTS = 15;
public static readonly LSL_Types.LSLInteger STATS_SCRIPT_LPS = 16; //Doesn't work
public static readonly LSL_Types.LSLInteger STATS_SCRIPT_EPS = 31;
public static readonly LSL_Types.LSLInteger STATS_IN_PACKETS_PER_SECOND = 17;
public static readonly LSL_Types.LSLInteger STATS_OUT_PACKETS_PER_SECOND = 18;
public static readonly LSL_Types.LSLInteger STATS_PENDING_DOWNLOADS = 19;
public static readonly LSL_Types.LSLInteger STATS_PENDING_UPLOADS = 20;
public static readonly LSL_Types.LSLInteger STATS_UNACKED_BYTES = 24;
public static readonly LSL_Types.LSLString URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED";
public static readonly LSL_Types.LSLString URL_REQUEST_DENIED = "URL_REQUEST_DENIED";
public static readonly LSL_Types.LSLInteger PASS_IF_NOT_HANDLED = 0;
public static readonly LSL_Types.LSLInteger PASS_ALWAYS = 1;
public static readonly LSL_Types.LSLInteger PASS_NEVER = 2;
public static readonly LSL_Types.LSLInteger RC_REJECT_TYPES = 2;
public static readonly LSL_Types.LSLInteger RC_DATA_FLAGS = 4;
public static readonly LSL_Types.LSLInteger RC_MAX_HITS = 8;
public static readonly LSL_Types.LSLInteger RC_DETECT_PHANTOM = 16;
public static readonly LSL_Types.LSLInteger RC_REJECT_AGENTS = 2;
public static readonly LSL_Types.LSLInteger RC_REJECT_PHYSICAL = 4;
public static readonly LSL_Types.LSLInteger RC_REJECT_NONPHYSICAL = 8;
public static readonly LSL_Types.LSLInteger RC_REJECT_LAND = 16;
public static readonly LSL_Types.LSLInteger RC_GET_NORMAL = 2;
public static readonly LSL_Types.LSLInteger RC_GET_ROOT_KEY = 4;
public static readonly LSL_Types.LSLInteger RC_GET_LINK_NUM = 8;
public static readonly LSL_Types.LSLInteger RCERR_CAST_TIME_EXCEEDED = 1;
public static readonly LSL_Types.LSLInteger PROFILE_NONE = 0;
public static readonly LSL_Types.LSLInteger PROFILE_SCRIPT_MEMORY = 1;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_BANNED_AGENT_ADD = 4;
public static readonly LSL_Types.LSLInteger ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5;
public static readonly LSL_Types.LSLInteger KFM_MODE = 2;
public static readonly LSL_Types.LSLInteger KFM_LOOP = 4;
public static readonly LSL_Types.LSLInteger KFM_REVERSE = 8;
public static readonly LSL_Types.LSLInteger KFM_FORWARD = 16;
public static readonly LSL_Types.LSLInteger KFM_PING_PONG = 32;
public static readonly LSL_Types.LSLInteger KFM_TRANSLATION = 64;
public static readonly LSL_Types.LSLInteger KFM_ROTATION = 128;
public static readonly LSL_Types.LSLInteger KFM_COMMAND = 256;
public static readonly LSL_Types.LSLInteger KFM_CMD_STOP = 512;
public static readonly LSL_Types.LSLInteger KFM_CMD_PLAY = 1024;
public static readonly LSL_Types.LSLInteger KFM_CMD_PAUSE = 2048;
public static readonly LSL_Types.LSLInteger KFM_DATA = 4096;
public static readonly LSL_Types.LSLInteger CHARACTER_DESIRED_SPEED = 1;
public static readonly LSL_Types.LSLInteger CHARACTER_RADIUS = 2;
public static readonly LSL_Types.LSLInteger CHARACTER_LENGTH = 3;
public static readonly LSL_Types.LSLInteger CHARACTER_ORIENTATION = 4;
public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE = 7;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE = 8;
public static readonly LSL_Types.LSLInteger CHARACTER_AVOIDANCE_MODE = 9;
public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ACCEL = 10;
public static readonly LSL_Types.LSLInteger CHARACTER_MAX_DECEL = 11;
public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ANGULAR_SPEED = 12;
public static readonly LSL_Types.LSLInteger CHARACTER_MAX_ANGULAR_ACCEL = 13;
public static readonly LSL_Types.LSLInteger CHARACTER_TURN_SPEED_MULTIPLIER = 14;
public static readonly LSL_Types.LSLInteger PURSUIT_OFFSET = 1;
public static readonly LSL_Types.LSLInteger REQUIRE_LINE_OF_SIGHT = 2;
public static readonly LSL_Types.LSLInteger PURSUIT_INTERCEPT = 4;
public static readonly LSL_Types.LSLInteger PURSUIT_FUZZ_FACTOR = 8;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_NONE = 0;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_A = 1;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_B = 2;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_C = 3;
public static readonly LSL_Types.LSLInteger CHARACTER_TYPE_D = 4;
public static readonly LSL_Types.LSLInteger AVOID_CHARACTERS = 1;
public static readonly LSL_Types.LSLInteger AVOID_DYNAMIC_OBSTACLES = 2;
public static readonly LSL_Types.LSLInteger HORIZONTAL = 0;
public static readonly LSL_Types.LSLInteger VERTICAL = 1;
public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_NONE = 1;
public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_FAST = 2;
public static readonly LSL_Types.LSLInteger TRAVERSAL_TYPE_SLOW = 4;
public static readonly LSL_Types.LSLInteger PU_SLOWDOWN_DISTANCE_REACHED = 0x00;
public static readonly LSL_Types.LSLInteger PU_GOAL_REACHED = 0x01;
public static readonly LSL_Types.LSLInteger PU_FAILURE_INVALID_START = 0x02;
public static readonly LSL_Types.LSLInteger PU_FAILURE_INVALID_GOAL = 0x03;
public static readonly LSL_Types.LSLInteger PU_FAILURE_UNREACHABLE = 0x04;
public static readonly LSL_Types.LSLInteger PU_FAILURE_TARGET_GONE = 0x05;
public static readonly LSL_Types.LSLInteger PU_FAILURE_NO_VALID_DESTINATION = 0x06;
public static readonly LSL_Types.LSLInteger PU_EVADE_HIDDEN = 0x07;
public static readonly LSL_Types.LSLInteger PU_EVADE_SPOTTED = 0x08;
public static readonly LSL_Types.LSLInteger PU_FAILURE_NO_NAVMESH = 0x09;
public static readonly LSL_Types.LSLInteger PU_FAILURE_OTHER = 0xF4240;
public static readonly LSL_Types.LSLInteger FORCE_DIRECT_PATH = 1;
public static readonly LSL_Types.LSLInteger CHARACTER_CMD_STOP = 0x0;
public static readonly LSL_Types.LSLInteger CHARACTER_CMD_JUMP = 0x1;
}
}
| |
// Copyright 2020 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.
using Google.Api.Gax;
using Google.Apis.Bigquery.v2.Data;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.BigQuery.V2
{
public abstract partial class BigQueryClient
{
#region GetModel (autogenerated - do not edit manually)
/// <summary>
/// Retrieves the specified model within this client's project.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="GetModel(ModelReference, GetModelOptions)"/>.
/// </summary>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The requested model.</returns>
public virtual BigQueryModel GetModel(string datasetId, string modelId, GetModelOptions options = null) =>
GetModel(GetModelReference(datasetId, modelId), options);
/// <summary>
/// Retrieves the specified model.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="GetModel(ModelReference, GetModelOptions)"/>.
/// </summary>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The requested model.</returns>
public virtual BigQueryModel GetModel(string projectId, string datasetId, string modelId, GetModelOptions options = null) =>
GetModel(GetModelReference(projectId, datasetId, modelId), options);
/// <summary>
/// Retrieves the specified model.
/// </summary>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The requested model.</returns>
public virtual BigQueryModel GetModel(ModelReference modelReference, GetModelOptions options = null) =>
throw new NotImplementedException();
/// <summary>
/// Asynchronously retrieves the specified model within this client's project.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="GetModelAsync(ModelReference, GetModelOptions, CancellationToken)"/>.
/// </summary>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the requested model.</returns>
public virtual Task<BigQueryModel> GetModelAsync(string datasetId, string modelId, GetModelOptions options = null, CancellationToken cancellationToken = default) =>
GetModelAsync(GetModelReference(datasetId, modelId), options, cancellationToken);
/// <summary>
/// Asynchronously retrieves the specified model.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="GetModelAsync(ModelReference, GetModelOptions, CancellationToken)"/>.
/// </summary>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the requested model.</returns>
public virtual Task<BigQueryModel> GetModelAsync(string projectId, string datasetId, string modelId, GetModelOptions options = null, CancellationToken cancellationToken = default) =>
GetModelAsync(GetModelReference(projectId, datasetId, modelId), options, cancellationToken);
/// <summary>
/// Asynchronously retrieves the specified model.
/// </summary>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the requested model.</returns>
public virtual Task<BigQueryModel> GetModelAsync(ModelReference modelReference, GetModelOptions options = null, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
#endregion
#region DeleteModel (autogenerated - do not edit manually)
/// <summary>
/// Deletes the specified model within this client's project.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="DeleteModel(ModelReference, DeleteModelOptions)"/>.
/// </summary>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
public virtual void DeleteModel(string datasetId, string modelId, DeleteModelOptions options = null) =>
DeleteModel(GetModelReference(datasetId, modelId), options);
/// <summary>
/// Deletes the specified model.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="DeleteModel(ModelReference, DeleteModelOptions)"/>.
/// </summary>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
public virtual void DeleteModel(string projectId, string datasetId, string modelId, DeleteModelOptions options = null) =>
DeleteModel(GetModelReference(projectId, datasetId, modelId), options);
/// <summary>
/// Deletes the specified model.
/// </summary>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
public virtual void DeleteModel(ModelReference modelReference, DeleteModelOptions options = null) =>
throw new NotImplementedException();
/// <summary>
/// Asynchronously deletes the specified model within this client's project.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="DeleteModelAsync(ModelReference, DeleteModelOptions, CancellationToken)"/>.
/// </summary>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public virtual Task DeleteModelAsync(string datasetId, string modelId, DeleteModelOptions options = null, CancellationToken cancellationToken = default) =>
DeleteModelAsync(GetModelReference(datasetId, modelId), options, cancellationToken);
/// <summary>
/// Asynchronously deletes the specified model.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="DeleteModelAsync(ModelReference, DeleteModelOptions, CancellationToken)"/>.
/// </summary>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public virtual Task DeleteModelAsync(string projectId, string datasetId, string modelId, DeleteModelOptions options = null, CancellationToken cancellationToken = default) =>
DeleteModelAsync(GetModelReference(projectId, datasetId, modelId), options, cancellationToken);
/// <summary>
/// Asynchronously deletes the specified model.
/// </summary>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public virtual Task DeleteModelAsync(ModelReference modelReference, DeleteModelOptions options = null, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
#endregion
#region PatchModel (autogenerated - do not edit manually)
/// <summary>
/// Patches the specified model within this client's project with fields in the given resource.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="PatchModel(ModelReference, Model, PatchModelOptions)"/>.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The updated model.</returns>
public virtual BigQueryModel PatchModel(string datasetId, string modelId, Model resource, PatchModelOptions options = null) =>
PatchModel(GetModelReference(datasetId, modelId), resource, options);
/// <summary>
/// Patches the specified model with fields in the given resource.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="PatchModel(ModelReference, Model, PatchModelOptions)"/>.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The updated model.</returns>
public virtual BigQueryModel PatchModel(string projectId, string datasetId, string modelId, Model resource, PatchModelOptions options = null) =>
PatchModel(GetModelReference(projectId, datasetId, modelId), resource, options);
/// <summary>
/// Patches the specified model with fields in the given resource.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>The updated model.</returns>
public virtual BigQueryModel PatchModel(ModelReference modelReference, Model resource, PatchModelOptions options = null) =>
throw new NotImplementedException();
/// <summary>
/// Asynchronously patches the specified model within this client's project with fields in the given resource.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="PatchModelAsync(ModelReference, Model, PatchModelOptions, CancellationToken)"/>.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the updated model.</returns>
public virtual Task<BigQueryModel> PatchModelAsync(string datasetId, string modelId, Model resource, PatchModelOptions options = null, CancellationToken cancellationToken = default) =>
PatchModelAsync(GetModelReference(datasetId, modelId), resource, options, cancellationToken);
/// <summary>
/// Asynchronously patches the specified model with fields in the given resource.
/// This method just creates a <see cref="ModelReference"/> and delegates to <see cref="PatchModelAsync(ModelReference, Model, PatchModelOptions, CancellationToken)"/>.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="projectId">The project ID. Must not be null.</param>
/// <param name="datasetId">The dataset ID. Must not be null.</param>
/// <param name="modelId">The model ID. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the updated model.</returns>
public virtual Task<BigQueryModel> PatchModelAsync(string projectId, string datasetId, string modelId, Model resource, PatchModelOptions options = null, CancellationToken cancellationToken = default) =>
PatchModelAsync(GetModelReference(projectId, datasetId, modelId), resource, options, cancellationToken);
/// <summary>
/// Asynchronously patches the specified model with fields in the given resource.
/// </summary>
/// <remarks>
/// If the resource contains an ETag, it is used for optimistic concurrency validation.
/// </remarks>
/// <param name="modelReference">A fully-qualified identifier for the model. Must not be null.</param>
/// <param name="resource">The model resource representation to use for the patch. Only fields present in the resource will be updated.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task representing the asynchronous operation. When complete, the result is
/// the updated model.</returns>
public virtual Task<BigQueryModel> PatchModelAsync(ModelReference modelReference, Model resource, PatchModelOptions options = null, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
#endregion
#region ListModelss
/// <summary>
/// Lists the models in a dataset specified by project ID and dataset ID.
/// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="ListModels(DatasetReference, ListModelsOptions)"/>.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="projectId">The ID of the project containing the dataset. Must not be null.</param>
/// <param name="datasetId">The ID of the dataset to list models from. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>A sequence of models within the dataset.</returns>
public virtual PagedEnumerable<ListModelsResponse, BigQueryModel> ListModels(string projectId, string datasetId, ListModelsOptions options = null) =>
ListModels(GetDatasetReference(projectId, datasetId), options);
/// <summary>
/// Lists the models in a dataset specified by dataset ID, where the dataset is in this client's project.
/// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="ListModels(DatasetReference, ListModelsOptions)"/>.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="datasetId">The ID of the dataset to list models from. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>A sequence of models within the dataset.</returns>
public virtual PagedEnumerable<ListModelsResponse, BigQueryModel> ListModels(string datasetId, ListModelsOptions options = null) =>
ListModels(GetDatasetReference(datasetId), options);
/// <summary>
/// Lists the models in a dataset.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>A sequence of models within the dataset.</returns>
public virtual PagedEnumerable<ListModelsResponse, BigQueryModel> ListModels(DatasetReference datasetReference, ListModelsOptions options = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists the models in a dataset specified by project ID and dataset ID.
/// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="ListModelsAsync(DatasetReference, ListModelsOptions)"/>.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="projectId">The ID of the project containing the dataset. Must not be null.</param>
/// <param name="datasetId">The ID of the dataset to list models from. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>An asynchronous sequence of models within the dataset.</returns>
public virtual PagedAsyncEnumerable<ListModelsResponse, BigQueryModel> ListModelsAsync(string projectId, string datasetId, ListModelsOptions options = null) =>
ListModelsAsync(GetDatasetReference(projectId, datasetId), options);
/// <summary>
/// Lists the models in a dataset specified by dataset ID, where the dataset is in this client's project.
/// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="ListModelsAsync(DatasetReference, ListModelsOptions)"/>.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="datasetId">The ID of the dataset to list models from. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>An asynchronous sequence of models within the dataset.</returns>
public virtual PagedAsyncEnumerable<ListModelsResponse, BigQueryModel> ListModelsAsync(string datasetId, ListModelsOptions options = null) =>
ListModelsAsync(GetDatasetReference(datasetId), options);
/// <summary>
/// Lists the models in a dataset.
/// </summary>
/// <remarks>
/// <para>
/// The returned models will not have all the properties in the resource populated. For complete information, make a GetModel
/// call for each model you need the details of.
/// </para>
/// <para>
/// No network requests are made until the returned sequence is enumerated.
/// This means that any exception due to an invalid request will be deferred until that time. Callers should be prepared
/// for exceptions to be thrown while enumerating the results. In addition to failures due to invalid requests, network
/// or service failures can cause exceptions even after the first results have been returned.
/// </para>
/// </remarks>
/// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param>
/// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param>
/// <returns>A sequence of models within the dataset.</returns>
public virtual PagedAsyncEnumerable<ListModelsResponse, BigQueryModel> ListModelsAsync(DatasetReference datasetReference, ListModelsOptions options = null)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
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.
*/
namespace Trizbort
{
partial class ConnectionPropertiesDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectionPropertiesDialog));
this.m_cancelButton = new System.Windows.Forms.Button();
this.m_okButton = new System.Windows.Forms.Button();
this.m_oneWayCheckBox = new System.Windows.Forms.CheckBox();
this.m_dottedCheckBox = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.m_endLabel = new System.Windows.Forms.Label();
this.m_endTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.m_middleTextBox = new System.Windows.Forms.TextBox();
this.m_startTextBox = new System.Windows.Forms.TextBox();
this.m_customRadioButton = new System.Windows.Forms.RadioButton();
this.m_oiRadioButton = new System.Windows.Forms.RadioButton();
this.m_ioRadioButton = new System.Windows.Forms.RadioButton();
this.m_duRadioButton = new System.Windows.Forms.RadioButton();
this.m_udRadioButton = new System.Windows.Forms.RadioButton();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// m_cancelButton
//
this.m_cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_cancelButton.Location = new System.Drawing.Point(348, 208);
this.m_cancelButton.Name = "m_cancelButton";
this.m_cancelButton.Size = new System.Drawing.Size(75, 23);
this.m_cancelButton.TabIndex = 3;
this.m_cancelButton.Text = "Cancel";
this.m_cancelButton.UseVisualStyleBackColor = true;
//
// m_okButton
//
this.m_okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.m_okButton.Location = new System.Drawing.Point(267, 208);
this.m_okButton.Name = "m_okButton";
this.m_okButton.Size = new System.Drawing.Size(75, 23);
this.m_okButton.TabIndex = 2;
this.m_okButton.Text = "OK";
this.m_okButton.UseVisualStyleBackColor = true;
//
// m_oneWayCheckBox
//
this.m_oneWayCheckBox.AutoSize = true;
this.m_oneWayCheckBox.Location = new System.Drawing.Point(9, 44);
this.m_oneWayCheckBox.Name = "m_oneWayCheckBox";
this.m_oneWayCheckBox.Size = new System.Drawing.Size(103, 17);
this.m_oneWayCheckBox.TabIndex = 1;
this.m_oneWayCheckBox.Text = "One Way &Arrow";
this.m_oneWayCheckBox.UseVisualStyleBackColor = true;
//
// m_dottedCheckBox
//
this.m_dottedCheckBox.AutoSize = true;
this.m_dottedCheckBox.Location = new System.Drawing.Point(10, 21);
this.m_dottedCheckBox.Name = "m_dottedCheckBox";
this.m_dottedCheckBox.Size = new System.Drawing.Size(59, 17);
this.m_dottedCheckBox.TabIndex = 0;
this.m_dottedCheckBox.Text = "&Dotted";
this.m_dottedCheckBox.UseVisualStyleBackColor = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.m_endLabel);
this.groupBox1.Controls.Add(this.m_endTextBox);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.m_middleTextBox);
this.groupBox1.Controls.Add(this.m_startTextBox);
this.groupBox1.Controls.Add(this.m_customRadioButton);
this.groupBox1.Controls.Add(this.m_oiRadioButton);
this.groupBox1.Controls.Add(this.m_ioRadioButton);
this.groupBox1.Controls.Add(this.m_duRadioButton);
this.groupBox1.Controls.Add(this.m_udRadioButton);
this.groupBox1.Location = new System.Drawing.Point(12, 90);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(411, 106);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "&Text";
//
// m_endLabel
//
this.m_endLabel.AutoSize = true;
this.m_endLabel.Location = new System.Drawing.Point(213, 72);
this.m_endLabel.Name = "m_endLabel";
this.m_endLabel.Size = new System.Drawing.Size(25, 13);
this.m_endLabel.TabIndex = 9;
this.m_endLabel.Text = "&End";
//
// m_endTextBox
//
this.m_endTextBox.Location = new System.Drawing.Point(245, 69);
this.m_endTextBox.Name = "m_endTextBox";
this.m_endTextBox.Size = new System.Drawing.Size(156, 21);
this.m_endTextBox.TabIndex = 10;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(201, 46);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(37, 13);
this.label2.TabIndex = 7;
this.label2.Text = "&Middle";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(210, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(31, 13);
this.label1.TabIndex = 5;
this.label1.Text = "&Start";
//
// m_middleTextBox
//
this.m_middleTextBox.Location = new System.Drawing.Point(245, 43);
this.m_middleTextBox.Name = "m_middleTextBox";
this.m_middleTextBox.Size = new System.Drawing.Size(156, 21);
this.m_middleTextBox.TabIndex = 8;
//
// m_startTextBox
//
this.m_startTextBox.Location = new System.Drawing.Point(245, 17);
this.m_startTextBox.Name = "m_startTextBox";
this.m_startTextBox.Size = new System.Drawing.Size(156, 21);
this.m_startTextBox.TabIndex = 6;
//
// m_customRadioButton
//
this.m_customRadioButton.AutoSize = true;
this.m_customRadioButton.Checked = true;
this.m_customRadioButton.Location = new System.Drawing.Point(9, 70);
this.m_customRadioButton.Name = "m_customRadioButton";
this.m_customRadioButton.Size = new System.Drawing.Size(61, 17);
this.m_customRadioButton.TabIndex = 4;
this.m_customRadioButton.TabStop = true;
this.m_customRadioButton.Text = "&Custom";
this.m_customRadioButton.UseVisualStyleBackColor = true;
this.m_customRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged);
//
// m_oiRadioButton
//
this.m_oiRadioButton.AutoSize = true;
this.m_oiRadioButton.Location = new System.Drawing.Point(95, 44);
this.m_oiRadioButton.Name = "m_oiRadioButton";
this.m_oiRadioButton.Size = new System.Drawing.Size(57, 17);
this.m_oiRadioButton.TabIndex = 3;
this.m_oiRadioButton.Text = "&Out/In";
this.m_oiRadioButton.UseVisualStyleBackColor = true;
this.m_oiRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged);
//
// m_ioRadioButton
//
this.m_ioRadioButton.AutoSize = true;
this.m_ioRadioButton.Location = new System.Drawing.Point(95, 18);
this.m_ioRadioButton.Name = "m_ioRadioButton";
this.m_ioRadioButton.Size = new System.Drawing.Size(57, 17);
this.m_ioRadioButton.TabIndex = 2;
this.m_ioRadioButton.Text = "&In/Out";
this.m_ioRadioButton.UseVisualStyleBackColor = true;
this.m_ioRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged);
//
// m_duRadioButton
//
this.m_duRadioButton.AutoSize = true;
this.m_duRadioButton.Location = new System.Drawing.Point(9, 44);
this.m_duRadioButton.Name = "m_duRadioButton";
this.m_duRadioButton.Size = new System.Drawing.Size(69, 17);
this.m_duRadioButton.TabIndex = 1;
this.m_duRadioButton.Text = "&Down/Up";
this.m_duRadioButton.UseVisualStyleBackColor = true;
this.m_duRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged);
//
// m_udRadioButton
//
this.m_udRadioButton.AutoSize = true;
this.m_udRadioButton.Location = new System.Drawing.Point(9, 18);
this.m_udRadioButton.Name = "m_udRadioButton";
this.m_udRadioButton.Size = new System.Drawing.Size(69, 17);
this.m_udRadioButton.TabIndex = 0;
this.m_udRadioButton.Text = "&Up/Down";
this.m_udRadioButton.UseVisualStyleBackColor = true;
this.m_udRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonCheckedChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.m_oneWayCheckBox);
this.groupBox2.Controls.Add(this.m_dottedCheckBox);
this.groupBox2.Location = new System.Drawing.Point(12, 10);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(411, 72);
this.groupBox2.TabIndex = 0;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "&Style";
//
// ConnectionPropertiesDialog
//
this.AcceptButton = this.m_okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.m_cancelButton;
this.ClientSize = new System.Drawing.Size(435, 243);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.m_cancelButton);
this.Controls.Add(this.m_okButton);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ConnectionPropertiesDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Connection Properties";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button m_cancelButton;
private System.Windows.Forms.Button m_okButton;
private System.Windows.Forms.CheckBox m_oneWayCheckBox;
private System.Windows.Forms.CheckBox m_dottedCheckBox;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton m_customRadioButton;
private System.Windows.Forms.RadioButton m_oiRadioButton;
private System.Windows.Forms.RadioButton m_ioRadioButton;
private System.Windows.Forms.RadioButton m_duRadioButton;
private System.Windows.Forms.RadioButton m_udRadioButton;
private System.Windows.Forms.Label m_endLabel;
private System.Windows.Forms.TextBox m_endTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox m_middleTextBox;
private System.Windows.Forms.TextBox m_startTextBox;
private System.Windows.Forms.GroupBox groupBox2;
}
}
| |
using System;
using System.Collections;
using System.Xml.Serialization;
namespace Data.Scans
{
/// <summary>
/// A scan point is a single point in a scan. It might have
/// more than one Shot (perhaps because several shots are being
/// taken per shot to improve S:N. The shots are stored in two
/// groups to facilitate switched scans. A scan point also has some
/// analog channel readings associated with it. The scan point keeps
/// a record of the scan parameter.
/// </summary>
[Serializable]
public class ScanPoint : MarshalByRefObject
{
private double scanParameter;
private ArrayList onShots = new ArrayList();
private ArrayList offShots = new ArrayList();
private ArrayList analogs = new ArrayList();
public double gpibval;
public Shot AverageOnShot
{
get { return AverageShots(onShots); }
}
public Shot AverageOffShot
{
get { return AverageShots(offShots); }
}
private Shot AverageShots(ArrayList shots)
{
if (shots.Count == 1) return (Shot)shots[0];
Shot temp = new Shot();
foreach (Shot s in shots) temp += s;
return temp/shots.Count;
}
public double IntegrateOn(int index, double startTime, double endTime)
{
return Integrate(onShots, index, startTime, endTime);
}
public double IntegrateOff(int index, double startTime, double endTime)
{
return Integrate(offShots, index, startTime, endTime);
}
public double VarianceOn(int index, double startTime, double endTime)
{
return Variance(onShots, index, startTime, endTime);
}
public double FractionOfShotNoiseOn(int index, double startTime, double endTime)
{
return FractionOfShotNoise(onShots, index, startTime, endTime);
}
public double FractionOfShotNoiseNormedOn(int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
return FractionOfShotNoiseNormed(onShots, index, startTime0, endTime0,startTime1,endTime1);
}
private double Integrate(ArrayList shots, int index, double startTime, double endTime)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Integrate(index, startTime, endTime);
return temp/shots.Count;
}
private double IntegrateNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1);
return temp / shots.Count;
}
private double Variance(ArrayList shots, int index, double startTime, double endTime)
{
double tempMn = 0;
double tempx2 = 0;
double vari = 0;
double n = shots.Count;
if (n==1)
{
return vari;
}
else
{
foreach (Shot s in shots) tempMn += s.Integrate(index, startTime, endTime);
foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index, startTime, endTime),2);
return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2));
}
}
private double VarianceNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double tempMn = 0;
double tempx2 = 0;
double vari = 0;
double n = shots.Count;
if (n == 1)
{
return vari;
}
else
{
foreach (Shot s in shots) tempMn += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1);
foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1), 2);
return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2));
}
}
private double Calibration(ArrayList shots, int index)
{
Shot s = (Shot)shots[0];
return s.Calibration(index);
}
private double FractionOfShotNoise(ArrayList shots, int index, double startTime, double endTime)
{
return Math.Pow(Variance(shots, index, startTime, endTime)/(Integrate(shots, index, startTime, endTime)*Calibration(shots, index)),0.5);
}
private double FractionOfShotNoiseNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1)
{
double fracNoiseTN = Math.Pow(VarianceNormed(shots, index, startTime0, endTime0, startTime1, endTime1),0.5) / IntegrateNormed(shots, index, startTime0, endTime0, startTime1, endTime1);
double fracNoiseT2 = Calibration(shots, index[0]) / Integrate(shots, index[0], startTime0, endTime0);
double fracNoiseN2 = Calibration(shots, index[1]) / Integrate(shots, index[1], startTime1, endTime1);
return fracNoiseTN / Math.Pow(fracNoiseT2 + fracNoiseN2, 0.5);
}
public double MeanOn(int index)
{
return Mean(onShots, index);
}
public double MeanOff(int index)
{
return Mean(offShots, index);
}
private double Mean(ArrayList shots, int index)
{
double temp = 0;
foreach (Shot s in shots) temp += s.Mean(index);
return temp / shots.Count;
}
public static ScanPoint operator +(ScanPoint p1, ScanPoint p2)
{
if (p1.OnShots.Count == p2.OnShots.Count
&& p1.OffShots.Count == p2.OffShots.Count
&& p1.Analogs.Count == p2.Analogs.Count)
{
ScanPoint temp = new ScanPoint();
temp.ScanParameter = p1.ScanParameter;
for (int i = 0 ; i < p1.OnShots.Count ; i++)
temp.OnShots.Add((Shot)p1.OnShots[i] + (Shot)p2.OnShots[i]);
for (int i = 0 ; i < p1.OffShots.Count ; i++)
temp.OffShots.Add((Shot)p1.OffShots[i] + (Shot)p2.OffShots[i]);
for (int i = 0 ; i < p1.Analogs.Count ; i++)
temp.Analogs.Add((double)p1.Analogs[i] + (double)p2.Analogs[i]);
return temp;
}
else
{
if (p1.OnShots.Count == 0) return p2;
if (p2.OnShots.Count == 0) return p1;
return null;
}
}
public static ScanPoint operator /(ScanPoint p, int n)
{
ScanPoint temp = new ScanPoint();
temp.ScanParameter = p.ScanParameter;
foreach (Shot s in p.OnShots) temp.OnShots.Add(s/n);
foreach (Shot s in p.OffShots) temp.OffShots.Add(s/n);
foreach (double a in p.Analogs) temp.Analogs.Add(a/n);
return temp;
}
public double ScanParameter
{
get { return scanParameter; }
set { scanParameter = value; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(Shot))]
public ArrayList OnShots
{
get { return onShots; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(Shot))]
public ArrayList OffShots
{
get { return offShots; }
}
[XmlArray]
[XmlArrayItem(Type = typeof(double))]
public ArrayList Analogs
{
get { return analogs; }
}
public double GPIBval
{
get { return gpibval; }
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Xml;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Multiverse.Network;
namespace Multiverse.Test {
public class WorldEntry {
public string worldId;
public string worldName;
public bool isDefault;
public WorldEntry(string id, string name, bool def) {
worldId = id;
worldName = name;
isDefault = def;
}
}
/// <summary>
/// This class is made available to the browser control.
/// </summary>
public class LoginHelper {
LoginSettings loginSettings;
NetworkHelper networkHelper;
string username = string.Empty;
string password = string.Empty;
string statusText = string.Empty;
string errorText = string.Empty;
string worldId = string.Empty;
bool rememberUsername = false;
bool fullScan = false;
string preferredWorldId = string.Empty;
List<WorldEntry> worldEntries = new List<WorldEntry>();
public LoginHelper(LoginSettings loginSettings, NetworkHelper networkHelper) {
this.loginSettings = loginSettings;
this.networkHelper = networkHelper;
if (loginSettings.worldId != string.Empty)
preferredWorldId = loginSettings.worldId;
}
public void ReloadSettings() {
ParseConfig("../Config/login_settings.xml");
}
public void LoginMaster(string worldId) {
// MessageBox.Show(string.Format("In Login: {0}:{1} => {2} {3}", username, password, worldId, remember));
Trace.TraceInformation("LoginButton_Click");
loginSettings.username = username;
loginSettings.password = password;
loginSettings.worldId = worldId;
StatusMessage = "Connecting ...";
NetworkHelperStatus rv = networkHelper.LoginMaster(loginSettings);
System.Diagnostics.Trace.TraceInformation("Login return: " + rv);
switch (rv) {
case NetworkHelperStatus.WorldResolveSuccess:
System.Diagnostics.Trace.TraceInformation("Success: " + rv);
break;
case NetworkHelperStatus.WorldResolveFailure:
StatusMessage = "";
ErrorMessage = "Unable to resolve world id";
break;
case NetworkHelperStatus.LoginFailure:
StatusMessage = "";
ErrorMessage = "Invalid username or password";
break;
case NetworkHelperStatus.MasterTcpConnectFailure:
case NetworkHelperStatus.MasterConnectFailure:
StatusMessage = "";
ErrorMessage = "Unable to connect to master server";
break;
default:
StatusMessage = "";
ErrorMessage = "Unable to login";
break;
}
}
/// <summary>
/// Get the number of worlds that are locally defined (either from
/// something akin to a quicklist, or passed on the command line).
/// </summary>
/// <returns></returns>
public int GetWorldCount()
{
return worldEntries.Count;
}
/// <summary>
/// Get the world entry at a given index
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public WorldEntry GetWorldEntry(int index)
{
return worldEntries[index];
}
/// <summary>
/// This is used so that the client can pass in a preferred world
/// with a flag like --world_id and we can select the associated option
/// from the script in the login page.
/// </summary>
/// <returns>the preferred world id if it has been set, or the empty string if it has not</returns>
public string GetPreferredWorld() {
return preferredWorldId;
}
internal void ParseConfig(string configFile) {
worldEntries.Clear();
worldId = string.Empty;
password = string.Empty;
username = string.Empty;
try {
Stream stream = File.OpenRead(configFile);
try {
XmlDocument document = new XmlDocument();
document.Load(stream);
foreach (XmlNode childNode in document.ChildNodes) {
switch (childNode.Name) {
case "LoginSettings":
ReadLoginSettings(childNode);
break;
default:
DebugMessage(childNode);
break;
}
}
} finally {
stream.Close();
}
} catch (Exception e) {
Trace.TraceInformation("Unable to load login settings: " + e);
}
}
protected void ReadLoginSettings(XmlNode node) {
foreach (XmlNode childNode in node.ChildNodes) {
switch (childNode.Name) {
case "accounts":
ReadAccounts(childNode);
break;
case "worlds":
ReadWorlds(childNode);
break;
default:
DebugMessage(childNode);
break;
}
}
}
protected void ReadAccounts(XmlNode node) {
foreach (XmlNode childNode in node.ChildNodes) {
switch (childNode.Name) {
case "account":
ReadAccount(childNode);
break;
default:
DebugMessage(childNode);
break;
}
}
#if OLD_SCHOOL
if (this.Username == "" && usernameComboBox.Items.Count > 0)
this.Username = (string)usernameComboBox.Items[0];
#endif
}
protected void ReadWorlds(XmlNode node) {
foreach (XmlNode childNode in node.ChildNodes) {
switch (childNode.Name) {
case "world":
ReadWorld(childNode);
break;
default:
DebugMessage(childNode);
break;
}
}
}
protected void ReadAccount(XmlNode node) {
bool isDefault = false;
foreach (XmlAttribute attr in node.Attributes) {
switch (attr.Name) {
case "username":
username = attr.Value;
// TODO: implement me
// usernameComboBox.Items.Add(username);
break;
case "password":
password = attr.Value;
// TODO: implement me
//if (!passwordSet) {
// passwordTextBox.Text = password;
// passwordSet = true;
//}
break;
case "default":
isDefault = bool.Parse(attr.Value);
break;
default:
DebugMessage(node, attr);
break;
}
}
#if OLD_SCHOOL
if (isDefault) {
this.Username = username;
this.passwordTextBox.Text = password;
}
#endif
}
protected void ReadWorld(XmlNode node) {
bool isDefault = false;
string worldName = string.Empty;
string worldId = string.Empty;
foreach (XmlAttribute attr in node.Attributes) {
switch (attr.Name) {
case "name":
worldName = attr.Value;
break;
case "id":
worldId = attr.Value;
break;
case "default":
isDefault = bool.Parse(attr.Value);
break;
default:
DebugMessage(node, attr);
break;
}
}
worldEntries.Add(new WorldEntry(worldId, worldName, isDefault));
}
protected void DebugMessage(XmlNode node) {
Trace.WriteLine("Unhandled node type: " + node.Name +
" with parent of " + node.ParentNode.Name);
}
protected void DebugMessage(XmlNode node, XmlAttribute attr) {
Trace.WriteLine("Unhandled node attribute: " + attr.Name +
" with parent node of " + node.Name);
}
public string Username {
get {
return username;
}
set {
username = value;
}
}
public string Password {
get {
return password;
}
set {
password = value;
}
}
public string StatusMessage {
get {
return statusText;
}
set {
statusText = value;
}
}
public string ErrorMessage {
get {
return errorText;
}
set {
errorText = value;
}
}
public bool FullScan {
get {
return fullScan;
}
set {
fullScan = value;
}
}
public bool RememberUsername {
get {
return rememberUsername;
}
set {
rememberUsername = value;
}
}
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
I implemented this algorithm with reference to following products though the algorithm is known publicly.
* MindTerm ( AppGate Network Security )
$Id: DES.cs,v 1.2 2005/04/20 08:58:56 okajima Exp $
*/
using System;
namespace Granados.Crypto
{
public class DES
{
private const int BLOCK_SIZE = 8; // bytes in a data-block
uint[] _key;
byte[] _iv;
byte[] _temp;
public DES() {
_key = new uint[32];
_iv = new byte[8];
_temp = new byte[8];
}
public void SetIV(byte[] newiv) {
Array.Copy(newiv, 0, _iv, 0, _iv.Length);
}
public void SetIV(byte[] newiv, int offset) {
Array.Copy(newiv, offset, _iv, 0, _iv.Length);
}
public void InitializeKey(byte[] key, int offset)
{
uint i, c, d, t, s, shifts;
c = CipherUtil.GetIntLE(key, offset+0);
d = CipherUtil.GetIntLE(key, offset+4);
t = ((d >> 4) ^ c) & 0x0f0f0f0f;
c ^= t;
d ^= t << 4;
t = (((c << (16 - (-2))) ^ c) & 0xcccc0000);
c = c ^ t ^ (t >> (16 - (-2)));
t = (((d << (16 - (-2))) ^ d) & 0xcccc0000);
d = d ^ t ^ (t >> (16 - (-2)));
t = ((d >> 1) ^ c) & 0x55555555;
c ^= t;
d ^= t << 1;
t = ((c >> 8) ^ d) & 0x00ff00ff;
d ^= t;
c ^= t << 8;
t = ((d >> 1) ^ c) & 0x55555555;
c ^= t;
d ^= t << 1;
d = ((d & 0xff) << 16) | (d & 0xff00) |
((d >> 16) & 0xff) | ((c >> 4) & 0xf000000);
c &= 0x0fffffff;
shifts = 0x7efc;
for(i = 0; i < 16; i++) {
if((shifts & 1) != 0) {
c = ((c >> 2) | (c << 26));
d = ((d >> 2) | (d << 26));
} else {
c = ((c >> 1) | (c << 27));
d = ((d >> 1) | (d << 27));
}
shifts >>= 1;
c &= 0x0fffffff;
d &= 0x0fffffff;
s = SKB[0, (c) & 0x3f] |
SKB[1, ((c >> 6 ) & 0x03)|((c >> 7 ) & 0x3c)] |
SKB[2, ((c >> 13) & 0x0f)|((c >> 14) & 0x30)] |
SKB[3, ((c >> 20) & 0x01)|((c >> 21) & 0x06) | ((c >> 22) & 0x38)];
t = SKB[4, (d) & 0x3f] |
SKB[5, ((d >> 7 ) & 0x03) | ((d >> 8 ) & 0x3c)] |
SKB[6, (d >> 15) & 0x3f ] |
SKB[7, ((d >> 21) & 0x0f) | ((d >> 22) & 0x30)];
_key[i * 2] = ((t << 16) | (s & 0xffff));
s = ((s >> 16) | (t & 0xffff0000));
_key[(i * 2) + 1] = (s << 4) | (s >> 28);
}
}
public void BlockEncrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint t;
int i;
uint[] lr = new uint[2];
lr[0] = CipherUtil.GetIntLE(input, inOffset);
lr[1] = CipherUtil.GetIntLE(input, inOffset + 4);
initPerm(lr);
t = (lr[1] << 1) | (lr[1] >> 31);
lr[1] = (lr[0] << 1) | (lr[0] >> 31);
lr[0] = t;
for (i = 0; i < 32; i += 4) {
desCipher1(lr, i);
desCipher2(lr, i + 2);
}
lr[0] = (lr[0] >> 1) | (lr[0] << 31);
lr[1] = (lr[1] >> 1) | (lr[1] << 31);
finalPerm(lr);
CipherUtil.PutIntLE(lr[0], output, outOffset);
CipherUtil.PutIntLE(lr[1], output, outOffset + 4);
}
public void BlockDecrypt(byte[] input, int inOffset, byte[] output, int outOffset) {
uint t;
int i;
uint[] lr = new uint[2];
lr[0] = CipherUtil.GetIntLE(input, inOffset);
lr[1] = CipherUtil.GetIntLE(input, inOffset + 4);
initPerm(lr);
t = (lr[1] << 1) | (lr[1] >> 31);
lr[1] = (lr[0] << 1) | (lr[0] >> 31);
lr[0] = t;
for (i = 30; i > 0; i -= 4) {
desCipher1(lr, i);
desCipher2(lr, i - 2);
}
lr[0] = (lr[0] >> 1) | (lr[0] << 31);
lr[1] = (lr[1] >> 1) | (lr[1] << 31);
finalPerm(lr);
CipherUtil.PutIntLE(lr[0], output, outOffset);
CipherUtil.PutIntLE(lr[1], output, outOffset + 4);
}
private void desCipher1(uint[] lr, int i) {
uint u = lr[1] ^ _key[i ];
uint t = lr[1] ^ _key[i + 1];
t = ((t >> 4) + (t << 28));
lr[0] ^= (SPTRANS[1, (t ) & 0x3f] |
SPTRANS[3, (t >> 8 ) & 0x3f] |
SPTRANS[5, (t >> 16) & 0x3f] |
SPTRANS[7, (t >> 24) & 0x3f] |
SPTRANS[0, (u ) & 0x3f] |
SPTRANS[2, (u >> 8 ) & 0x3f] |
SPTRANS[4, (u >> 16) & 0x3f] |
SPTRANS[6, (u >> 24) & 0x3f]);
}
private void desCipher2(uint[] lr, int i) {
uint u = lr[0] ^ _key[i ];
uint t = lr[0] ^ _key[i + 1];
t = ((t >> 4) + (t << 28));
lr[1] ^= (SPTRANS[1, (t ) & 0x3f] |
SPTRANS[3, (t >> 8 ) & 0x3f] |
SPTRANS[5, (t >> 16) & 0x3f] |
SPTRANS[7, (t >> 24) & 0x3f] |
SPTRANS[0, (u ) & 0x3f] |
SPTRANS[2, (u >> 8 ) & 0x3f] |
SPTRANS[4, (u >> 16) & 0x3f] |
SPTRANS[6, (u >> 24) & 0x3f]);
}
private static void initPerm(uint[] lr) {
uint t = ((lr[1] >> 4) ^ lr[0]) & 0x0f0f0f0f;
lr[0] ^= t;
lr[1] ^= t << 4;
t = ((lr[0] >> 16) ^ lr[1]) & 0x0000ffff;
lr[1] ^= t;
lr[0] ^= t << 16;
t = ((lr[1] >> 2) ^ lr[0]) & 0x33333333;
lr[0] ^= t;
lr[1] ^= t << 2;
t = ((lr[0] >> 8) ^ lr[1]) & 0x00ff00ff;
lr[1] ^= t;
lr[0] ^= t << 8;
t = ((lr[1] >> 1) ^ lr[0]) & 0x55555555;
lr[0] ^= t;
lr[1] ^= t << 1;
}
private static void finalPerm(uint[] lr) {
uint t = ((lr[1] >> 1) ^ lr[0]) & 0x55555555;
lr[0] ^= t;
lr[1] ^= t << 1;
t = ((lr[0] >> 8) ^ lr[1]) & 0x00ff00ff;
lr[1] ^= t;
lr[0] ^= t << 8;
t = ((lr[1] >> 2) ^ lr[0]) & 0x33333333;
lr[0] ^= t;
lr[1] ^= t << 2;
t = ((lr[0] >> 16) ^ lr[1]) & 0x0000ffff;
lr[1] ^= t;
lr[0] ^= t << 16;
t = ((lr[1] >> 4) ^ lr[0]) & 0x0f0f0f0f;
lr[0] ^= t;
lr[1] ^= t << 4;
}
public void EncryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
int nBlocks = inputLen / 8;
for(int bc = 0; bc < nBlocks; bc++) {
CipherUtil.BlockXor(input, inputOffset, 8, _iv, 0);
BlockEncrypt(_iv, 0, output, outputOffset);
Array.Copy(output, outputOffset, _iv, 0, 8);
inputOffset += 8;
outputOffset += 8;
}
}
public void DecryptCBC(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) {
int nBlocks = inputLen / 8;
for(int bc = 0; bc < nBlocks; bc++) {
BlockDecrypt(input, inputOffset, _temp, 0);
for(int i = 0; i < 8; i++) {
_temp[i] ^= _iv[i];
_iv[i] = input[inputOffset + i];
output[outputOffset + i] = _temp[i];
}
inputOffset += 8;
outputOffset += 8;
}
}
/*
* Copyright (C) 1993 Eric Young
*/
private static readonly uint[,] SKB = new uint[,] {
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
{ 0x00000000,0x00000010,0x20000000,0x20000010,
0x00010000,0x00010010,0x20010000,0x20010010,
0x00000800,0x00000810,0x20000800,0x20000810,
0x00010800,0x00010810,0x20010800,0x20010810,
0x00000020,0x00000030,0x20000020,0x20000030,
0x00010020,0x00010030,0x20010020,0x20010030,
0x00000820,0x00000830,0x20000820,0x20000830,
0x00010820,0x00010830,0x20010820,0x20010830,
0x00080000,0x00080010,0x20080000,0x20080010,
0x00090000,0x00090010,0x20090000,0x20090010,
0x00080800,0x00080810,0x20080800,0x20080810,
0x00090800,0x00090810,0x20090800,0x20090810,
0x00080020,0x00080030,0x20080020,0x20080030,
0x00090020,0x00090030,0x20090020,0x20090030,
0x00080820,0x00080830,0x20080820,0x20080830,
0x00090820,0x00090830,0x20090820,0x20090830 },
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
{ 0x00000000,0x02000000,0x00002000,0x02002000,
0x00200000,0x02200000,0x00202000,0x02202000,
0x00000004,0x02000004,0x00002004,0x02002004,
0x00200004,0x02200004,0x00202004,0x02202004,
0x00000400,0x02000400,0x00002400,0x02002400,
0x00200400,0x02200400,0x00202400,0x02202400,
0x00000404,0x02000404,0x00002404,0x02002404,
0x00200404,0x02200404,0x00202404,0x02202404,
0x10000000,0x12000000,0x10002000,0x12002000,
0x10200000,0x12200000,0x10202000,0x12202000,
0x10000004,0x12000004,0x10002004,0x12002004,
0x10200004,0x12200004,0x10202004,0x12202004,
0x10000400,0x12000400,0x10002400,0x12002400,
0x10200400,0x12200400,0x10202400,0x12202400,
0x10000404,0x12000404,0x10002404,0x12002404,
0x10200404,0x12200404,0x10202404,0x12202404 },
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
{ 0x00000000,0x00000001,0x00040000,0x00040001,
0x01000000,0x01000001,0x01040000,0x01040001,
0x00000002,0x00000003,0x00040002,0x00040003,
0x01000002,0x01000003,0x01040002,0x01040003,
0x00000200,0x00000201,0x00040200,0x00040201,
0x01000200,0x01000201,0x01040200,0x01040201,
0x00000202,0x00000203,0x00040202,0x00040203,
0x01000202,0x01000203,0x01040202,0x01040203,
0x08000000,0x08000001,0x08040000,0x08040001,
0x09000000,0x09000001,0x09040000,0x09040001,
0x08000002,0x08000003,0x08040002,0x08040003,
0x09000002,0x09000003,0x09040002,0x09040003,
0x08000200,0x08000201,0x08040200,0x08040201,
0x09000200,0x09000201,0x09040200,0x09040201,
0x08000202,0x08000203,0x08040202,0x08040203,
0x09000202,0x09000203,0x09040202,0x09040203 },
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
{ 0x00000000,0x00100000,0x00000100,0x00100100,
0x00000008,0x00100008,0x00000108,0x00100108,
0x00001000,0x00101000,0x00001100,0x00101100,
0x00001008,0x00101008,0x00001108,0x00101108,
0x04000000,0x04100000,0x04000100,0x04100100,
0x04000008,0x04100008,0x04000108,0x04100108,
0x04001000,0x04101000,0x04001100,0x04101100,
0x04001008,0x04101008,0x04001108,0x04101108,
0x00020000,0x00120000,0x00020100,0x00120100,
0x00020008,0x00120008,0x00020108,0x00120108,
0x00021000,0x00121000,0x00021100,0x00121100,
0x00021008,0x00121008,0x00021108,0x00121108,
0x04020000,0x04120000,0x04020100,0x04120100,
0x04020008,0x04120008,0x04020108,0x04120108,
0x04021000,0x04121000,0x04021100,0x04121100,
0x04021008,0x04121008,0x04021108,0x04121108 },
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
{ 0x00000000,0x10000000,0x00010000,0x10010000,
0x00000004,0x10000004,0x00010004,0x10010004,
0x20000000,0x30000000,0x20010000,0x30010000,
0x20000004,0x30000004,0x20010004,0x30010004,
0x00100000,0x10100000,0x00110000,0x10110000,
0x00100004,0x10100004,0x00110004,0x10110004,
0x20100000,0x30100000,0x20110000,0x30110000,
0x20100004,0x30100004,0x20110004,0x30110004,
0x00001000,0x10001000,0x00011000,0x10011000,
0x00001004,0x10001004,0x00011004,0x10011004,
0x20001000,0x30001000,0x20011000,0x30011000,
0x20001004,0x30001004,0x20011004,0x30011004,
0x00101000,0x10101000,0x00111000,0x10111000,
0x00101004,0x10101004,0x00111004,0x10111004,
0x20101000,0x30101000,0x20111000,0x30111000,
0x20101004,0x30101004,0x20111004,0x30111004 },
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
{ 0x00000000,0x08000000,0x00000008,0x08000008,
0x00000400,0x08000400,0x00000408,0x08000408,
0x00020000,0x08020000,0x00020008,0x08020008,
0x00020400,0x08020400,0x00020408,0x08020408,
0x00000001,0x08000001,0x00000009,0x08000009,
0x00000401,0x08000401,0x00000409,0x08000409,
0x00020001,0x08020001,0x00020009,0x08020009,
0x00020401,0x08020401,0x00020409,0x08020409,
0x02000000,0x0A000000,0x02000008,0x0A000008,
0x02000400,0x0A000400,0x02000408,0x0A000408,
0x02020000,0x0A020000,0x02020008,0x0A020008,
0x02020400,0x0A020400,0x02020408,0x0A020408,
0x02000001,0x0A000001,0x02000009,0x0A000009,
0x02000401,0x0A000401,0x02000409,0x0A000409,
0x02020001,0x0A020001,0x02020009,0x0A020009,
0x02020401,0x0A020401,0x02020409,0x0A020409 },
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
{ 0x00000000,0x00000100,0x00080000,0x00080100,
0x01000000,0x01000100,0x01080000,0x01080100,
0x00000010,0x00000110,0x00080010,0x00080110,
0x01000010,0x01000110,0x01080010,0x01080110,
0x00200000,0x00200100,0x00280000,0x00280100,
0x01200000,0x01200100,0x01280000,0x01280100,
0x00200010,0x00200110,0x00280010,0x00280110,
0x01200010,0x01200110,0x01280010,0x01280110,
0x00000200,0x00000300,0x00080200,0x00080300,
0x01000200,0x01000300,0x01080200,0x01080300,
0x00000210,0x00000310,0x00080210,0x00080310,
0x01000210,0x01000310,0x01080210,0x01080310,
0x00200200,0x00200300,0x00280200,0x00280300,
0x01200200,0x01200300,0x01280200,0x01280300,
0x00200210,0x00200310,0x00280210,0x00280310,
0x01200210,0x01200310,0x01280210,0x01280310 },
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
{ 0x00000000,0x04000000,0x00040000,0x04040000,
0x00000002,0x04000002,0x00040002,0x04040002,
0x00002000,0x04002000,0x00042000,0x04042000,
0x00002002,0x04002002,0x00042002,0x04042002,
0x00000020,0x04000020,0x00040020,0x04040020,
0x00000022,0x04000022,0x00040022,0x04040022,
0x00002020,0x04002020,0x00042020,0x04042020,
0x00002022,0x04002022,0x00042022,0x04042022,
0x00000800,0x04000800,0x00040800,0x04040800,
0x00000802,0x04000802,0x00040802,0x04040802,
0x00002800,0x04002800,0x00042800,0x04042800,
0x00002802,0x04002802,0x00042802,0x04042802,
0x00000820,0x04000820,0x00040820,0x04040820,
0x00000822,0x04000822,0x00040822,0x04040822,
0x00002820,0x04002820,0x00042820,0x04042820,
0x00002822,0x04002822,0x00042822,0x04042822 }
};
private static uint[,] SPTRANS = new uint[,] {
/* nibble 0 */
{ 0x00820200, 0x00020000, 0x80800000, 0x80820200,
0x00800000, 0x80020200, 0x80020000, 0x80800000,
0x80020200, 0x00820200, 0x00820000, 0x80000200,
0x80800200, 0x00800000, 0x00000000, 0x80020000,
0x00020000, 0x80000000, 0x00800200, 0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200,
0x80000000, 0x00000200, 0x00020200, 0x80820000,
0x00000200, 0x80800200, 0x80820000, 0x00000000,
0x00000000, 0x80820200, 0x00800200, 0x80020000,
0x00820200, 0x00020000, 0x80000200, 0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000,
0x80020200, 0x80000000, 0x80800000, 0x00820000,
0x80820200, 0x00020200, 0x00820000, 0x80800200,
0x00800000, 0x80000200, 0x80020000, 0x00000000,
0x00020000, 0x00800000, 0x80800200, 0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200 },
/* nibble 1 */
{ 0x10042004, 0x00000000, 0x00042000, 0x10040000,
0x10000004, 0x00002004, 0x10002000, 0x00042000,
0x00002000, 0x10040004, 0x00000004, 0x10002000,
0x00040004, 0x10042000, 0x10040000, 0x00000004,
0x00040000, 0x10002004, 0x10040004, 0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004,
0x10002004, 0x00042004, 0x10042000, 0x10000004,
0x10000000, 0x00040000, 0x00002004, 0x10042004,
0x00040004, 0x10042000, 0x10002000, 0x00042004,
0x10042004, 0x00040004, 0x10000004, 0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004,
0x00002000, 0x10000000, 0x00042004, 0x10002004,
0x10042000, 0x00002000, 0x00000000, 0x10000004,
0x00000004, 0x10042004, 0x00042000, 0x10040000,
0x10040004, 0x00040000, 0x00002004, 0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000 },
/* nibble 2 */
{ 0x41000000, 0x01010040, 0x00000040, 0x41000040,
0x40010000, 0x01000000, 0x41000040, 0x00010040,
0x01000040, 0x00010000, 0x01010000, 0x40000000,
0x41010040, 0x40000040, 0x40000000, 0x41010000,
0x00000000, 0x40010000, 0x01010040, 0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000,
0x41010000, 0x01000040, 0x40010040, 0x01010000,
0x00010040, 0x00000000, 0x01000000, 0x40010040,
0x01010040, 0x00000040, 0x40000000, 0x00010000,
0x40000040, 0x40010000, 0x01010000, 0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000,
0x40010000, 0x01000000, 0x41010040, 0x40000000,
0x40010040, 0x41000000, 0x01000000, 0x41010040,
0x00010000, 0x01000040, 0x41000040, 0x00010040,
0x01000040, 0x00000000, 0x41010000, 0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000 },
/* nibble 3 */
{ 0x00100402, 0x04000400, 0x00000002, 0x04100402,
0x00000000, 0x04100000, 0x04000402, 0x00100002,
0x04100400, 0x04000002, 0x04000000, 0x00000402,
0x04000002, 0x00100402, 0x00100000, 0x04000000,
0x04100002, 0x00100400, 0x00000400, 0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400,
0x00000402, 0x00000000, 0x00100002, 0x04100400,
0x04000400, 0x04100002, 0x04100402, 0x00100000,
0x04100002, 0x00000402, 0x00100000, 0x04000002,
0x00100400, 0x04000400, 0x00000002, 0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002,
0x00000000, 0x04100002, 0x04100400, 0x00000400,
0x04000000, 0x04100402, 0x00100402, 0x00100000,
0x04100402, 0x00000002, 0x04000400, 0x00100402,
0x00100002, 0x00100400, 0x04100000, 0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400 },
/* nibble 4 */
{ 0x02000000, 0x00004000, 0x00000100, 0x02004108,
0x02004008, 0x02000100, 0x00004108, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x00004100,
0x02000108, 0x02004008, 0x02004100, 0x00000000,
0x00004100, 0x02000000, 0x00004008, 0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008,
0x00000008, 0x02000108, 0x02004108, 0x00004008,
0x02004000, 0x00000100, 0x00000108, 0x02004100,
0x02004100, 0x02000108, 0x00004008, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000,
0x00004108, 0x02000000, 0x00000100, 0x00004008,
0x02000108, 0x00000100, 0x00000000, 0x02004108,
0x02004008, 0x02004100, 0x00000108, 0x00004000,
0x00004100, 0x02004008, 0x02000100, 0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008 },
/* nibble 5 */
{ 0x20000010, 0x00080010, 0x00000000, 0x20080800,
0x00080010, 0x00000800, 0x20000810, 0x00080000,
0x00000810, 0x20080810, 0x00080800, 0x20000000,
0x20000800, 0x20000010, 0x20080000, 0x00080810,
0x00080000, 0x20000810, 0x20080010, 0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010,
0x20080810, 0x20080000, 0x20000000, 0x00000810,
0x00000010, 0x00080800, 0x00080810, 0x20000800,
0x00000810, 0x20000000, 0x20000800, 0x00080810,
0x20080800, 0x00080010, 0x00000000, 0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000,
0x00080010, 0x20080810, 0x00080800, 0x00000010,
0x20080810, 0x00080800, 0x00080000, 0x20000810,
0x20000010, 0x20080000, 0x00080810, 0x00000000,
0x00000800, 0x20000010, 0x20000810, 0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010 },
/* nibble 6 */
{ 0x00001000, 0x00000080, 0x00400080, 0x00400001,
0x00401081, 0x00001001, 0x00001080, 0x00000000,
0x00400000, 0x00400081, 0x00000081, 0x00401000,
0x00000001, 0x00401080, 0x00401000, 0x00000081,
0x00400081, 0x00001000, 0x00001001, 0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080,
0x00401001, 0x00001081, 0x00401080, 0x00000001,
0x00001081, 0x00401001, 0x00000080, 0x00400000,
0x00001081, 0x00401000, 0x00401001, 0x00000081,
0x00001000, 0x00000080, 0x00400000, 0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000,
0x00000080, 0x00400001, 0x00000001, 0x00400080,
0x00000000, 0x00400081, 0x00400080, 0x00001080,
0x00000081, 0x00001000, 0x00401081, 0x00400000,
0x00401080, 0x00000001, 0x00001001, 0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001 },
/* nibble 7 */
{ 0x08200020, 0x08208000, 0x00008020, 0x00000000,
0x08008000, 0x00200020, 0x08200000, 0x08208020,
0x00000020, 0x08000000, 0x00208000, 0x00008020,
0x00208020, 0x08008020, 0x08000020, 0x08200000,
0x00008000, 0x00208020, 0x00200020, 0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000,
0x08000000, 0x00200000, 0x08008020, 0x08200020,
0x00200000, 0x00008000, 0x08208000, 0x00000020,
0x00200000, 0x00008000, 0x08000020, 0x08208020,
0x00008020, 0x08000000, 0x00000000, 0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020,
0x08208000, 0x00000020, 0x00200020, 0x08008000,
0x08208020, 0x00200000, 0x08200000, 0x08000020,
0x00208000, 0x00008020, 0x08008020, 0x08200000,
0x00000020, 0x08208000, 0x00208020, 0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020 }
};
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Glx
{
/// <summary>
/// [GLX] Value of GLX_SYNC_FRAME_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_video_resize")]
[Log(BitmaskName = "GLXSyncType")]
public const int SYNC_FRAME_SGIX = 0x00000000;
/// <summary>
/// [GLX] Value of GLX_SYNC_SWAP_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_video_resize")]
[Log(BitmaskName = "GLXSyncType")]
public const int SYNC_SWAP_SGIX = 0x00000001;
/// <summary>
/// [GLX] glXBindChannelToWindowSGIX: Binding for glXBindChannelToWindowSGIX.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="screen">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="channel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="window">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_video_resize")]
public static int BindChannelToWindowSGIX(IntPtr display, int screen, int channel, IntPtr window)
{
int retValue;
Debug.Assert(Delegates.pglXBindChannelToWindowSGIX != null, "pglXBindChannelToWindowSGIX not implemented");
retValue = Delegates.pglXBindChannelToWindowSGIX(display, screen, channel, window);
LogCommand("glXBindChannelToWindowSGIX", retValue, display, screen, channel, window );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXChannelRectSGIX: Binding for glXChannelRectSGIX.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="screen">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="channel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="h">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_video_resize")]
public static int ChannelRectSGIX(IntPtr display, int screen, int channel, int x, int y, int w, int h)
{
int retValue;
Debug.Assert(Delegates.pglXChannelRectSGIX != null, "pglXChannelRectSGIX not implemented");
retValue = Delegates.pglXChannelRectSGIX(display, screen, channel, x, y, w, h);
LogCommand("glXChannelRectSGIX", retValue, display, screen, channel, x, y, w, h );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXQueryChannelRectSGIX: Binding for glXQueryChannelRectSGIX.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="screen">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="channel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dx">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="dy">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="dw">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="dh">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_video_resize")]
public static int QueryChannelRectSGIX(IntPtr display, int screen, int channel, int[] dx, int[] dy, int[] dw, int[] dh)
{
int retValue;
unsafe {
fixed (int* p_dx = dx)
fixed (int* p_dy = dy)
fixed (int* p_dw = dw)
fixed (int* p_dh = dh)
{
Debug.Assert(Delegates.pglXQueryChannelRectSGIX != null, "pglXQueryChannelRectSGIX not implemented");
retValue = Delegates.pglXQueryChannelRectSGIX(display, screen, channel, p_dx, p_dy, p_dw, p_dh);
LogCommand("glXQueryChannelRectSGIX", retValue, display, screen, channel, dx, dy, dw, dh );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXQueryChannelDeltasSGIX: Binding for glXQueryChannelDeltasSGIX.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="screen">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="channel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:int[]"/>.
/// </param>
/// <param name="h">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_video_resize")]
public static int QueryChannelDeltasSGIX(IntPtr display, int screen, int channel, int[] x, int[] y, int[] w, int[] h)
{
int retValue;
unsafe {
fixed (int* p_x = x)
fixed (int* p_y = y)
fixed (int* p_w = w)
fixed (int* p_h = h)
{
Debug.Assert(Delegates.pglXQueryChannelDeltasSGIX != null, "pglXQueryChannelDeltasSGIX not implemented");
retValue = Delegates.pglXQueryChannelDeltasSGIX(display, screen, channel, p_x, p_y, p_w, p_h);
LogCommand("glXQueryChannelDeltasSGIX", retValue, display, screen, channel, x, y, w, h );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXChannelRectSyncSGIX: Binding for glXChannelRectSyncSGIX.
/// </summary>
/// <param name="display">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="screen">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="channel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="synctype">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_video_resize")]
public static int ChannelRectSyncSGIX(IntPtr display, int screen, int channel, int synctype)
{
int retValue;
Debug.Assert(Delegates.pglXChannelRectSyncSGIX != null, "pglXChannelRectSyncSGIX not implemented");
retValue = Delegates.pglXChannelRectSyncSGIX(display, screen, channel, synctype);
LogCommand("glXChannelRectSyncSGIX", retValue, display, screen, channel, synctype );
DebugCheckErrors(retValue);
return (retValue);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GLX_SGIX_video_resize")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXBindChannelToWindowSGIX(IntPtr display, int screen, int channel, IntPtr window);
[RequiredByFeature("GLX_SGIX_video_resize")]
internal static glXBindChannelToWindowSGIX pglXBindChannelToWindowSGIX;
[RequiredByFeature("GLX_SGIX_video_resize")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXChannelRectSGIX(IntPtr display, int screen, int channel, int x, int y, int w, int h);
[RequiredByFeature("GLX_SGIX_video_resize")]
internal static glXChannelRectSGIX pglXChannelRectSGIX;
[RequiredByFeature("GLX_SGIX_video_resize")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXQueryChannelRectSGIX(IntPtr display, int screen, int channel, int* dx, int* dy, int* dw, int* dh);
[RequiredByFeature("GLX_SGIX_video_resize")]
internal static glXQueryChannelRectSGIX pglXQueryChannelRectSGIX;
[RequiredByFeature("GLX_SGIX_video_resize")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXQueryChannelDeltasSGIX(IntPtr display, int screen, int channel, int* x, int* y, int* w, int* h);
[RequiredByFeature("GLX_SGIX_video_resize")]
internal static glXQueryChannelDeltasSGIX pglXQueryChannelDeltasSGIX;
[RequiredByFeature("GLX_SGIX_video_resize")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXChannelRectSyncSGIX(IntPtr display, int screen, int channel, int synctype);
[RequiredByFeature("GLX_SGIX_video_resize")]
internal static glXChannelRectSyncSGIX pglXChannelRectSyncSGIX;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
#if !NETCOREAPP2_0
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
#endif
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static partial class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** Indicates examples tests. */
public const string CategoryExamples = "EXAMPLES_TEST";
/** */
private const int DfltBusywaitSleepInterval = 200;
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms64m",
"-Xmx99m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets the primary keys.
/// </summary>
public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName,
IClusterNode node = null)
{
var aff = ignite.GetAffinity(cacheName);
node = node ?? ignite.GetCluster().GetLocalNode();
return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x));
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
{
return GetPrimaryKeys(ignite, cacheName, node).First();
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
#if !NETCOREAPP2_0
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList();
if (items.Any())
{
Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'",
grid.Name, expectedCount, handleRegistry.Count,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
#endif
}
/// <summary>
/// Serializes and deserializes back an object.
/// </summary>
public static T SerializeDeserialize<T>(T obj)
{
#if NETCOREAPP2_0
var marshType = typeof(IIgnite).Assembly.GetType("Apache.Ignite.Core.Impl.Binary.Marshaller");
var marsh = Activator.CreateInstance(marshType, new object[] { null, null });
marshType.GetProperty("CompactFooter").SetValue(marsh, false);
var bytes = marshType.GetMethod("Marshal").MakeGenericMethod(typeof(object))
.Invoke(marsh, new object[] { obj });
var res = marshType.GetMethods().Single(mi =>
mi.Name == "Unmarshal" && mi.GetParameters().First().ParameterType == typeof(byte[]))
.MakeGenericMethod(typeof(object)).Invoke(marsh, new[] { bytes, 0 });
return (T)res;
#else
var marsh = new Marshaller(null) { CompactFooter = false };
return marsh.Unmarshal<T>(marsh.Marshal(obj));
#endif
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentQueue.cs
//
// A lock-free, concurrent queue primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
//fields of ConcurrentQueue
private volatile Segment _head;
private volatile Segment _tail;
private const int SEGMENT_SIZE = 32;
//number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot.
internal volatile int _numSnapshotTakers = 0;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
_head = _tail = new Segment(0, this);
}
/// <summary>
/// Initializes the contents of the queue from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor
_head = localTail;
int index = 0;
foreach (T element in collection)
{
Debug.Assert(index >= 0 && index < SEGMENT_SIZE);
localTail.UnsafeAdd(element);
index++;
if (index >= SEGMENT_SIZE)
{
localTail = localTail.UnsafeGrow();
index = 0;
}
}
_tail = localTail;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentQueue{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
InitializeFromCollection(collection);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException("array");
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
((ICollection)ToList()).CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
// Gets a value indicating whether access to this collection is synchronized. Always returns
// false. The reason is subtle. While access is in face thread safe, it's not the case that
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
// would typically indicate; that's because we internally use CAS operations vs. true locks.
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
/// end of the <see cref="ConcurrentQueue{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Enqueue(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryDequeue(out item);
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
get
{
Segment head = _head;
if (!head.IsEmpty)
//fast route 1:
//if current head is not empty, then queue is not empty
return false;
else if (head.Next == null)
//fast route 2:
//if current head is empty and it's the last segment
//then queue is empty
return true;
else
//slow route:
//current head is empty and it is NOT the last segment,
//it means another thread is growing new segment
{
SpinWait spin = new SpinWait();
while (head.IsEmpty)
{
if (head.Next == null)
return true;
spin.SpinOnce();
head = _head;
}
return false;
}
}
}
/// <summary>
/// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
return ToList().ToArray();
}
#pragma warning disable 0420 // No warning for Interlocked.xxx if compiled with new managed compiler (Roslyn)
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see
/// cref="T:System.Collections.Generic.List{T}"/>.
/// </summary>
/// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of
/// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
private List<T> ToList()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether _numSnapshotTakers == 0.
Interlocked.Increment(ref _numSnapshotTakers);
List<T> list = new List<T>();
try
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
head.AddToList(list, headLow, tailHigh);
}
else
{
head.AddToList(list, headLow, SEGMENT_SIZE - 1);
Segment curr = head.Next;
while (curr != tail)
{
curr.AddToList(list, 0, SEGMENT_SIZE - 1);
curr = curr.Next;
}
//Add tail segment
tail.AddToList(list, 0, tailHigh);
}
}
finally
{
// This Decrement must happen after copying is over.
Interlocked.Decrement(ref _numSnapshotTakers);
}
return list;
}
/// <summary>
/// Store the position of the current head and tail positions.
/// </summary>
/// <param name="head">return the head segment</param>
/// <param name="tail">return the tail segment</param>
/// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param>
/// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param>
private void GetHeadTailPositions(out Segment head, out Segment tail,
out int headLow, out int tailHigh)
{
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
SpinWait spin = new SpinWait();
//we loop until the observed values are stable and sensible.
//This ensures that any update order by other methods can be tolerated.
while (
//if head and tail changed, retry
head != _head || tail != _tail
//if low and high pointers, retry
|| headLow != head.Low || tailHigh != tail.High
//if head jumps ahead of tail because of concurrent grow and dequeue, retry
|| head._index > tail._index)
{
spin.SpinOnce();
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
return tailHigh - headLow + 1;
}
//head segment
int count = SEGMENT_SIZE - headLow;
//middle segment(s), if any, are full.
//We don't deal with overflow to be consistent with the behavior of generic types in CLR.
count += SEGMENT_SIZE * ((int)(tail._index - head._index - 1));
//tail segment
count += tailHigh + 1;
return count;
}
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
/// cref="T:System.Array">Array</see>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
ToList().CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether _numSnapshotTakers == 0.
Interlocked.Increment(ref _numSnapshotTakers);
// Takes a snapshot of the queue.
// A design flaw here: if a Thread.Abort() happens, we cannot decrement _numSnapshotTakers. But we cannot
// wrap the following with a try/finally block, otherwise the decrement will happen before the yield return
// statements in the GetEnumerator (head, tail, headLow, tailHigh) method.
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
// the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
// This is inconsistent with existing generic collections. In order to prevent it, we capture the
// value of _head in a buffer and call out to a helper method.
//The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an
// unnecessary perfomance hit.
return GetEnumerator(head, tail, headLow, tailHigh);
}
/// <summary>
/// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation.
/// </summary>
private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh)
{
try
{
SpinWait spin = new SpinWait();
if (head == tail)
{
for (int i = headLow; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head._state[i]._value)
{
spin.SpinOnce();
}
yield return head._array[i];
}
}
else
{
//iterate on head segment
for (int i = headLow; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head._state[i]._value)
{
spin.SpinOnce();
}
yield return head._array[i];
}
//iterate on middle segments
Segment curr = head.Next;
while (curr != tail)
{
for (int i = 0; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!curr._state[i]._value)
{
spin.SpinOnce();
}
yield return curr._array[i];
}
curr = curr.Next;
}
//iterate on tail segment
for (int i = 0; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!tail._state[i]._value)
{
spin.SpinOnce();
}
yield return tail._array[i];
}
}
}
finally
{
// This Decrement must happen after the enumeration is over.
Interlocked.Decrement(ref _numSnapshotTakers);
}
}
/// <summary>
/// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="item">The object to add to the end of the <see
/// cref="ConcurrentQueue{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
SpinWait spin = new SpinWait();
while (true)
{
Segment tail = _tail;
if (tail.TryAppend(item))
return;
spin.SpinOnce();
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the beggining of the <see
/// cref="ConcurrentQueue{T}"/>
/// succesfully; otherwise, false.</returns>
public bool TryDequeue(out T result)
{
while (!IsEmpty)
{
Segment head = _head;
if (head.TryRemove(out result))
return true;
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
return false;
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Interlocked.Increment(ref _numSnapshotTakers);
while (!IsEmpty)
{
Segment head = _head;
if (head.TryPeek(out result))
{
Interlocked.Decrement(ref _numSnapshotTakers);
return true;
}
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
Interlocked.Decrement(ref _numSnapshotTakers);
return false;
}
/// <summary>
/// private class for ConcurrentQueue.
/// a queue is a linked list of small arrays, each node is called a segment.
/// A segment contains an array, a pointer to the next segment, and _low, _high indices recording
/// the first and last valid elements of the array.
/// </summary>
private class Segment
{
//we define two volatile arrays: _array and _state. Note that the accesses to the array items
//do not get volatile treatment. But we don't need to worry about loading adjacent elements or
//store/load on adjacent elements would suffer reordering.
// - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
// - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
// are sufficient to prevent reordering of the loads of the elements.
internal volatile T[] _array;
// For each entry in _array, the corresponding entry in _state indicates whether this position contains
// a valid value. _state is initially all false.
internal volatile VolatileBool[] _state;
//pointer to the next segment. null if the current segment is the last segment
private volatile Segment _next;
//We use this zero based index to track how many segments have been created for the queue, and
//to compute how many active segments are there currently.
// * The number of currently active segments is : _tail._index - _head._index + 1;
// * _index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
// assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
// billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
internal readonly long _index;
//indices of where the first and last valid values
// - _low points to the position of the next element to pop from this segment, range [0, infinity)
// _low >= SEGMENT_SIZE implies the segment is disposable
// - _high points to the position of the latest pushed element, range [-1, infinity)
// _high == -1 implies the segment is new and empty
// _high >= SEGMENT_SIZE-1 means this segment is ready to grow.
// and the thread who sets _high to SEGMENT_SIZE-1 is responsible to grow the segment
// - Math.Min(_low, SEGMENT_SIZE) > Math.Min(_high, SEGMENT_SIZE-1) implies segment is empty
// - initially _low =0 and _high=-1;
private volatile int _low;
private volatile int _high;
private volatile ConcurrentQueue<T> _source;
/// <summary>
/// Create and initialize a segment with the specified index.
/// </summary>
internal Segment(long index, ConcurrentQueue<T> source)
{
_array = new T[SEGMENT_SIZE];
_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
_high = -1;
Debug.Assert(index >= 0);
_index = index;
_source = source;
}
/// <summary>
/// return the next segment
/// </summary>
internal Segment Next
{
get { return _next; }
}
/// <summary>
/// return true if the current segment is empty (doesn't have any element available to dequeue,
/// false otherwise
/// </summary>
internal bool IsEmpty
{
get { return (Low > High); }
}
/// <summary>
/// Add an element to the tail of the current segment
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
Debug.Assert(_high < SEGMENT_SIZE - 1);
_high++;
_array[_high] = value;
_state[_high]._value = true;
}
/// <summary>
/// Create a new segment and append to the current one
/// Does not update the _tail pointer
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
Debug.Assert(_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(_index + 1, _source); //_index is Int64, we don't need to worry about overflow
_next = newSegment;
return newSegment;
}
/// <summary>
/// Create a new segment and append to the current one
/// Update the _tail pointer
/// This method is called when there is no contention
/// </summary>
internal void Grow()
{
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(_index + 1, _source); //_index is Int64, we don't need to worry about overflow
_next = newSegment;
Debug.Assert(_source._tail == this);
_source._tail = _next;
}
/// <summary>
/// Try to append an element at the end of this segment.
/// </summary>
/// <param name="value">the element to append</param>
/// <param name="tail">The tail.</param>
/// <returns>true if the element is appended, false if the current segment is full</returns>
/// <remarks>if appending the specified element succeeds, and after which the segment is full,
/// then grow the segment</remarks>
internal bool TryAppend(T value)
{
//quickly check if _high is already over the boundary, if so, bail out
if (_high >= SEGMENT_SIZE - 1)
{
return false;
}
//Now we will use a CAS to increment _high, and store the result in newhigh.
//Depending on how many free spots left in this segment and how many threads are doing this Increment
//at this time, the returning "newhigh" can be
// 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
// 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
// 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
// Queue.Enqueue method, telling it to try again in the next segment.
int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for _state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref _high);
if (newhigh <= SEGMENT_SIZE - 1)
{
_array[newhigh] = value;
_state[newhigh]._value = true;
}
//if this thread takes up the last slot in the segment, then this thread is responsible
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
//if thread abort during Grow, other threads will be left busy spinning forever.
if (newhigh == SEGMENT_SIZE - 1)
{
Grow();
}
}
//if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
return newhigh <= SEGMENT_SIZE - 1;
}
/// <summary>
/// try to remove an element from the head of current segment
/// </summary>
/// <param name="result">The result.</param>
/// <param name="head">The head.</param>
/// <returns>return false only if the current segment is empty</returns>
internal bool TryRemove(out T result)
{
SpinWait spin = new SpinWait();
int lowLocal = Low, highLocal = High;
while (lowLocal <= highLocal)
{
//try to update _low
if (Interlocked.CompareExchange(ref _low, lowLocal + 1, lowLocal) == lowLocal)
{
//if the specified value is not available (this spot is taken by a push operation,
// but the value is not written into yet), then spin
SpinWait spinLocal = new SpinWait();
while (!_state[lowLocal]._value)
{
spinLocal.SpinOnce();
}
result = _array[lowLocal];
// If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null.
// It is ok if after this conditional check _numSnapshotTakers becomes > 0, because new snapshots won't include
// the deleted entry at _array[lowLocal].
if (_source._numSnapshotTakers <= 0)
{
_array[lowLocal] = default(T); //release the reference to the object.
}
//if the current thread sets _low to SEGMENT_SIZE, which means the current segment becomes
//disposable, then this thread is responsible to dispose this segment, and reset _head
if (lowLocal + 1 >= SEGMENT_SIZE)
{
// Invariant: we only dispose the current _head, not any other segment
// In usual situation, disposing a segment is simply seting _head to _head._next
// But there is one special case, where _head and _tail points to the same and ONLY
//segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
//Grow operation, this is the reason of having the following while loop
spinLocal = new SpinWait();
while (_next == null)
{
spinLocal.SpinOnce();
}
Debug.Assert(_source._head == this);
_source._head = _next;
}
return true;
}
else
{
//CAS failed due to contention: spin briefly and retry
spin.SpinOnce();
lowLocal = Low; highLocal = High;
}
}//end of while
result = default(T);
return false;
}
#pragma warning restore 0420
/// <summary>
/// try to peek the current segment
/// </summary>
/// <param name="result">holds the return value of the element at the head position,
/// value set to default(T) if there is no such an element</param>
/// <returns>true if there are elements in the current segment, false otherwise</returns>
internal bool TryPeek(out T result)
{
result = default(T);
int lowLocal = Low;
if (lowLocal > High)
return false;
SpinWait spin = new SpinWait();
while (!_state[lowLocal]._value)
{
spin.SpinOnce();
}
result = _array[lowLocal];
return true;
}
/// <summary>
/// Adds part or all of the current segment into a List.
/// </summary>
/// <param name="list">the list to which to add</param>
/// <param name="start">the start position</param>
/// <param name="end">the end position</param>
internal void AddToList(List<T> list, int start, int end)
{
for (int i = start; i <= end; i++)
{
SpinWait spin = new SpinWait();
while (!_state[i]._value)
{
spin.SpinOnce();
}
list.Add(_array[i]);
}
}
/// <summary>
/// return the position of the head of the current segment
/// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty
/// </summary>
internal int Low
{
get
{
return Math.Min(_low, SEGMENT_SIZE);
}
}
/// <summary>
/// return the logical position of the tail of the current segment
/// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet
/// </summary>
internal int High
{
get
{
//if _high > SEGMENT_SIZE, it means it's out of range, we should return
//SEGMENT_SIZE-1 as the logical position
return Math.Min(_high, SEGMENT_SIZE - 1);
}
}
}
}//end of class Segment
/// <summary>
/// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile
/// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile
/// </summary>
struct VolatileBool
{
public volatile bool _value;
}
}
| |
#pragma warning disable 1591
using AjaxControlToolkit.Design;
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// An extender class which adds collapse/expand behavior to an ASP.NET Panel control.
/// The panel that is extended can then be collapsed or expanded by the user of the page, which is handy
/// for doing things like showing or hiding content or maximizing available space.
/// </summary>
[Designer(typeof(CollapsiblePanelExtenderDesigner))]
[ClientScriptResource("Sys.Extended.UI.CollapsiblePanelBehavior", Constants.CollapsiblePanelName)]
[RequiredScript(typeof(CommonToolkitScripts))]
[RequiredScript(typeof(AnimationScripts))]
[TargetControlType(typeof(Panel))]
[DefaultProperty("CollapseControlID")]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.CollapsiblePanelName + Constants.IconPostfix)]
public class CollapsiblePanelExtender : ExtenderControlBase {
public CollapsiblePanelExtender() {
ClientStateValuesLoaded += new EventHandler(CollapsiblePanelExtender_ClientStateValuesLoaded);
EnableClientState = true;
}
/// <summary>
/// The server ID of the control to initiate the collapse of the target panel. The panel will
/// collapse when this control fires its client side "onclick" event
/// </summary>
/// <remarks>
/// If this value is the same as the value for "ExpandControlID", the CollapsiblePanel will
/// toggle when this control is clicked
/// </remarks>
[IDReferenceProperty(typeof(WebControl))]
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("collapseControlID")]
public string CollapseControlID {
get { return GetPropertyValue("CollapseControlID", String.Empty); }
set { SetPropertyValue("CollapseControlID", value); }
}
/// <summary>
/// The server ID of the control to initiate the expansion of the target panel. The panel will
/// opening when this control fires its client side "onclick" event
/// </summary>
/// <remarks>
/// If this value is the same as the value for "CollapseControlID", the CollapsiblePanel will
/// toggle when this control is clicked
/// </remarks>
[IDReferenceProperty(typeof(WebControl))]
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("expandControlID")]
public string ExpandControlID {
get { return GetPropertyValue("ExpandControlID", String.Empty); }
set { SetPropertyValue("ExpandControlID", value); }
}
/// <summary>
/// If true, and the panel is in its 'expanded' state, the panel will
/// automatically collapse when the mouse pointer moves off of the panel.
/// The default is false
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("autoCollapse")]
public bool AutoCollapse {
get { return GetPropertyValue("AutoCollapse", false); }
set { SetPropertyValue("AutoCollapse", value); }
}
/// <summary>
/// If true, and the panel is in its 'collapsed' state, the panel will
/// automatically expand when the mouse pointer moves into the panel.
/// The default is false
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("autoExpand")]
public bool AutoExpand {
get { return GetPropertyValue("AutoExpand", false); }
set { SetPropertyValue("AutoExpand", value); }
}
/// <summary>
/// The size of the panel when it is in it's collapsed state. To avoid flicker when your page
/// initializes, set the initial height (or width) of your Panel control to match this value, and set the Collapsed property
/// to 'true'
/// </summary>
/// <remarks>
/// The default value is -1, which indicates that the CollapsiblePanel should initialize the CollapsedSize based on the
/// initial size of the object
/// </remarks>
[DefaultValue(-1)]
[ExtenderControlProperty]
[ClientPropertyName("collapsedSize")]
public int CollapsedSize {
get { return GetPropertyValue("CollapseHeight", -1); }
set { SetPropertyValue("CollapseHeight", value); }
}
/// <summary>
/// The size of the panel when it is in it's opened state. To avoid flicker when your page
/// initializes, set the initial width of your Panel control to match this value, and set the Collapsed property
/// to 'false'
/// </summary>
/// <remarks>
/// The default value is -1, which indicates that the CollapsiblePanel should initialize the ExpandedSize based on the
/// parent div offsetheight if aligned vertically and parentdiv offsetwidth if aligned horizonatally
/// </remarks>
[DefaultValue(-1)]
[ExtenderControlProperty]
public int ExpandedSize {
get { return GetPropertyValue("ExpandedSize", -1); }
set { SetPropertyValue("ExpandedSize", value); }
}
/// <summary>
/// Determines whether the contents of the panel should be scrolled or clipped if they do not fit into
/// the expanded size.
/// The default is false
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("scrollContents")]
public bool ScrollContents {
get { return GetPropertyValue("ScrollContents", false); }
set { SetPropertyValue("ScrollContents", value); }
}
/// <summary>
/// Determines whether the CollapsiblePanelBehavior should suppress the click operations of the controls
/// referenced in CollapseControlID and/or ExpandControlID.
/// </summary>
/// <remarks>
/// By default, this value is false, except for anchor ("A") tags
/// </remarks>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("suppressPostBack")]
public bool SuppressPostBack {
get { return GetPropertyValue("SuppressPostBack", false); }
set { SetPropertyValue("SuppressPostBack", value); }
}
/// <summary>
/// Signals the initial collapsed state of the control. Note this will not cause
/// an expanded control to collapse at initialization, but rather tells the extender
/// what the initial state of the Panel control is.
/// The default is false
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("collapsed")]
public bool Collapsed {
get { return GetPropertyValue("Collapsed", false); }
set { SetPropertyValue("Collapsed", value); }
}
/// <summary>
/// The text to display in the collapsed state. When the panel is collapsed,
/// the internal contents (anything between the start and ending tags) of the control referenced by
/// the TextLabelID property will be replaced with this text. This collapsed text is also used
/// as the alternate text of the image if ImageControlID is set
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("collapsedText")]
public string CollapsedText {
get { return GetPropertyValue("CollapsedText", String.Empty); }
set { SetPropertyValue("CollapsedText", value); }
}
/// <summary>
/// The text to display in the expanded state. When the panel is expanded,
/// the internal contents (anything between the start and ending tags) of the control referenced by
/// the TextLabelID property will be replaced with this text. This expanded text is also used
/// as the alternate text of the image if ImageControlID is set
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("expandedText")]
public string ExpandedText {
get { return GetPropertyValue("ExpandedText", String.Empty); }
set { SetPropertyValue("ExpandedText", value); }
}
/// <summary>
/// The ID of a label control to display the current state of the Panel. When the collapsed state of the
/// panel changes, the entire HTML contents (anything between the start and ending tags of the label) will be replaced
/// with the status text
/// </summary>
[IDReferenceProperty(typeof(Label))]
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("textLabelID")]
public string TextLabelID {
get { return GetPropertyValue("TextLabelID", String.Empty); }
set { SetPropertyValue("TextLabelID", value); }
}
/// <summary>
/// Image to be displayed when the Panel is expanded and the ImageControlID is set
/// </summary>
[DefaultValue("")]
[UrlProperty]
[ExtenderControlProperty]
[ClientPropertyName("expandedImage")]
public string ExpandedImage {
get { return GetPropertyValue("ExpandedImage", String.Empty); }
set { SetPropertyValue("ExpandedImage", value); }
}
/// <summary>
/// Image to be displayed when the Panel is collapsed and the ImageControlID is set
/// </summary>
[DefaultValue("")]
[UrlProperty]
[ExtenderControlProperty]
[ClientPropertyName("collapsedImage")]
public string CollapsedImage {
get { return GetPropertyValue("CollapsedImage", String.Empty); }
set { SetPropertyValue("CollapsedImage", value); }
}
/// <summary>
/// The ID of an image control to display the current state of the Panel. When the collapsed state of the
/// panel changes, the image source will be changed from the ExpandedImage to the CollapsedImage. We also
/// use the ExpandedText and CollapsedText as the image's alternate text if they are provided
/// </summary>
[IDReferenceProperty(typeof(System.Web.UI.WebControls.Image))]
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("imageControlID")]
public string ImageControlID {
get { return GetPropertyValue("ImageControlID", String.Empty); }
set { SetPropertyValue("ImageControlID", value); }
}
/// <summary>
/// The dimension to use for collapsing and expanding - vertical or horizontal
/// </summary>
[DefaultValue(CollapsiblePanelExpandDirection.Vertical)]
[ExtenderControlProperty]
[ClientPropertyName("expandDirection")]
public CollapsiblePanelExpandDirection ExpandDirection {
get { return GetPropertyValue("ExpandDirection", CollapsiblePanelExpandDirection.Vertical); }
set { SetPropertyValue("ExpandDirection", value); }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void EnsureValid() {
base.EnsureValid();
if((ExpandedText != null || CollapsedText != null) && TextLabelID == null)
throw new ArgumentException("If CollapsedText or ExpandedText is set, TextLabelID must also be set.");
}
void CollapsiblePanelExtender_ClientStateValuesLoaded(object sender, EventArgs e) {
var ctrl = this.FindControl(this.TargetControlID) as WebControl;
if(ctrl != null) {
if(!String.IsNullOrEmpty(base.ClientState)) {
var collapsed = bool.Parse(base.ClientState);
if(collapsed)
ctrl.Style["display"] = "none";
else
ctrl.Style["display"] = String.Empty;
}
}
}
}
}
#pragma warning restore 1591
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace OpenMetaverse.StructuredData
{
/// <summary>
///
/// </summary>
public enum OSDType
{
/// <summary></summary>
Unknown,
/// <summary></summary>
Boolean,
/// <summary></summary>
Integer,
/// <summary></summary>
Real,
/// <summary></summary>
String,
/// <summary></summary>
UUID,
/// <summary></summary>
Date,
/// <summary></summary>
URI,
/// <summary></summary>
Binary,
/// <summary></summary>
Map,
/// <summary></summary>
Array
}
public enum OSDFormat
{
Xml = 0,
Json,
Binary
}
/// <summary>
///
/// </summary>
public class OSDException : Exception
{
public OSDException(string message) : base(message) { }
}
/// <summary>
///
/// </summary>
public partial class OSD
{
public virtual OSDType Type { get { return OSDType.Unknown; } }
public virtual bool AsBoolean() { return false; }
public virtual int AsInteger() { return 0; }
public virtual uint AsUInteger() { return 0; }
public virtual long AsLong() { return 0; }
public virtual ulong AsULong() { return 0; }
public virtual double AsReal() { return 0d; }
public virtual string AsString() { return String.Empty; }
public virtual UUID AsUUID() { return UUID.Zero; }
public virtual DateTime AsDate() { return Utils.Epoch; }
public virtual Uri AsUri() { return null; }
public virtual byte[] AsBinary() { return Utils.EmptyBytes; }
public virtual Vector2 AsVector2() { return Vector2.Zero; }
public virtual Vector3 AsVector3() { return Vector3.Zero; }
public virtual Vector3d AsVector3d() { return Vector3d.Zero; }
public virtual Vector4 AsVector4() { return Vector4.Zero; }
public virtual Quaternion AsQuaternion() { return Quaternion.Identity; }
public virtual Color4 AsColor4() { return Color4.Black; }
public override string ToString() { return "undef"; }
public static OSD FromBoolean(bool value) { return new OSDBoolean(value); }
public static OSD FromInteger(int value) { return new OSDInteger(value); }
public static OSD FromInteger(uint value) { return new OSDInteger((int)value); }
public static OSD FromInteger(short value) { return new OSDInteger((int)value); }
public static OSD FromInteger(ushort value) { return new OSDInteger((int)value); }
public static OSD FromInteger(sbyte value) { return new OSDInteger((int)value); }
public static OSD FromInteger(byte value) { return new OSDInteger((int)value); }
public static OSD FromUInteger(uint value) { return new OSDBinary(value); }
public static OSD FromLong(long value) { return new OSDBinary(value); }
public static OSD FromULong(ulong value) { return new OSDBinary(value); }
public static OSD FromReal(double value) { return new OSDReal(value); }
public static OSD FromReal(float value) { return new OSDReal((double)value); }
public static OSD FromString(string value) { return new OSDString(value); }
public static OSD FromUUID(UUID value) { return new OSDUUID(value); }
public static OSD FromDate(DateTime value) { return new OSDDate(value); }
public static OSD FromUri(Uri value) { return new OSDUri(value); }
public static OSD FromBinary(byte[] value) { return new OSDBinary(value); }
public static OSD FromVector2(Vector2 value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.X));
array.Add(OSD.FromReal(value.Y));
return array;
}
public static OSD FromVector3(Vector3 value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.X));
array.Add(OSD.FromReal(value.Y));
array.Add(OSD.FromReal(value.Z));
return array;
}
public static OSD FromVector3d(Vector3d value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.X));
array.Add(OSD.FromReal(value.Y));
array.Add(OSD.FromReal(value.Z));
return array;
}
public static OSD FromVector4(Vector4 value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.X));
array.Add(OSD.FromReal(value.Y));
array.Add(OSD.FromReal(value.Z));
array.Add(OSD.FromReal(value.W));
return array;
}
public static OSD FromQuaternion(Quaternion value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.X));
array.Add(OSD.FromReal(value.Y));
array.Add(OSD.FromReal(value.Z));
array.Add(OSD.FromReal(value.W));
return array;
}
public static OSD FromColor4(Color4 value)
{
OSDArray array = new OSDArray();
array.Add(OSD.FromReal(value.R));
array.Add(OSD.FromReal(value.G));
array.Add(OSD.FromReal(value.B));
array.Add(OSD.FromReal(value.A));
return array;
}
public static OSD FromObject(object value)
{
if (value == null) { return new OSD(); }
else if (value is bool) { return new OSDBoolean((bool)value); }
else if (value is int) { return new OSDInteger((int)value); }
else if (value is uint) { return new OSDBinary((uint)value); }
else if (value is short) { return new OSDInteger((int)(short)value); }
else if (value is ushort) { return new OSDInteger((int)(ushort)value); }
else if (value is sbyte) { return new OSDInteger((int)(sbyte)value); }
else if (value is byte) { return new OSDInteger((int)(byte)value); }
else if (value is double) { return new OSDReal((double)value); }
else if (value is float) { return new OSDReal((double)(float)value); }
else if (value is string) { return new OSDString((string)value); }
else if (value is UUID) { return new OSDUUID((UUID)value); }
else if (value is DateTime) { return new OSDDate((DateTime)value); }
else if (value is Uri) { return new OSDUri((Uri)value); }
else if (value is byte[]) { return new OSDBinary((byte[])value); }
else if (value is long) { return new OSDBinary((long)value); }
else if (value is ulong) { return new OSDBinary((ulong)value); }
else if (value is Vector2) { return FromVector2((Vector2)value); }
else if (value is Vector3) { return FromVector3((Vector3)value); }
else if (value is Vector3d) { return FromVector3d((Vector3d)value); }
else if (value is Vector4) { return FromVector4((Vector4)value); }
else if (value is Quaternion) { return FromQuaternion((Quaternion)value); }
else if (value is Color4) { return FromColor4((Color4)value); }
else return new OSD();
}
public static object ToObject(Type type, OSD value)
{
if (type == typeof(ulong))
{
if (value.Type == OSDType.Binary)
{
byte[] bytes = value.AsBinary();
return Utils.BytesToUInt64(bytes);
}
else
{
return (ulong)value.AsInteger();
}
}
else if (type == typeof(uint))
{
if (value.Type == OSDType.Binary)
{
byte[] bytes = value.AsBinary();
return Utils.BytesToUInt(bytes);
}
else
{
return (uint)value.AsInteger();
}
}
else if (type == typeof(ushort))
{
return (ushort)value.AsInteger();
}
else if (type == typeof(byte))
{
return (byte)value.AsInteger();
}
else if (type == typeof(short))
{
return (short)value.AsInteger();
}
else if (type == typeof(string))
{
return value.AsString();
}
else if (type == typeof(bool))
{
return value.AsBoolean();
}
else if (type == typeof(float))
{
return (float)value.AsReal();
}
else if (type == typeof(double))
{
return value.AsReal();
}
else if (type == typeof(int))
{
return value.AsInteger();
}
else if (type == typeof(UUID))
{
return value.AsUUID();
}
else if (type == typeof(Vector3))
{
if (value.Type == OSDType.Array)
return ((OSDArray)value).AsVector3();
else
return Vector3.Zero;
}
else if (type == typeof(Vector4))
{
if (value.Type == OSDType.Array)
return ((OSDArray)value).AsVector4();
else
return Vector4.Zero;
}
else if (type == typeof(Quaternion))
{
if (value.Type == OSDType.Array)
return ((OSDArray)value).AsQuaternion();
else
return Quaternion.Identity;
}
else
{
return null;
}
}
#region Implicit Conversions
public static implicit operator OSD(bool value) { return new OSDBoolean(value); }
public static implicit operator OSD(int value) { return new OSDInteger(value); }
public static implicit operator OSD(uint value) { return new OSDInteger((int)value); }
public static implicit operator OSD(short value) { return new OSDInteger((int)value); }
public static implicit operator OSD(ushort value) { return new OSDInteger((int)value); }
public static implicit operator OSD(sbyte value) { return new OSDInteger((int)value); }
public static implicit operator OSD(byte value) { return new OSDInteger((int)value); }
public static implicit operator OSD(long value) { return new OSDBinary(value); }
public static implicit operator OSD(ulong value) { return new OSDBinary(value); }
public static implicit operator OSD(double value) { return new OSDReal(value); }
public static implicit operator OSD(float value) { return new OSDReal(value); }
public static implicit operator OSD(string value) { return new OSDString(value); }
public static implicit operator OSD(UUID value) { return new OSDUUID(value); }
public static implicit operator OSD(DateTime value) { return new OSDDate(value); }
public static implicit operator OSD(Uri value) { return new OSDUri(value); }
public static implicit operator OSD(byte[] value) { return new OSDBinary(value); }
public static implicit operator OSD(Vector2 value) { return OSD.FromVector2(value); }
public static implicit operator OSD(Vector3 value) { return OSD.FromVector3(value); }
public static implicit operator OSD(Vector3d value) { return OSD.FromVector3d(value); }
public static implicit operator OSD(Vector4 value) { return OSD.FromVector4(value); }
public static implicit operator OSD(Quaternion value) { return OSD.FromQuaternion(value); }
public static implicit operator OSD(Color4 value) { return OSD.FromColor4(value); }
public static implicit operator bool(OSD value) { return value.AsBoolean(); }
public static implicit operator int(OSD value) { return value.AsInteger(); }
public static implicit operator uint(OSD value) { return value.AsUInteger(); }
public static implicit operator long(OSD value) { return value.AsLong(); }
public static implicit operator ulong(OSD value) { return value.AsULong(); }
public static implicit operator double(OSD value) { return value.AsReal(); }
public static implicit operator float(OSD value) { return (float)value.AsReal(); }
public static implicit operator string(OSD value) { return value.AsString(); }
public static implicit operator UUID(OSD value) { return value.AsUUID(); }
public static implicit operator DateTime(OSD value) { return value.AsDate(); }
public static implicit operator Uri(OSD value) { return value.AsUri(); }
public static implicit operator byte[](OSD value) { return value.AsBinary(); }
public static implicit operator Vector2(OSD value) { return value.AsVector2(); }
public static implicit operator Vector3(OSD value) { return value.AsVector3(); }
public static implicit operator Vector3d(OSD value) { return value.AsVector3d(); }
public static implicit operator Vector4(OSD value) { return value.AsVector4(); }
public static implicit operator Quaternion(OSD value) { return value.AsQuaternion(); }
public static implicit operator Color4(OSD value) { return value.AsColor4(); }
#endregion Implicit Conversions
/// <summary>
/// Uses reflection to create an SDMap from all of the SD
/// serializable types in an object
/// </summary>
/// <param name="obj">Class or struct containing serializable types</param>
/// <returns>An SDMap holding the serialized values from the
/// container object</returns>
public static OSDMap SerializeMembers(object obj)
{
Type t = obj.GetType();
FieldInfo[] fields = t.GetFields();
OSDMap map = new OSDMap(fields.Length);
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute)))
{
OSD serializedField = OSD.FromObject(field.GetValue(obj));
if (serializedField.Type != OSDType.Unknown || field.FieldType == typeof(string) || field.FieldType == typeof(byte[]))
map.Add(field.Name, serializedField);
}
}
return map;
}
/// <summary>
/// Uses reflection to deserialize member variables in an object from
/// an SDMap
/// </summary>
/// <param name="obj">Reference to an object to fill with deserialized
/// values</param>
/// <param name="serialized">Serialized values to put in the target
/// object</param>
public static void DeserializeMembers(ref object obj, OSDMap serialized)
{
Type t = obj.GetType();
FieldInfo[] fields = t.GetFields();
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
if (!Attribute.IsDefined(field, typeof(NonSerializedAttribute)))
{
OSD serializedField;
if (serialized.TryGetValue(field.Name, out serializedField))
field.SetValue(obj, ToObject(field.FieldType, serializedField));
}
}
}
}
/// <summary>
///
/// </summary>
public sealed class OSDBoolean : OSD
{
private bool value;
private static byte[] trueBinary = { 0x31 };
private static byte[] falseBinary = { 0x30 };
public override OSDType Type { get { return OSDType.Boolean; } }
public OSDBoolean(bool value)
{
this.value = value;
}
public override bool AsBoolean() { return value; }
public override int AsInteger() { return value ? 1 : 0; }
public override double AsReal() { return value ? 1d : 0d; }
public override string AsString() { return value ? "1" : "0"; }
public override byte[] AsBinary() { return value ? trueBinary : falseBinary; }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDInteger : OSD
{
private int value;
public override OSDType Type { get { return OSDType.Integer; } }
public OSDInteger(int value)
{
this.value = value;
}
public override bool AsBoolean() { return value != 0; }
public override int AsInteger() { return value; }
public override uint AsUInteger() { return (uint)value; }
public override long AsLong() { return value; }
public override ulong AsULong() { return (ulong)value; }
public override double AsReal() { return (double)value; }
public override string AsString() { return value.ToString(); }
public override byte[] AsBinary() { return Utils.IntToBytesBig(value); }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDReal : OSD
{
private double value;
public override OSDType Type { get { return OSDType.Real; } }
public OSDReal(double value)
{
this.value = value;
}
public override bool AsBoolean() { return (!Double.IsNaN(value) && value != 0d); }
public override int AsInteger()
{
if (Double.IsNaN(value))
return 0;
if (value > (double)Int32.MaxValue)
return Int32.MaxValue;
if (value < (double)Int32.MinValue)
return Int32.MinValue;
return (int)Math.Round(value);
}
public override uint AsUInteger()
{
if (Double.IsNaN(value))
return 0;
if (value > (double)UInt32.MaxValue)
return UInt32.MaxValue;
if (value < (double)UInt32.MinValue)
return UInt32.MinValue;
return (uint)Math.Round(value);
}
public override long AsLong()
{
if (Double.IsNaN(value))
return 0;
if (value > (double)Int64.MaxValue)
return Int64.MaxValue;
if (value < (double)Int64.MinValue)
return Int64.MinValue;
return (long)Math.Round(value);
}
public override ulong AsULong()
{
if (Double.IsNaN(value))
return 0;
if (value > (double)UInt64.MaxValue)
return Int32.MaxValue;
if (value < (double)UInt64.MinValue)
return UInt64.MinValue;
return (ulong)Math.Round(value);
}
public override double AsReal() { return value; }
// "r" ensures the value will correctly round-trip back through Double.TryParse
public override string AsString() { return value.ToString("r", Utils.EnUsCulture); }
public override byte[] AsBinary() { return Utils.DoubleToBytesBig(value); }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDString : OSD
{
private string value;
public override OSDType Type { get { return OSDType.String; } }
public OSDString(string value)
{
// Refuse to hold null pointers
if (value != null)
this.value = value;
else
this.value = String.Empty;
}
public override bool AsBoolean()
{
if (String.IsNullOrEmpty(value))
return false;
if (value == "0" || value.ToLower() == "false")
return false;
return true;
}
public override int AsInteger()
{
double dbl;
if (Double.TryParse(value, out dbl))
return (int)Math.Floor(dbl);
else
return 0;
}
public override uint AsUInteger()
{
double dbl;
if (Double.TryParse(value, out dbl))
return (uint)Math.Floor(dbl);
else
return 0;
}
public override long AsLong()
{
double dbl;
if (Double.TryParse(value, out dbl))
return (long)Math.Floor(dbl);
else
return 0;
}
public override ulong AsULong()
{
double dbl;
if (Double.TryParse(value, out dbl))
return (ulong)Math.Floor(dbl);
else
return 0;
}
public override double AsReal()
{
double dbl;
if (Double.TryParse(value, out dbl))
return dbl;
else
return 0d;
}
public override string AsString() { return value; }
public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(value); }
public override UUID AsUUID()
{
string tmpVal = value;
if (tmpVal.Substring(0, 6) == "uuid::")
{
tmpVal = tmpVal.Substring(6);
}
UUID uuid;
if (UUID.TryParse(tmpVal, out uuid))
return uuid;
else
return UUID.Zero;
}
public override DateTime AsDate()
{
DateTime dt;
if (DateTime.TryParse(value, out dt))
return dt;
else
return Utils.Epoch;
}
public override Uri AsUri()
{
Uri uri;
if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out uri))
return uri;
else
return null;
}
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDUUID : OSD
{
private UUID value;
public override OSDType Type { get { return OSDType.UUID; } }
public OSDUUID(UUID value)
{
this.value = value;
}
public override bool AsBoolean() { return (value == UUID.Zero) ? false : true; }
public override string AsString() { return value.ToString(); }
public override UUID AsUUID() { return value; }
public override byte[] AsBinary() { return value.GetBytes(); }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDDate : OSD
{
private DateTime value;
public override OSDType Type { get { return OSDType.Date; } }
public OSDDate(DateTime value)
{
this.value = value;
}
public override string AsString()
{
string format;
if (value.Millisecond > 0)
format = "yyyy-MM-ddTHH:mm:ss.ffZ";
else
format = "yyyy-MM-ddTHH:mm:ssZ";
return value.ToUniversalTime().ToString(format);
}
public override int AsInteger()
{
return (int)Utils.DateTimeToUnixTime(value);
}
public override uint AsUInteger()
{
return Utils.DateTimeToUnixTime(value);
}
public override long AsLong()
{
return (long)Utils.DateTimeToUnixTime(value);
}
public override ulong AsULong()
{
return Utils.DateTimeToUnixTime(value);
}
public override byte[] AsBinary()
{
TimeSpan ts = value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Utils.DoubleToBytes(ts.TotalSeconds);
}
public override DateTime AsDate() { return value; }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDUri : OSD
{
private Uri value;
public override OSDType Type { get { return OSDType.URI; } }
public OSDUri(Uri value)
{
this.value = value;
}
public override string AsString()
{
if (value != null)
{
if (value.IsAbsoluteUri)
return value.AbsoluteUri;
else
return value.ToString();
}
return string.Empty;
}
public override Uri AsUri() { return value; }
public override byte[] AsBinary() { return Encoding.UTF8.GetBytes(AsString()); }
public override string ToString() { return AsString(); }
}
/// <summary>
///
/// </summary>
public sealed class OSDBinary : OSD
{
private byte[] value;
public override OSDType Type { get { return OSDType.Binary; } }
public OSDBinary(byte[] value)
{
if (value != null)
this.value = value;
else
this.value = Utils.EmptyBytes;
}
public OSDBinary(uint value)
{
this.value = new byte[]
{
(byte)((value >> 24) % 256),
(byte)((value >> 16) % 256),
(byte)((value >> 8) % 256),
(byte)(value % 256)
};
}
public OSDBinary(long value)
{
this.value = new byte[]
{
(byte)((value >> 56) % 256),
(byte)((value >> 48) % 256),
(byte)((value >> 40) % 256),
(byte)((value >> 32) % 256),
(byte)((value >> 24) % 256),
(byte)((value >> 16) % 256),
(byte)((value >> 8) % 256),
(byte)(value % 256)
};
}
public OSDBinary(ulong value)
{
this.value = new byte[]
{
(byte)((value >> 56) % 256),
(byte)((value >> 48) % 256),
(byte)((value >> 40) % 256),
(byte)((value >> 32) % 256),
(byte)((value >> 24) % 256),
(byte)((value >> 16) % 256),
(byte)((value >> 8) % 256),
(byte)(value % 256)
};
}
public override string AsString() { return Convert.ToBase64String(value); }
public override byte[] AsBinary() { return value; }
public override uint AsUInteger()
{
return (uint)(
(value[0] << 24) +
(value[1] << 16) +
(value[2] << 8) +
(value[3] << 0));
}
public override long AsLong()
{
return (long)(
((long)value[0] << 56) +
((long)value[1] << 48) +
((long)value[2] << 40) +
((long)value[3] << 32) +
((long)value[4] << 24) +
((long)value[5] << 16) +
((long)value[6] << 8) +
((long)value[7] << 0));
}
public override ulong AsULong()
{
return (ulong)(
((ulong)value[0] << 56) +
((ulong)value[1] << 48) +
((ulong)value[2] << 40) +
((ulong)value[3] << 32) +
((ulong)value[4] << 24) +
((ulong)value[5] << 16) +
((ulong)value[6] << 8) +
((ulong)value[7] << 0));
}
public override string ToString()
{
return Utils.BytesToHexString(value, null);
}
}
/// <summary>
///
/// </summary>
public sealed class OSDMap : OSD, IDictionary<string, OSD>
{
private Dictionary<string, OSD> value;
public override OSDType Type { get { return OSDType.Map; } }
public OSDMap()
{
value = new Dictionary<string, OSD>();
}
public OSDMap(int capacity)
{
value = new Dictionary<string, OSD>(capacity);
}
public OSDMap(Dictionary<string, OSD> value)
{
if (value != null)
this.value = value;
else
this.value = new Dictionary<string, OSD>();
}
public override bool AsBoolean() { return value.Count > 0; }
public override string ToString()
{
return OSDParser.SerializeJsonString(this, true);
}
#region IDictionary Implementation
public int Count { get { return value.Count; } }
public bool IsReadOnly { get { return false; } }
public ICollection<string> Keys { get { return value.Keys; } }
public ICollection<OSD> Values { get { return value.Values; } }
public OSD this[string key]
{
get
{
OSD llsd;
if (this.value.TryGetValue(key, out llsd))
return llsd;
else
return new OSD();
}
set { this.value[key] = value; }
}
public bool ContainsKey(string key)
{
return value.ContainsKey(key);
}
public void Add(string key, OSD llsd)
{
value.Add(key, llsd);
}
public void Add(KeyValuePair<string, OSD> kvp)
{
value.Add(kvp.Key, kvp.Value);
}
public bool Remove(string key)
{
return value.Remove(key);
}
public bool TryGetValue(string key, out OSD llsd)
{
return value.TryGetValue(key, out llsd);
}
public void Clear()
{
value.Clear();
}
public bool Contains(KeyValuePair<string, OSD> kvp)
{
// This is a bizarre function... we don't really implement it
// properly, hopefully no one wants to use it
return value.ContainsKey(kvp.Key);
}
public void CopyTo(KeyValuePair<string, OSD>[] array, int index)
{
throw new NotImplementedException();
}
public bool Remove(KeyValuePair<string, OSD> kvp)
{
return this.value.Remove(kvp.Key);
}
public System.Collections.IDictionaryEnumerator GetEnumerator()
{
return value.GetEnumerator();
}
IEnumerator<KeyValuePair<string, OSD>> IEnumerable<KeyValuePair<string, OSD>>.GetEnumerator()
{
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
return value.GetEnumerator();
}
#endregion IDictionary Implementation
}
/// <summary>
///
/// </summary>
public sealed class OSDArray : OSD, IList<OSD>
{
private List<OSD> value;
public override OSDType Type { get { return OSDType.Array; } }
public OSDArray()
{
value = new List<OSD>();
}
public OSDArray(int capacity)
{
value = new List<OSD>(capacity);
}
public OSDArray(List<OSD> value)
{
if (value != null)
this.value = value;
else
this.value = new List<OSD>();
}
public override byte[] AsBinary()
{
byte[] binary = new byte[value.Count];
for (int i = 0; i < value.Count; i++)
binary[i] = (byte)value[i].AsInteger();
return binary;
}
public override long AsLong()
{
OSDBinary binary = new OSDBinary(AsBinary());
return binary.AsLong();
}
public override ulong AsULong()
{
OSDBinary binary = new OSDBinary(AsBinary());
return binary.AsULong();
}
public override uint AsUInteger()
{
OSDBinary binary = new OSDBinary(AsBinary());
return binary.AsUInteger();
}
public override Vector2 AsVector2()
{
Vector2 vector = Vector2.Zero;
if (this.Count == 2)
{
vector.X = (float)this[0].AsReal();
vector.Y = (float)this[1].AsReal();
}
return vector;
}
public override Vector3 AsVector3()
{
Vector3 vector = Vector3.Zero;
if (this.Count == 3)
{
vector.X = (float)this[0].AsReal();
vector.Y = (float)this[1].AsReal();
vector.Z = (float)this[2].AsReal();
}
return vector;
}
public override Vector3d AsVector3d()
{
Vector3d vector = Vector3d.Zero;
if (this.Count == 3)
{
vector.X = this[0].AsReal();
vector.Y = this[1].AsReal();
vector.Z = this[2].AsReal();
}
return vector;
}
public override Vector4 AsVector4()
{
Vector4 vector = Vector4.Zero;
if (this.Count == 4)
{
vector.X = (float)this[0].AsReal();
vector.Y = (float)this[1].AsReal();
vector.Z = (float)this[2].AsReal();
vector.W = (float)this[3].AsReal();
}
return vector;
}
public override Quaternion AsQuaternion()
{
Quaternion quaternion = Quaternion.Identity;
if (this.Count == 4)
{
quaternion.X = (float)this[0].AsReal();
quaternion.Y = (float)this[1].AsReal();
quaternion.Z = (float)this[2].AsReal();
quaternion.W = (float)this[3].AsReal();
}
return quaternion;
}
public override Color4 AsColor4()
{
Color4 color = Color4.Black;
if (this.Count == 4)
{
color.R = (float)this[0].AsReal();
color.G = (float)this[1].AsReal();
color.B = (float)this[2].AsReal();
color.A = (float)this[3].AsReal();
}
return color;
}
public override bool AsBoolean() { return value.Count > 0; }
public override string ToString()
{
return OSDParser.SerializeJsonString(this, true);
}
#region IList Implementation
public int Count { get { return value.Count; } }
public bool IsReadOnly { get { return false; } }
public OSD this[int index]
{
get { return value[index]; }
set { this.value[index] = value; }
}
public int IndexOf(OSD llsd)
{
return value.IndexOf(llsd);
}
public void Insert(int index, OSD llsd)
{
value.Insert(index, llsd);
}
public void RemoveAt(int index)
{
value.RemoveAt(index);
}
public void Add(OSD llsd)
{
value.Add(llsd);
}
public void Clear()
{
value.Clear();
}
public bool Contains(OSD llsd)
{
return value.Contains(llsd);
}
public bool Contains(string element)
{
for (int i = 0; i < value.Count; i++)
{
if (value[i].Type == OSDType.String && value[i].AsString() == element)
return true;
}
return false;
}
public void CopyTo(OSD[] array, int index)
{
throw new NotImplementedException();
}
public bool Remove(OSD llsd)
{
return value.Remove(llsd);
}
IEnumerator IEnumerable.GetEnumerator()
{
return value.GetEnumerator();
}
IEnumerator<OSD> IEnumerable<OSD>.GetEnumerator()
{
return value.GetEnumerator();
}
#endregion IList Implementation
}
public partial class OSDParser
{
const string LLSD_BINARY_HEADER = "<? llsd/binary ?>";
const string LLSD_XML_HEADER = "<llsd>";
const string LLSD_XML_ALT_HEADER = "<?xml";
const string LLSD_XML_ALT2_HEADER = "<? llsd/xml ?>";
public static OSD Deserialize(byte[] data)
{
string header = Encoding.ASCII.GetString(data, 0, data.Length >= 17 ? 17 : data.Length);
try
{
string uHeader = Encoding.UTF8.GetString(data, 0, data.Length >= 17 ? 17 : data.Length).TrimStart();
if (uHeader.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
uHeader.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
uHeader.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase))
{
return DeserializeLLSDXml(data);
}
}
catch { }
if (header.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase))
{
return DeserializeLLSDBinary(data);
}
else if (header.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
header.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
header.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase))
{
return DeserializeLLSDXml(data);
}
else
{
return DeserializeJson(Encoding.UTF8.GetString(data));
}
}
public static OSD Deserialize(string data)
{
if (data.StartsWith(LLSD_BINARY_HEADER, StringComparison.InvariantCultureIgnoreCase))
{
return DeserializeLLSDBinary(Encoding.UTF8.GetBytes(data));
}
else if (data.StartsWith(LLSD_XML_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
data.StartsWith(LLSD_XML_ALT_HEADER, StringComparison.InvariantCultureIgnoreCase) ||
data.StartsWith(LLSD_XML_ALT2_HEADER, StringComparison.InvariantCultureIgnoreCase))
{
return DeserializeLLSDXml(data);
}
else
{
return DeserializeJson(data);
}
}
public static OSD Deserialize(Stream stream)
{
if (stream.CanSeek)
{
byte[] headerData = new byte[14];
stream.Read(headerData, 0, 14);
stream.Seek(0, SeekOrigin.Begin);
string header = Encoding.ASCII.GetString(headerData);
if (header.StartsWith(LLSD_BINARY_HEADER))
return DeserializeLLSDBinary(stream);
else if (header.StartsWith(LLSD_XML_HEADER) || header.StartsWith(LLSD_XML_ALT_HEADER) || header.StartsWith(LLSD_XML_ALT2_HEADER))
return DeserializeLLSDXml(stream);
else
return DeserializeJson(stream);
}
else
{
throw new OSDException("Cannot deserialize structured data from unseekable streams");
}
}
}
}
| |
//
// MpqHuffman.cs
//
// Authors:
// Foole (fooleau@gmail.com)
//
// (C) 2006 Foole (fooleau@gmail.com)
// Based on code from StormLib by Ladislav Zezula
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
#if WITH_ZLIB
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
#endif
#if WITH_BZIP
using ICSharpCode.SharpZipLib.BZip2;
#endif
namespace MpqReader
{
/// <summary>
/// A Stream based class for reading a file from an MPQ file
/// </summary>
public class MpqStream : Stream
{
private Stream mStream;
private int mBlockSize;
private MpqBlock mBlock;
private uint[] mBlockPositions;
private uint mSeed1;
private long mPosition;
private byte[] mCurrentData;
private int mCurrentBlockIndex = -1;
private MpqStream()
{}
internal MpqStream(MpqArchive File, MpqBlock Block)
{
mBlock = Block;
mStream = File.BaseStream;
mBlockSize = File.BlockSize;
if (mBlock.IsCompressed) LoadBlockPositions();
}
// Compressed files start with an array of offsets to make seeking possible
private void LoadBlockPositions()
{
int blockposcount = (int)((mBlock.FileSize + mBlockSize - 1) / mBlockSize) + 1;
mBlockPositions = new uint[blockposcount];
lock(mStream)
{
mStream.Seek(mBlock.FilePos, SeekOrigin.Begin);
BinaryReader br = new BinaryReader(mStream);
for (int i = 0; i < blockposcount; i++)
mBlockPositions[i] = br.ReadUInt32();
}
uint blockpossize = (uint)blockposcount * 4;
// StormLib takes this to mean the data is encrypted
if (mBlockPositions[0] != blockpossize)
{
if (mSeed1 == 0)
{
mSeed1 = MpqArchive.DetectFileSeed(mBlockPositions, blockpossize);
if (mSeed1 == 0)
throw new Exception("Unable to determine encyption seed");
}
MpqArchive.DecryptBlock(mBlockPositions, mSeed1);
mSeed1++; // Add 1 because the first block is the offset list
}
}
private byte[] LoadBlock(int BlockIndex, int ExpectedLength)
{
uint offset;
int toread;
if (mBlock.IsCompressed)
{
offset = mBlockPositions[BlockIndex];
toread = (int)(mBlockPositions[BlockIndex + 1] - offset);
} else
{
offset = (uint)(BlockIndex * mBlockSize);
toread = ExpectedLength;
}
offset += mBlock.FilePos;
byte[] data = new byte[toread];
lock(mStream)
{
mStream.Seek(offset, SeekOrigin.Begin);
mStream.Read(data, 0, toread);
}
if (mBlock.IsEncrypted && mBlock.FileSize > 3)
{
if (mSeed1 == 0)
throw new Exception("Unable to determine encryption key");
MpqArchive.DecryptBlock(data, (uint)(mSeed1 + BlockIndex));
}
if (mBlock.IsCompressed && data.Length != ExpectedLength)
{
if ((mBlock.Flags & MpqFileFlags.CompressedMulti) != 0)
data = DecompressMulti(data, ExpectedLength);
else
data = PKDecompress(new MemoryStream(data), ExpectedLength);
}
return data;
}
#region Stream overrides
public override bool CanRead
{ get { return true; } }
public override bool CanSeek
{ get { return true; } }
public override bool CanWrite
{ get { return false; } }
public override long Length
{ get { return mBlock.FileSize; } }
public override long Position
{
get
{
return mPosition;
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
public override void Flush()
{
// NOP
}
public override long Seek(long Offset, SeekOrigin Origin)
{
long target;
switch (Origin)
{
case SeekOrigin.Begin:
target = Offset;
break;
case SeekOrigin.Current:
target = Position + Offset;
break;
case SeekOrigin.End:
target = Length + Offset;
break;
default:
throw new ArgumentException("Origin", "Invalid SeekOrigin");
}
if (target < 0)
throw new ArgumentOutOfRangeException("Attmpted to Seek before the beginning of the stream");
if (target >= Length)
throw new ArgumentOutOfRangeException("Attmpted to Seek beyond the end of the stream");
mPosition = target;
return mPosition;
}
public override void SetLength(long Value)
{
throw new NotSupportedException("SetLength is not supported");
}
public override int Read(byte[] Buffer, int Offset, int Count)
{
int toread = Count;
int readtotal = 0;
while (toread > 0)
{
int read = ReadInternal(Buffer, Offset, toread);
if (read == 0) break;
readtotal += read;
Offset += read;
toread -= read;
}
return readtotal;
}
private int ReadInternal(byte[] Buffer, int Offset, int Count)
{
BufferData();
int localposition = (int)(mPosition % mBlockSize);
int bytestocopy = Math.Min(mCurrentData.Length - localposition, Count);
if (bytestocopy <= 0) return 0;
Array.Copy(mCurrentData, localposition, Buffer, Offset, bytestocopy);
mPosition += bytestocopy;
return bytestocopy;
}
public override int ReadByte()
{
if (mPosition >= Length) return -1;
BufferData();
int localposition = (int)(mPosition % mBlockSize);
mPosition++;
return mCurrentData[localposition];
}
private void BufferData()
{
int requiredblock = (int)(mPosition / mBlockSize);
if (requiredblock != mCurrentBlockIndex)
{
int expectedlength = (int)Math.Min(Length - (requiredblock * mBlockSize), mBlockSize);
mCurrentData = LoadBlock(requiredblock, expectedlength);
mCurrentBlockIndex = requiredblock;
}
}
public override void Write(byte[] Buffer, int Offset, int Count)
{
throw new NotSupportedException("Writing is not supported");
}
#endregion Strem overrides
/* Compression types in order:
* 10 = BZip2
* 8 = PKLib
* 2 = ZLib
* 1 = Huffman
* 80 = IMA ADPCM Stereo
* 40 = IMA ADPCM Mono
*/
private static byte[] DecompressMulti(byte[] Input, int OutputLength)
{
Stream sinput = new MemoryStream(Input);
byte comptype = (byte)sinput.ReadByte();
#if WITH_BZIP
// BZip2
if ((comptype & 0x10) != 0)
{
byte[] result = BZip2Decompress(sinput, OutputLength);
comptype &= 0xEF;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
#endif
// PKLib
if ((comptype & 8) != 0)
{
byte[] result = PKDecompress(sinput, OutputLength);
comptype &= 0xF7;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
#if WITH_ZLIB
// ZLib
if ((comptype & 2) != 0)
{
byte[] result = ZlibDecompress(sinput, OutputLength);
comptype &= 0xFD;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
#endif
if ((comptype & 1) != 0)
{
byte[] result = MpqHuffman.Decompress(sinput);
comptype &= 0xfe;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
if ((comptype & 0x80) != 0)
{
byte[] result = MpqWavCompression.Decompress(sinput, 2);
comptype &= 0x7f;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
if ((comptype & 0x40) != 0)
{
byte[] result = MpqWavCompression.Decompress(sinput, 1);
comptype &= 0xbf;
if (comptype == 0) return result;
sinput = new MemoryStream(result);
}
throw new Exception(String.Format("Unhandled compression flags: 0x{0:X}", comptype));
}
#if WITH_BZIP
private static byte[] BZip2Decompress(Stream Data, int ExpectedLength)
{
MemoryStream output = new MemoryStream();
BZip2.Decompress(Data, output);
return output.ToArray();
}
#endif
private static byte[] PKDecompress(Stream Data, int ExpectedLength)
{
PKLibDecompress pk = new PKLibDecompress(Data);
return pk.Explode(ExpectedLength);
}
#if WITH_ZLIB
private static byte[] ZlibDecompress(Stream Data, int ExpectedLength)
{
// This assumes that Zlib won't be used in combination with another compression type
byte[] Output = new byte[ExpectedLength];
Stream s = new InflaterInputStream(Data);
int Offset = 0;
while(true)
{
int size = s.Read(Output, Offset, ExpectedLength);
if (size == 0) break;
Offset += size;
}
return Output;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
/// <summary>
/// Binds and validates models specified by a <see cref="ParameterDescriptor"/>.
/// </summary>
public class ParameterBinder
{
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly IModelBinderFactory _modelBinderFactory;
private readonly IObjectModelValidator _objectModelValidator;
/// <summary>
/// Initializes a new instance of <see cref="ParameterBinder"/>.
/// </summary>
/// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
/// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/>.</param>
/// <param name="validator">The <see cref="IObjectModelValidator"/>.</param>
/// <param name="mvcOptions">The <see cref="MvcOptions"/> accessor.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <remarks>The <paramref name="mvcOptions"/> parameter is currently ignored.</remarks>
public ParameterBinder(
IModelMetadataProvider modelMetadataProvider,
IModelBinderFactory modelBinderFactory,
IObjectModelValidator validator,
IOptions<MvcOptions> mvcOptions,
ILoggerFactory loggerFactory)
{
if (modelMetadataProvider == null)
{
throw new ArgumentNullException(nameof(modelMetadataProvider));
}
if (modelBinderFactory == null)
{
throw new ArgumentNullException(nameof(modelBinderFactory));
}
if (validator == null)
{
throw new ArgumentNullException(nameof(validator));
}
if (mvcOptions == null)
{
throw new ArgumentNullException(nameof(mvcOptions));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_modelMetadataProvider = modelMetadataProvider;
_modelBinderFactory = modelBinderFactory;
_objectModelValidator = validator;
Logger = loggerFactory.CreateLogger(GetType());
}
/// <summary>
/// The <see cref="ILogger"/> used for logging in this binder.
/// </summary>
protected ILogger Logger { get; }
/// <summary>
/// Binds a model specified by <paramref name="parameter"/> using <paramref name="value"/> as the initial value.
/// </summary>
/// <param name="actionContext">The <see cref="ActionContext"/>.</param>
/// <param name="modelBinder">The <see cref="IModelBinder"/>.</param>
/// <param name="valueProvider">The <see cref="IValueProvider"/>.</param>
/// <param name="parameter">The <see cref="ParameterDescriptor"/></param>
/// <param name="metadata">The <see cref="ModelMetadata"/>.</param>
/// <param name="value">The initial model value.</param>
/// <returns>The result of model binding.</returns>
public virtual Task<ModelBindingResult> BindModelAsync(
ActionContext actionContext,
IModelBinder modelBinder,
IValueProvider valueProvider,
ParameterDescriptor parameter,
ModelMetadata metadata,
object? value)
=> BindModelAsync(actionContext, modelBinder, valueProvider, parameter, metadata, value, container: null).AsTask();
/// <summary>
/// Binds a model specified by <paramref name="parameter"/> using <paramref name="value"/> as the initial value.
/// </summary>
/// <param name="actionContext">The <see cref="ActionContext"/>.</param>
/// <param name="modelBinder">The <see cref="IModelBinder"/>.</param>
/// <param name="valueProvider">The <see cref="IValueProvider"/>.</param>
/// <param name="parameter">The <see cref="ParameterDescriptor"/></param>
/// <param name="metadata">The <see cref="ModelMetadata"/>.</param>
/// <param name="value">The initial model value.</param>
/// <param name="container">The container for the model.</param>
/// <returns>The result of model binding.</returns>
public virtual async ValueTask<ModelBindingResult> BindModelAsync(
ActionContext actionContext,
IModelBinder modelBinder,
IValueProvider valueProvider,
ParameterDescriptor parameter,
ModelMetadata metadata,
object? value,
object? container)
{
if (actionContext == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
if (modelBinder == null)
{
throw new ArgumentNullException(nameof(modelBinder));
}
if (valueProvider == null)
{
throw new ArgumentNullException(nameof(valueProvider));
}
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
Logger.AttemptingToBindParameterOrProperty(parameter, metadata);
if (parameter.BindingInfo?.RequestPredicate?.Invoke(actionContext) == false)
{
Logger.ParameterBinderRequestPredicateShortCircuit(parameter, metadata);
return ModelBindingResult.Failed();
}
var modelBindingContext = DefaultModelBindingContext.CreateBindingContext(
actionContext,
valueProvider,
metadata,
parameter.BindingInfo,
parameter.Name);
modelBindingContext.Model = value;
var parameterModelName = parameter.BindingInfo?.BinderModelName ?? metadata.BinderModelName;
if (parameterModelName != null)
{
// The name was set explicitly, always use that as the prefix.
modelBindingContext.ModelName = parameterModelName;
}
else if (modelBindingContext.ValueProvider.ContainsPrefix(parameter.Name))
{
// We have a match for the parameter name, use that as that prefix.
modelBindingContext.ModelName = parameter.Name;
}
else
{
// No match, fallback to empty string as the prefix.
modelBindingContext.ModelName = string.Empty;
}
await modelBinder.BindModelAsync(modelBindingContext);
Logger.DoneAttemptingToBindParameterOrProperty(parameter, metadata);
var modelBindingResult = modelBindingContext.Result;
if (_objectModelValidator is ObjectModelValidator baseObjectValidator)
{
Logger.AttemptingToValidateParameterOrProperty(parameter, metadata);
EnforceBindRequiredAndValidate(
baseObjectValidator,
actionContext,
parameter,
metadata,
modelBindingContext,
modelBindingResult,
container);
Logger.DoneAttemptingToValidateParameterOrProperty(parameter, metadata);
}
else
{
// For legacy implementations (which directly implemented IObjectModelValidator), fall back to the
// back-compatibility logic. In this scenario, top-level validation attributes will be ignored like
// they were historically.
if (modelBindingResult.IsModelSet)
{
_objectModelValidator.Validate(
actionContext,
modelBindingContext.ValidationState,
modelBindingContext.ModelName,
modelBindingResult.Model);
}
}
return modelBindingResult;
}
private void EnforceBindRequiredAndValidate(
ObjectModelValidator baseObjectValidator,
ActionContext actionContext,
ParameterDescriptor parameter,
ModelMetadata metadata,
ModelBindingContext modelBindingContext,
ModelBindingResult modelBindingResult,
object? container)
{
RecalculateModelMetadata(parameter, modelBindingResult, ref metadata);
if (!modelBindingResult.IsModelSet && metadata.IsBindingRequired)
{
// Enforce BindingBehavior.Required (e.g., [BindRequired])
var modelName = modelBindingContext.FieldName;
var message = metadata.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(modelName);
actionContext.ModelState.TryAddModelError(modelName, message);
}
else if (modelBindingResult.IsModelSet)
{
// Enforce any other validation rules
baseObjectValidator.Validate(
actionContext,
modelBindingContext.ValidationState,
modelBindingContext.ModelName,
modelBindingResult.Model,
metadata,
container);
}
else if (metadata.IsRequired)
{
// We need to special case the model name for cases where a 'fallback' to empty
// prefix occurred but binding wasn't successful. For these cases there will be no
// entry in validation state to match and determine the correct key.
//
// See https://github.com/aspnet/Mvc/issues/7503
//
// This is to avoid adding validation errors for an 'empty' prefix when a simple
// type fails to bind. The fix for #7503 uncovered this issue, and was likely the
// original problem being worked around that regressed #7503.
var modelName = modelBindingContext.ModelName;
if (string.IsNullOrEmpty(modelBindingContext.ModelName) &&
parameter.BindingInfo?.BinderModelName == null)
{
// If we get here then this is a fallback case. The model name wasn't explicitly set
// and we ended up with an empty prefix.
modelName = modelBindingContext.FieldName;
}
// Run validation, we expect this to validate [Required].
baseObjectValidator.Validate(
actionContext,
modelBindingContext.ValidationState,
modelName,
modelBindingResult.Model,
metadata,
container);
}
}
private void RecalculateModelMetadata(
ParameterDescriptor parameter,
ModelBindingResult modelBindingResult,
ref ModelMetadata metadata)
{
// Attempt to recalculate ModelMetadata for top level parameters and properties using the actual
// model type. This ensures validation uses a combination of top-level validation metadata
// as well as metadata on the actual, rather than declared, model type.
if (!modelBindingResult.IsModelSet ||
modelBindingResult.Model == null ||
_modelMetadataProvider is not ModelMetadataProvider modelMetadataProvider)
{
return;
}
var modelType = modelBindingResult.Model.GetType();
if (parameter is IParameterInfoParameterDescriptor parameterInfoParameter)
{
var parameterInfo = parameterInfoParameter.ParameterInfo;
if (modelType != parameterInfo.ParameterType)
{
metadata = modelMetadataProvider.GetMetadataForParameter(parameterInfo, modelType);
}
}
else if (parameter is IPropertyInfoParameterDescriptor propertyInfoParameter)
{
var propertyInfo = propertyInfoParameter.PropertyInfo;
if (modelType != propertyInfo.PropertyType)
{
metadata = modelMetadataProvider.GetMetadataForProperty(propertyInfo, modelType);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class UnionTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
var q2 = from x2 in new int?[] { 1, 9, null, 4 }
select x2;
Assert.Equal(q1.Union(q2), q1.Union(q2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
var q2 = from x2 in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" }
select x2;
Assert.Equal(q1.Union(q2), q1.Union(q2));
}
[Fact]
public void BothEmpty()
{
int[] first = { };
int[] second = { };
Assert.Empty(first.Union(second));
}
[Fact]
public void CustomComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "Charlie" };
var comparer = new AnagramEqualityComparer();
Assert.Equal(expected, first.Union(second, comparer), comparer);
}
[Fact]
public void FirstNullCustomComparer()
{
string[] first = null;
string[] second = { "ttaM", "Charlie", "Bbo" };
var ane = Assert.Throws<ArgumentNullException>("first", () => first.Union(second, new AnagramEqualityComparer()));
}
[Fact]
public void SecondNullCustomComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = null;
var ane = Assert.Throws<ArgumentNullException>("second", () => first.Union(second, new AnagramEqualityComparer()));
}
[Fact]
public void FirstNullNoComparer()
{
string[] first = null;
string[] second = { "ttaM", "Charlie", "Bbo" };
var ane = Assert.Throws<ArgumentNullException>("first", () => first.Union(second));
}
[Fact]
public void SecondNullNoComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = null;
var ane = Assert.Throws<ArgumentNullException>("second", () => first.Union(second));
}
[Fact]
public void SingleNullWithEmpty()
{
string[] first = { null };
string[] second = new string[0];
string[] expected = { null };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void NullEmptyStringMix()
{
string[] first = { null, null, string.Empty };
string[] second = { null, null };
string[] expected = { null, string.Empty };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void DoubleNullWithEmpty()
{
string[] first = { null, null };
string[] second = new string[0];
string[] expected = { null };
Assert.Equal(expected, first.Union(second, EqualityComparer<string>.Default));
}
[Fact]
public void EmptyWithNonEmpty()
{
int[] first = { };
int[] second = { 2, 4, 5, 3, 2, 3, 9 };
int[] expected = { 2, 4, 5, 3, 9 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void NonEmptyWithEmpty()
{
int[] first = { 2, 4, 5, 3, 2, 3, 9 };
int[] second = { };
int[] expected = { 2, 4, 5, 3, 9 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void CommonElementsShared()
{
int[] first = { 1, 2, 3, 4, 5, 6 };
int[] second = { 6, 7, 7, 7, 8, 1 };
int[] expected = { 1, 2, 3, 4, 5, 6, 7, 8 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void SameElementRepeated()
{
int[] first = { 1, 1, 1, 1, 1, 1 };
int[] second = { 1, 1, 1, 1, 1, 1 };
int[] expected = { 1 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void RepeatedElementsWithSingleElement()
{
int[] first = { 1, 2, 3, 5, 3, 6 };
int[] second = { 7 };
int[] expected = { 1, 2, 3, 5, 6, 7 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void SingleWithAllUnique()
{
int?[] first = { 2 };
int?[] second = { 3, null, 4, 5 };
int?[] expected = { 2, 3, null, 4, 5 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void EachHasRepeatsBetweenAndAmongstThemselves()
{
int?[] first = { 1, 2, 3, 4, null, 5, 1 };
int?[] second = { 6, 2, 3, 4, 5, 6 };
int?[] expected = { 1, 2, 3, 4, null, 5, 6 };
Assert.Equal(expected, first.Union(second));
}
[Fact]
public void NullEqualityComparer()
{
string[] first = { "Bob", "Robert", "Tim", "Matt", "miT" };
string[] second = { "ttaM", "Charlie", "Bbo" };
string[] expected = { "Bob", "Robert", "Tim", "Matt", "miT", "ttaM", "Charlie", "Bbo" };
Assert.Equal(expected, first.Union(second, null));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Union(Enumerable.Range(0, 3));
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Diagnostics;
using System.Security.Principal;
using Xunit;
namespace System.ServiceProcess.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(10);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe";
var process = new Process();
process.StartInfo.FileName = serviceExecutable;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString());
}
}
}
[OuterLoop(/* Modifies machine state */)]
public class ServiceControllerTests : IDisposable
{
private const int ExpectedDependentServiceCount = 3;
private static readonly Lazy<bool> s_runningWithElevatedPrivileges = new Lazy<bool>(
() => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator));
private readonly ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
private static bool RunningWithElevatedPrivileges
{
get { return s_runningWithElevatedPrivileges.Value; }
}
private void AssertExpectedProperties(ServiceController testServiceController)
{
Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName);
Assert.Equal(_testService.TestMachineName, testServiceController.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName_ToUpper()
{
var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant());
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
AssertExpectedProperties(controller);
Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Start_NullArg_ThrowsArgumentNullException()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<ArgumentNullException>("args[0]", () => controller.Start(new string[] { null } ));
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void GetServices_FindSelf()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
AssertExpectedProperties(service);
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Dependencies()
{
// The test service creates a number of dependent services, each of which is depended on
// by all the services created after it.
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i);
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
// Assert that this dependent service is depended on by all the test services created after it
Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length);
for (int j = i + 1; j < ExpectedDependentServiceCount; j++)
{
AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
// Assert that the dependent service depends on the main test service
AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName);
// Assert that this dependent service depends on all the test services created before it
Assert.Equal(i + 1, dependent.ServicesDependedOn.Length);
for (int j = i - 1; j >= 0; j--)
{
AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceStartMode.Manual, controller.StartType);
// Check for the startType of the dependent services.
for (int i = 0; i < controller.DependentServices.Length; i++)
{
Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
{
var dependent = FindService(controller.DependentServices, serviceName, displayName);
Assert.NotNull(dependent);
return dependent;
}
private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName)
{
var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName);
Assert.NotNull(dependency);
return dependency;
}
private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName)
{
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName && service.DisplayName == displayName)
{
return service;
}
}
return null;
}
}
}
| |
// uncomment to track garbage collection of widgets
//#define TRACK_GC
using System;
using System.Globalization;
using System.Linq.Expressions;
namespace Eto
{
/// <summary>
/// Interface for widgets that have a control object
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IControlObjectSource
{
/// <summary>
/// Gets the control object for this widget
/// </summary>
/// <value>The control object for the widget</value>
object ControlObject { get; }
}
/// <summary>
/// Interface for widgets that have a handler
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IHandlerSource
{
/// <summary>
/// Gets the platform handler object for the widget
/// </summary>
/// <value>The handler for the widget</value>
object Handler { get; }
}
/// <summary>
/// Interface to get the callback object for a widget
/// </summary>
public interface ICallbackSource
{
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <remarks>
/// The callback should implement the parent class' callback interface so that there only needs
/// to be a single callback for the entire hierarchy.
///
/// This should return a static instance to avoid having overhead for each instance of your widget.
/// </remarks>
/// <returns>The callback instance to use for this widget</returns>
object Callback { get; }
}
/// <summary>
/// Base widget class for all objects requiring a platform-specific implementation
/// </summary>
/// <remarks>
/// The Widget is the base of all abstracted objects that have platform-specific implementations.
///
/// To implement the handler for a widget, use the <see cref="Eto.WidgetHandler{TWidget}"/> as the base class.
/// </remarks>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[RuntimeNameProperty("ID")]
public abstract class Widget : IHandlerSource, IDisposable, ICallbackSource, ICloneable
{
IHandler WidgetHandler { get { return Handler as IHandler; } }
/// <summary>
/// Gets the platform that was used to create the <see cref="Handler"/> for this widget
/// </summary>
/// <remarks>
/// This gets set to the current <see cref="Eto.Platform.Instance"/> during the construction of the object
/// </remarks>
public Platform Platform { get; private set; }
/// <summary>
/// Gets the platform-specific handler for this widget
/// </summary>
public object Handler { get; internal set; }
/// <summary>
/// Gets the native platform-specific handle for integration purposes
/// </summary>
/// <value>The native handle.</value>
public IntPtr NativeHandle
{
get { return WidgetHandler.NativeHandle; }
}
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <remarks>
/// The callback should implement the parent class' <see cref="ICallback"/> interface so that there only needs
/// to be a single callback for the entire hierarchy.
///
/// This should return a static instance to avoid having overhead for each instance of your control.
/// </remarks>
/// <returns>The callback instance to use for this widget</returns>
protected virtual object GetCallback() { return null; }
object ICallbackSource.Callback { get { return GetCallback(); } }
/// <summary>>
/// Base callback interface for all widgets
/// </summary>
public interface ICallback
{
}
/// <summary>
/// Handler interface for the <see cref="Widget"/> class
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IHandler
{
/// <summary>
/// Gets or sets an ID for the widget
/// </summary>
/// <remarks>
/// Some platforms may use this to identify controls (e.g. web)
/// </remarks>
string ID { get; set; }
/// <summary>
/// Gets the widget this handler is implemented for
/// </summary>
Widget Widget { get; set; }
/// <summary>
/// Gets the native platform-specific handle for integration purposes
/// </summary>
/// <value>The native handle.</value>
IntPtr NativeHandle { get; }
/// <summary>
/// Called after the widget is constructed
/// </summary>
/// <remarks>
/// This gets called automatically after the control is constructed and the <see cref="Widget"/> and <see cref="Platform"/> properties are set.
/// When the handler has specialized construction methods, then the <see cref="AutoInitializeAttribute"/> can be used to disable automatic
/// initialization. In this case, it is the responsibility of the subclass to call <see cref="Eto.Widget.Initialize()"/>
/// </remarks>
void Initialize();
/// <summary>
/// Called to handle a specific event
/// </summary>
/// <remarks>
/// Most events are late bound by this method. Instead of wiring all events, this
/// will be called with an event string that is defined by the control.
///
/// This is called automatically when attaching to events, but must be called manually
/// when users of the control only override the event's On... method.
/// </remarks>
/// <param name="id">ID of the event to handle</param>
/// <param name = "defaultEvent">True if the event is default (e.g. overridden or via an event handler subscription)</param>
void HandleEvent(string id, bool defaultEvent = false);
}
/// <summary>
/// Registers the event for overridding
/// </summary>
/// <remarks>
/// This is used to register an event that will be automatically hooked up when a derived class overrides the
/// event method.
/// This should be called in the static constructor of your class.
/// </remarks>
/// <example>
/// Shows a custom control with an event:
/// <code>
/// public class MyEtoControl : Eto.Forms.Control
/// {
/// public const string MySomethingEvent = "MyEtoControl.MySomethingEvent";
///
/// public event EventHandler<EventArgs> MySomething
/// {
/// add { Properties.AddHandlerEvent(MySomethingEvent, value); }
/// remove { Properties.RemoveEvent(MySomethingEvent, value); }
/// }
///
/// protected virtual void OnMySomething(EventArgs e)
/// {
/// Properties.TriggerEvent(MySomethingEvent, this, e);
/// }
///
/// static MyEtoControl()
/// {
/// RegisterEvent<MyEtoControl>(c => c.OnMySomething(null), MySomethingEvent);
/// }
/// }
/// </code>
/// </example>
/// <param name="method">Expression to call the method that raises your event</param>
/// <param name="identifier">Identifier of the event</param>
/// <typeparam name="T">Your object type</typeparam>
protected static void RegisterEvent<T>(Expression<Action<T>> method, string identifier)
{
EventLookup.Register(method, identifier);
}
#if TRACK_GC
~Widget()
{
Dispose(false);
}
#endif
private void InitializeHandler()
{
var platform = Platform.Instance;
if (platform == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Platform instance is null. Have you created your application?"));
var info = platform.FindHandler(GetType());
if (info == null)
throw new ArgumentOutOfRangeException(string.Format(CultureInfo.CurrentCulture, "Type for '{0}' could not be found in this platform", GetType().FullName));
Handler = info.Instantiator();
Platform = platform;
var widgetHandler = this.Handler as IHandler;
if (widgetHandler != null)
{
widgetHandler.Widget = this;
}
if (info.Initialize)
Initialize();
}
/// <summary>
/// Initializes a new instance of the Widget class
/// </summary>
protected Widget()
{
InitializeHandler();
}
/// <summary>
/// Clones this control
/// </summary>
public object Clone()
{
Widget widget = (Widget) Activator.CreateInstance(GetType());
widget.InitializeHandler();
widget.CloneProperties(this);
Platform.Instance.TriggerWidgetCloned(new WidgetClonedEventArgs(widget, this));
return widget;
}
/// <summary>
/// Clones properties for this widget
/// </summary>
protected virtual void CloneProperties(Widget widgetToClone)
{
ID = widgetToClone.ID; // Copy / Clone ?
string style = widgetToClone.Style;
if (string.IsNullOrEmpty(style) == false)
{
Style = style;
}
}
/// <summary>
/// Initializes a new instance of the Widget class
/// </summary>
/// <param name="handler">Handler to assign to this widget for its implementation</param>
protected Widget(IHandler handler)
{
Handler = handler;
Platform = Platform.Instance;
if (handler != null)
{
handler.Widget = this; // tell the handler who we are
}
Initialize();
}
/// <summary>
/// Initializes the widget handler
/// </summary>
/// <remarks>
/// This is typically called from the constructor after all of the logic is completed to construct
/// the object.
///
/// If your handler interface has the <see cref="AutoInitializeAttribute"/> set to false, then you are responsible
/// for calling this method in your constructor after calling the creation method on your custom handler.
/// </remarks>
protected void Initialize()
{
var handler = WidgetHandler;
if (handler != null)
handler.Initialize();
EventLookup.HookupEvents(this);
Platform.Instance.TriggerWidgetCreated(new WidgetCreatedEventArgs(this));
}
PropertyStore properties;
/// <summary>
/// Gets the dictionary of properties for this widget
/// </summary>
public PropertyStore Properties
{
get { return properties ?? (properties = new PropertyStore(this)); }
}
/// <summary>
/// Gets or sets the ID of this widget
/// </summary>
public string ID
{
get { return WidgetHandler.ID; }
set { WidgetHandler.ID = value; }
}
/// <summary>
/// Gets or sets the style of this widget
/// </summary>
/// <remarks>
/// Styles allow you to attach custom platform-specific logic to a widget.
/// In your platform-specific assembly, use <see cref="M:Style.Add{H}(string, StyleHandler{H})"/>
/// to add the style logic with the same id.
/// </remarks>
/// <example>
/// <code><![CDATA[
/// // in your UI
/// var control = new Button { Style = "mystyle" };
///
/// // in your platform assembly
/// using Eto.Mac.Forms.Controls;
///
/// Styles.AddHandler<ButtonHandler>("mystyle", handler => {
/// // this is where you can use handler.Control to set properties, handle events, etc.
/// handler.Control.BezelStyle = NSBezelStyle.SmallSquare;
/// });
/// ]]></code>
/// </example>
public string Style
{
get { return Properties.Get<string>(StyleKey); }
set
{
var style = Style;
if (style != value)
{
Properties[StyleKey] = value;
OnStyleChanged(EventArgs.Empty);
}
}
}
static readonly object StyleKey = new object();
#region Events
static readonly object StyleChangedKey = new object();
/// <summary>
/// Occurs when the <see cref="Widget.Style"/> property has changed
/// </summary>
public event EventHandler<EventArgs> StyleChanged
{
add { Properties.AddEvent(StyleChangedKey, value); }
remove { Properties.RemoveEvent(StyleChangedKey, value); }
}
/// <summary>
/// Handles when the <see cref="Style"/> is changed.
/// </summary>
protected virtual void OnStyleChanged(EventArgs e)
{
Eto.Style.OnStyleWidget(this);
Properties.TriggerEvent(StyleChangedKey, this, e);
}
#endregion
/// <summary>
/// Gets the instance of the platform-specific object
/// </summary>
/// <remarks>
/// This can sometimes be useful to get the platform-specific object.
/// Some handlers may not have any backing object for its functionality, so this may be null.
///
/// It is more preferred to use the <see cref="Widget.Handler"/> and cast that to the platform-specific
/// handler class which can give you additional methods and helpers to do common tasks.
///
/// For example, the <see cref="Forms.Application"/> object's handler for OS X has a AddFullScreenMenuItem
/// property to specify if you want full screen support in your app.
/// </remarks>
public object ControlObject
{
get
{
var controlObjectSource = Handler as IControlObjectSource;
return controlObjectSource != null ? controlObjectSource.ControlObject : null;
}
}
/// <summary>
/// Attaches the specified late-bound event to the control to be handled
/// </summary>
/// <remarks>
/// This needs to be called when you want to override the On... methods instead of attaching
/// to the associated event.
/// </remarks>
/// <example>
/// <code><![CDATA[
/// // this will call HandleEvent automatically
/// var textBox = new TextBox ();
/// textBox.TextChanged += MyTextChangedHandler;
///
/// // must call HandleEvent when overriding OnTextChanged
/// public class MyTextBox : TextBox
/// {
/// public MyTextBox()
/// {
/// HandleEvent (TextChangedEvent);
/// }
///
/// protected override void OnTextChanged (EventArgs e)
/// {
/// // your logic
/// }
/// }
///
/// ]]></code>
/// </example>
/// <param name="id">ID of the event to handle. Usually a constant in the form of [Control].[EventName]Event (e.g. TextBox.TextChangedEvent)</param>
internal void HandleEvent(string id)
{
WidgetHandler.HandleEvent(id);
}
/// <summary>
/// Disposes of this widget, supressing the finalizer
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Handles the disposal of this widget
/// </summary>
/// <param name="disposing">True if the caller called <see cref="Dispose()"/> manually, false if being called from a finalizer</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var handler = Handler as IDisposable;
if (handler != null)
handler.Dispose();
Handler = null;
}
#if TRACK_GC
System.Diagnostics.Debug.WriteLine ("{0}: {1}", disposing ? "Dispose" : "GC", GetType().Name);
#endif
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Azure.Cosmos.Table.Protocol;
using Microsoft.Azure.Cosmos.Tables.SharedFiles;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Clustering.AzureStorage;
using Orleans.TestingHost.Utils;
using TestExtensions;
using Xunit;
namespace Tester.AzureUtils
{
[TestCategory("Azure"), TestCategory("Storage")]
public class AzureTableDataManagerTests : AzureStorageBasicTests
{
private string PartitionKey;
private UnitTestAzureTableDataManager manager;
private UnitTestAzureTableData GenerateNewData()
{
return new UnitTestAzureTableData("JustData", PartitionKey, "RK-" + Guid.NewGuid());
}
public AzureTableDataManagerTests()
{
TestingUtils.ConfigureThreadPoolSettingsForStorageTests();
// Pre-create table, if required
manager = new UnitTestAzureTableDataManager();
PartitionKey = "PK-AzureTableDataManagerTests-" + Guid.NewGuid();
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_CreateTableEntryAsync()
{
var data = GenerateNewData();
await manager.CreateTableEntryAsync(data);
try
{
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.CreateTableEntryAsync(data2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Creating an already existing entry."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpsertTableEntryAsync()
{
var data = GenerateNewData();
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.UpsertTableEntryAsync(data2);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTableEntryAsync()
{
var data = GenerateNewData();
try
{
await manager.UpdateTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
await manager.UpsertTableEntryAsync(data);
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal(data.StringData, tuple.Item1.StringData);
var data2 = data.Clone();
data2.StringData = "NewData";
string eTag1 = await manager.UpdateTableEntryAsync(data2, AzureTableUtils.ANY_ETAG);
tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey);
Assert.Equal(data2.StringData, tuple.Item1.StringData);
var data3 = data.Clone();
data3.StringData = "EvenNewerData";
_ = await manager.UpdateTableEntryAsync(data3, eTag1);
tuple = await manager.ReadSingleTableEntryAsync(data3.PartitionKey, data3.RowKey);
Assert.Equal(data3.StringData, tuple.Item1.StringData);
try
{
string eTag3 = await manager.UpdateTableEntryAsync(data3.Clone(), eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_DeleteTableAsync()
{
var data = GenerateNewData();
try
{
await manager.DeleteTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Delete before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
await manager.DeleteTableEntryAsync(data, eTag1);
try
{
await manager.DeleteTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Deleting an already deleted item."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_MergeTableAsync()
{
var data = GenerateNewData();
try
{
await manager.MergeTableEntryAsync(data, AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Merge before create."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string eTag1 = await manager.UpsertTableEntryAsync(data);
var data2 = data.Clone();
data2.StringData = "NewData";
await manager.MergeTableEntryAsync(data2, eTag1);
try
{
await manager.MergeTableEntryAsync(data, eTag1);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Equal("NewData", tuple.Item1.StringData);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_ReadSingleTableEntryAsync()
{
var data = GenerateNewData();
var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey);
Assert.Null(tuple);
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureTableUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Upadte item 2 before created it."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
}
try
{
await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureTableUtils.ANY_ETAG);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode); // "Inserting an already existing item 1 AND wring eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.Conflict, httpStatusCode);
Assert.Equal("EntityAlreadyExists", restStatus);
};
}
[SkippableFact, TestCategory("Functional")]
public async Task AzureTableDataManager_UpdateTwoTableEntriesConditionallyAsync()
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
var data1 = GenerateNewData();
var data2 = GenerateNewData();
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, AzureTableUtils.ANY_ETAG, data2, AzureTableUtils.ANY_ETAG);
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode); // "Update before insert."
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.NotFound, httpStatusCode);
Assert.Equal(StorageErrorCodeStrings.ResourceNotFound, restStatus);
}
string etag = await manager.CreateTableEntryAsync(data2.Clone());
var tuple1 = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag);
_ = await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
try
{
await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2);
Assert.True(false, "Should have thrown StorageException.");
}
catch(StorageException exc)
{
Assert.Equal((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode); // "Wrong eTag"
HttpStatusCode httpStatusCode;
string restStatus;
AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true);
Assert.Equal(HttpStatusCode.PreconditionFailed, httpStatusCode);
Assert.True(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied
|| restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// A shim around LLUDPServer that implements the IClientNetworkServer interface
/// </summary>
public sealed class LLUDPServerShim : IClientNetworkServer
{
LLUDPServer m_udpServer;
public LLUDPServerShim()
{
}
public void Initialize(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource)
{
m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource);
}
public void NetworkStop()
{
m_udpServer.Stop();
}
public void AddScene(IScene scene)
{
m_udpServer.AddScene(scene);
}
public bool HandlesRegion(Location x)
{
return m_udpServer.HandlesRegion(x);
}
public void Start()
{
m_udpServer.Start();
}
public void Stop()
{
m_udpServer.Stop();
}
}
/// <summary>
/// The LLUDP server for a region. This handles incoming and outgoing
/// packets for all UDP connections to the region
/// </summary>
public class LLUDPServer : OpenSimUDPBase
{
/// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
public const int MTU = 1400;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>The measured resolution of Environment.TickCount</summary>
public readonly float TickCountResolution;
/// <summary>Number of prim updates to put on the queue each time the
/// OnQueueEmpty event is triggered for updates</summary>
public readonly int PrimUpdatesPerCallback;
/// <summary>Number of texture packets to put on the queue each time the
/// OnQueueEmpty event is triggered for textures</summary>
public readonly int TextureSendLimit;
/// <summary>Handlers for incoming packets</summary>
//PacketEventDictionary packetEvents = new PacketEventDictionary();
/// <summary>Incoming packets that are awaiting handling</summary>
private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
/// <summary></summary>
//private UDPClientCollection m_clients = new UDPClientCollection();
/// <summary>Bandwidth throttle for this UDP server</summary>
protected TokenBucket m_throttle;
/// <summary>Bandwidth throttle rates for this UDP server</summary>
protected ThrottleRates m_throttleRates;
/// <summary>Reference to the scene this UDP server is attached to</summary>
protected Scene m_scene;
/// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
private Location m_location;
/// <summary>The size of the receive buffer for the UDP socket. This value
/// is passed up to the operating system and used in the system networking
/// stack. Use zero to leave this value as the default</summary>
private int m_recvBufferSize;
/// <summary>Flag to process packets asynchronously or synchronously</summary>
private bool m_asyncPacketHandling;
/// <summary>Tracks whether or not a packet was sent each round so we know
/// whether or not to sleep</summary>
private bool m_packetSent;
/// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
private int m_elapsedMSSinceLastStatReport = 0;
/// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
private int m_tickLastOutgoingPacketHandler;
/// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
private int m_elapsedMSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed100MSOutgoingPacketHandler;
/// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
private int m_elapsed500MSOutgoingPacketHandler;
/// <summary>Flag to signal when clients should check for resends</summary>
private bool m_resendUnacked;
/// <summary>Flag to signal when clients should send ACKs</summary>
private bool m_sendAcks;
/// <summary>Flag to signal when clients should send pings</summary>
private bool m_sendPing;
private int m_defaultRTO = 0;
private int m_maxRTO = 0;
//create a 50 MB (max) buffer pool
private ByteBufferPool _bufferPool = new ByteBufferPool(50 * 1024 * 1024, new int[] { 64, 128, 256, 512, LLUDPServer.MTU });
public OpenMetaverse.Interfaces.IByteBufferPool ByteBufferPool
{
get
{
return _bufferPool;
}
}
private const int ZERO_BUFFER_SZ = 4096;
//create an 8MB (max) zero buffer pool
private ByteBufferPool _zeroBufferPool = new ByteBufferPool(8 * 1024 * 1024, new int[] { ZERO_BUFFER_SZ });
public Socket Server { get { return null; } }
public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource)
: base(listenIP, (int)port)
{
#region Environment.TickCount Measurement
// Measure the resolution of Environment.TickCount
TickCountResolution = 0f;
for (int i = 0; i < 5; i++)
{
int start = Environment.TickCount;
int now = start;
while (now == start)
now = Environment.TickCount;
TickCountResolution += (float)(now - start) * 0.2f;
}
m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
TickCountResolution = (float)Math.Ceiling(TickCountResolution);
#endregion Environment.TickCount Measurement
int sceneThrottleBps = 0;
IConfig config = configSource.Configs["ClientStack.LindenUDP"];
if (config != null)
{
m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 20);
TextureSendLimit = config.GetInt("TextureSendLimit", 20);
m_defaultRTO = config.GetInt("DefaultRTO", 0);
m_maxRTO = config.GetInt("MaxRTO", 0);
}
else
{
PrimUpdatesPerCallback = 20;
TextureSendLimit = 20;
}
#region BinaryStats
config = configSource.Configs["Statistics.Binary"];
m_shouldCollectStats = false;
if (config != null)
{
if (config.Contains("enabled") && config.GetBoolean("enabled"))
{
if (config.Contains("collect_packet_headers"))
m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
if (config.Contains("packet_headers_period_seconds"))
{
binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
}
if (config.Contains("stats_dir"))
{
binStatsDir = config.GetString("stats_dir");
}
}
else
{
m_shouldCollectStats = false;
}
}
#endregion BinaryStats
m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
m_throttleRates = new ThrottleRates(configSource);
}
public void Start()
{
if (m_scene == null)
throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
base.Start(m_recvBufferSize, m_asyncPacketHandling);
// Start the packet processing threads
Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
public new void Stop()
{
m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
base.Stop();
}
public void AddScene(IScene scene)
{
if (m_scene != null)
{
m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
return;
}
if (!(scene is Scene))
{
m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
return;
}
m_scene = (Scene)scene;
m_location = new Location(m_scene.RegionInfo.RegionHandle);
}
public bool HandlesRegion(Location x)
{
return x == m_location;
}
/*public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
{
// CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}
else
{
byte[] data = packet.ToBytes();
m_scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
}
);
}
}*/
/// <summary>
/// Maximum size of a split packet
/// </summary>
private long MAX_PACKET_SIZE = 100 * 1024 * 1024;
public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting)
{
// CoarseLocationUpdate packets cannot be split in an automated way
if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
{
byte[][] datas;
int[] sizes;
if (packet.UsesBufferPooling)
{
datas = packet.ToBytesMultiple(_bufferPool, out sizes);
}
else
{
datas = packet.ToBytesMultiple();
sizes = new int[datas.Length];
for (int i = 0; i < datas.Length; i++)
{
sizes[i] = datas[i].Length;
}
}
//add up all the sizes of the data going out for this packet. if it is more than MAX_PACKET_SIZE
//drop it and log it
long totalSz = 0;
foreach (int size in sizes)
{
totalSz += size;
}
if (totalSz > MAX_PACKET_SIZE)
{
m_log.ErrorFormat("[LLUDPSERVER] Not sending HUGE packet Type:{0}, Size: {1}", packet.Type, totalSz);
datas = null;
return;
}
int packetCount = datas.Length;
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
SendPacketData(udpClient, data, sizes[i], packet.Type, category, packet.UsesBufferPooling);
}
}
else
{
byte[] data;
int size = 0;
if (packet.UsesBufferPooling)
{
data = packet.ToBytes(_bufferPool, ref size);
}
else
{
data = packet.ToBytes();
size = data.Length;
}
if (size > MAX_PACKET_SIZE)
{
m_log.ErrorFormat("[LLUDPSERVER] Not sending HUGE packet Type:{0}, Size: {1}", packet.Type, size);
data = null;
return;
}
SendPacketData(udpClient, data, size, packet.Type, category, packet.UsesBufferPooling);
}
}
public void SendPacketData(LLUDPClient udpClient, byte[] data, int dataLength, PacketType type,
ThrottleOutPacketType category, bool bufferAcquiredFromPool)
{
bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
bool zeroCoded = false;
byte[] outBuffer = null;
// Zerocode if needed
if (doZerocode)
{
// Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
// The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
// there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
// to accomodate for both common scenarios and provide ample room for ACK appending in both
int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
try
{
//zerocode and return the current buffer to the pool if necessary
outBuffer = _bufferPool.LeaseBytes(bufferSize);
dataLength = Helpers.ZeroEncode(data, dataLength, outBuffer);
zeroCoded = true;
if (bufferAcquiredFromPool)
{
_bufferPool.ReturnBytes(data);
}
//now the buffer is from a pool most definitely
bufferAcquiredFromPool = true;
}
catch (IndexOutOfRangeException)
{
//TODO: Throwing an exception here needs to be revisted. I've seen an issue with
//70+ avatars where a very common high freq packet hits this code everytime
//that packet either needs to be split, or this needs to be revised to not throw
//and instead check the buffer size and return an error condition
// The packet grew larger than the bufferSize while zerocoding.
// Remove the MSG_ZEROCODED flag and send the unencoded data
// instead
m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
" and BufferLength=" + outBuffer.Length + ". Removing MSG_ZEROCODED flag");
data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
_bufferPool.ReturnBytes(outBuffer);
}
}
if (! zeroCoded)
{
outBuffer = data;
}
#region Queue or Send
OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, outBuffer, (int)category, dataLength,
udpClient.RemoteEndPoint, bufferAcquiredFromPool, type);
if (!udpClient.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
#endregion Queue or Send
}
public void SendAcks(LLUDPClient udpClient)
{
uint ack;
if (udpClient.PendingAcks.Dequeue(out ack))
{
List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
while (udpClient.PendingAcks.Dequeue(out ack))
{
block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
}
PacketAckPacket packet = new PacketAckPacket();
packet.Header.Reliable = false;
packet.Packets = blocks.ToArray();
SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true);
}
}
public void SendPing(LLUDPClient udpClient)
{
StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
pc.Header.Reliable = false;
pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
// We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
pc.PingID.OldestUnacked = 0;
SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
}
public void CompletePing(LLUDPClient udpClient, byte pingID)
{
CompletePingCheckPacket completePing = new CompletePingCheckPacket();
completePing.PingID.PingID = pingID;
SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
}
public void ResendUnacked(LLUDPClient udpClient)
{
if (!udpClient.IsConnected)
return;
// Disconnect an agent if no packets are received for some time
//FIXME: Make 60 an .ini setting
if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
{
IClientAPI client;
if (m_scene.TryGetClient(udpClient.AgentID, out client))
{
if (client.IsActive) // to prevent duplicate reporting
m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
RemoveClient(client);
}
return;
}
// Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
KeyValuePair<UnackedPacketCollection.ResendReason, List<OutgoingPacket>> expiredPackets
= udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
if (expiredPackets.Key != UnackedPacketCollection.ResendReason.None)
{
//m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
// Exponential backoff of the retransmission timeout
if ((expiredPackets.Key & UnackedPacketCollection.ResendReason.TimeoutExpired) != 0) udpClient.BackoffRTO();
var packetList = expiredPackets.Value;
// Resend packets
for (int i = 0; i < packetList.Count; i++)
{
OutgoingPacket outgoingPacket = packetList[i];
/*m_log.DebugFormat("[LLUDPSERVER]: {0} Resending packet #{1} (attempt {2}), {3}ms have passed",
(expiredPackets.Key & UnackedPacketCollection.ResendReason.FastRetransmit) != 0 ? "(Fast)" : String.Empty,
outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
*/
// Set the resent flag
outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
outgoingPacket.Category = (int) ThrottleOutPacketType.Resend;
// Bump up the resend count on this packet
Interlocked.Increment(ref outgoingPacket.ResendCount);
//Interlocked.Increment(ref Stats.ResentPackets);
// Requeue or resend the packet
if (!udpClient.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
}
/*
if (packetList.Count != 0)
{
m_log.DebugFormat("[LLUDPSERVER]: {0} Resent {1} packet(s) for {2}",
(expiredPackets.Key & UnackedPacketCollection.ResendReason.FastRetransmit) != 0 ? "(Fast)" : String.Empty,
packetList.Count, udpClient.AgentID);
}*/
}
}
public void Flush(LLUDPClient udpClient)
{
// FIXME: Implement?
}
internal void SendPacketFinal(OutgoingPacket outgoingPacket)
{
byte[] buffer = outgoingPacket.Buffer.Data;
byte flags = buffer[0];
bool isResend = (flags & Helpers.MSG_RESENT) != 0;
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
LLUDPClient udpClient = (LLUDPClient)outgoingPacket.Client;
if (!udpClient.IsConnected)
return;
#region ACK Appending
int dataLength = outgoingPacket.DataSize;
// NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
if (!isZerocoded && (buffer[0] & Helpers.MSG_APPENDED_ACKS) == 0)
{
// Keep appending ACKs until there is no room left in the buffer or there are
// no more ACKs to append
uint ackCount = 0;
uint ack;
while (dataLength + 5 < buffer.Length && udpClient.PendingAcks.Dequeue(out ack))
{
Utils.UIntToBytesBig(ack, buffer, dataLength);
dataLength += 4;
++ackCount;
}
if (ackCount > 0)
{
// Set the last byte of the packet equal to the number of appended ACKs
buffer[dataLength++] = (byte)ackCount;
// Set the appended ACKs flag on this packet
buffer[0] = (byte)(buffer[0] | Helpers.MSG_APPENDED_ACKS);
outgoingPacket.DataSize = dataLength;
}
}
#endregion ACK Appending
#region Sequence Number Assignment
if (!isResend)
{
// Not a resend, assign a new sequence number
uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
Utils.UIntToBytesBig(sequenceNumber, buffer, 1);
outgoingPacket.SequenceNumber = sequenceNumber;
if (isReliable)
{
// Add this packet to the list of ACK responses we are waiting on from the server
udpClient.NeedAcks.Add(outgoingPacket);
}
}
#endregion Sequence Number Assignment
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsSent);
if (isReliable)
Interlocked.Add(ref udpClient.UnackedBytes, outgoingPacket.DataSize);
// Put the UDP payload on the wire
AsyncBeginSend(outgoingPacket);
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
}
private HashSet<uint> connectionsInProgress = new HashSet<uint>();
protected override void PacketReceived(UDPPacketBuffer buffer)
{
// Debugging/Profiling
//try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
//catch (Exception) { }
LLUDPClient udpClient = null;
Packet packet = null;
int packetEnd = buffer.DataLength - 1;
IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
#region Decoding
if (buffer.DataLength < 7)
return; // Drop undersizd packet
int headerLen = 7;
if (buffer.Data[6] == 0xFF)
{
if (buffer.Data[7] == 0xFF)
headerLen = 10;
else
headerLen = 8;
}
if (buffer.DataLength < headerLen)
return; // Malformed header
byte[] zeroBuffer = null;
try
{
if ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0)
{
// Only allocate a buffer for zerodecoding if the packet is zerocoded
zeroBuffer = _zeroBufferPool.LeaseBytes(ZERO_BUFFER_SZ);
}
packet = Packet.BuildPacket(buffer.Data, ref packetEnd, zeroBuffer);
}
catch (MalformedDataException)
{
}
catch (IndexOutOfRangeException)
{
}
finally
{
if (zeroBuffer != null)
{
_zeroBufferPool.ReturnBytes(zeroBuffer);
}
}
// Fail-safe check
if (packet == null)
{
m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}:",
buffer.DataLength, buffer.RemoteEndPoint);
m_log.Error(Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
return;
}
#endregion Decoding
#region Packet to Client Mapping
IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
this.PacketBuildingFinished(buffer);
// UseCircuitCode handling
if (packet.Type == PacketType.UseCircuitCode)
{
//m_log.Info("[LLUDPSERVER]: Handling UseCircuitCode packet from " + buffer.RemoteEndPoint);
object[] array = new object[] { remoteEndPoint, packet };
UseCircuitCodePacket UCC = (UseCircuitCodePacket)packet;
lock (connectionsInProgress)
{
if (connectionsInProgress.Add(UCC.CircuitCode.Code))
Util.FireAndForget(HandleUseCircuitCode, array);
else
m_log.WarnFormat("[LLUDPSERVER]: Duplicate UseCircuitCode for {0} {1} {2}",
UCC.CircuitCode.Code.ToString(), UCC.CircuitCode.SessionID.ToString(), UCC.CircuitCode.ID.ToString());
// HandleUseCircuitCode(array);
}
return;
}
// Determine which agent this packet came from
IClientAPI client;
if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
{
// m_log.Warn("[LLUDPSERVER]: Received a " + packet.Type.ToString() + " packet from an unrecognized source: " + address.ToString() + " in " + m_scene.RegionInfo.RegionName);
return;
}
udpClient = ((LLClientView)client).UDPClient;
if (!udpClient.IsConnected)
{
m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type.ToString() + " packet from an unconnected source: " + address.ToString() + " in " + m_scene.RegionInfo.RegionName);
return;
}
#endregion Packet to Client Mapping
// Stats tracking
Interlocked.Increment(ref udpClient.PacketsReceived);
int now = Environment.TickCount & Int32.MaxValue;
udpClient.TickLastPacketReceived = now;
#region ACK Receiving
// Handle appended ACKs
if (packet.Header.AppendedAcks && packet.Header.AckList != null)
{
for (int i = 0; i < packet.Header.AckList.Length; i++)
udpClient.NeedAcks.Remove(packet.Header.AckList[i], now, packet.Header.Resent);
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
for (int i = 0; i < ackPacket.Packets.Length; i++)
udpClient.NeedAcks.Remove(ackPacket.Packets[i].ID, now, packet.Header.Resent);
// We don't need to do anything else with PacketAck packets
return;
}
#endregion ACK Receiving
#region ACK Sending
if (packet.Header.Reliable)
{
udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
// This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
// add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
// 2*MTU bytes from the value and send ACKs, and finally add the local value back to
// client.BytesSinceLastACK. Lockless thread safety
int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
bytesSinceLastACK += buffer.DataLength;
if (bytesSinceLastACK > LLUDPServer.MTU * 2)
{
bytesSinceLastACK -= LLUDPServer.MTU * 2;
SendAcks(udpClient);
}
Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
}
#endregion ACK Sending
#region Incoming Packet Accounting
// Check the archive of received reliable packet IDs to see whether we already received this packet
if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
{
if (packet.Header.Resent)
m_log.Debug("[LLUDPSERVER]: Received a resend of already processed packet #" + packet.Header.Sequence + ", type: " + packet.Type);
else
m_log.Warn("[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #" + packet.Header.Sequence + ", type: " + packet.Type);
// Avoid firing a callback twice for the same packet
return;
}
#endregion Incoming Packet Accounting
#region BinaryStats
LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
#endregion BinaryStats
#region Ping Check Handling
if (packet.Type == PacketType.StartPingCheck)
{
// We don't need to do anything else with ping checks
StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
CompletePing(udpClient, startPing.PingID.PingID);
if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
{
udpClient.SendPacketStats();
m_elapsedMSSinceLastStatReport = Environment.TickCount;
}
return;
}
else if (packet.Type == PacketType.CompletePingCheck)
{
// We don't currently track client ping times
return;
}
#endregion Ping Check Handling
// Inbox insertion
packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
}
#region BinaryStats
public class PacketLogger
{
public DateTime StartTime;
public string Path = null;
public System.IO.BinaryWriter Log = null;
}
public static PacketLogger PacketLog;
protected static bool m_shouldCollectStats = false;
// Number of seconds to log for
static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
static object binStatsLogLock = new object();
static string binStatsDir = String.Empty;
public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
{
if (!m_shouldCollectStats) return;
// Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
// Put the incoming bit into the least significant bit of the flags byte
if (incoming)
flags |= 0x01;
else
flags &= 0xFE;
// Put the flags byte into the most significant bits of the type integer
uint type = (uint)packetType;
type |= (uint)flags << 24;
// m_log.Debug("1 LogPacketHeader(): Outside lock");
lock (binStatsLogLock)
{
DateTime now = DateTime.Now;
// m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
try
{
if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
{
if (PacketLog != null && PacketLog.Log != null)
{
PacketLog.Log.Close();
}
// First log file or time has expired, start writing to a new log file
PacketLog = new PacketLogger();
PacketLog.StartTime = now;
PacketLog.Path = (!String.IsNullOrEmpty(binStatsDir) ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : String.Empty)
+ String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
}
// Serialize the data
byte[] output = new byte[18];
Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
// Write the serialized data to disk
if (PacketLog != null && PacketLog.Log != null)
PacketLog.Log.Write(output);
}
catch (Exception ex)
{
m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
if (PacketLog.Log != null)
{
PacketLog.Log.Close();
}
PacketLog = null;
}
}
}
#endregion BinaryStats
private void HandleUseCircuitCode(object o)
{
object[] array = (object[])o;
UseCircuitCodePacket UCC = (UseCircuitCodePacket)array[1];
// m_log.WarnFormat("[LLUDPSERVER]: HandleUseCircuitCode, client {0}, circuit code {1}, session {2}", UCC.CircuitCode.ID, UCC.CircuitCode.Code, UCC.CircuitCode.SessionID);
try
{
IPEndPoint remoteEndPoint = (IPEndPoint)array[0];
// Begin the process of adding the client to the simulator
if (AddNewClient(UCC, remoteEndPoint))
{
// Acknowledge the UseCircuitCode packet
SendAckImmediate(remoteEndPoint, UCC.Header.Sequence);
}
}
finally
{
lock (connectionsInProgress)
{
connectionsInProgress.Remove(UCC.CircuitCode.Code);
}
}
}
private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
{
PacketAckPacket ack = new PacketAckPacket();
ack.Header.Reliable = false;
ack.Packets = new PacketAckPacket.PacketsBlock[1];
ack.Packets[0] = new PacketAckPacket.PacketsBlock();
ack.Packets[0].ID = sequenceNumber;
byte[] packetData = ack.ToBytes();
int length = packetData.Length;
OutgoingPacket outgoingPacket = new OutgoingPacket(null, packetData, 0, length,
remoteEndpoint, false, PacketType.PacketAck);
AsyncBeginSend(outgoingPacket);
}
private bool AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
{
UUID agentID = useCircuitCode.CircuitCode.ID;
UUID sessionID = useCircuitCode.CircuitCode.SessionID;
uint circuitCode = useCircuitCode.CircuitCode.Code;
try
{
m_log.InfoFormat(
"[LLUDPSERVER]: UCC Received for client {0} circuit code {1}",
useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code);
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, agentID, sessionID, circuitCode);
m_scene.ConnectionManager.TryAttachUdpCircuit(client);
client.Start();
return true;
}
catch (OpenSim.Region.Framework.Connection.AttachUdpCircuitException e)
{
if (e.CircuitAlreadyExisted)
{
m_log.WarnFormat("[LLUDPSERVER]: Ignoring duplicate UDP connection request. {0}", e.Message);
//if the circuit matches, we can ACK the UCC since the client should be
//able to communicate with the current circuit
if (e.ExistingCircuitMatched)
{
return true;
}
else
{
return false;
}
}
else
{
m_log.ErrorFormat("[LLUDPSERVER]: Unable to start new connection: {0}", e);
return false;
}
}
}
private void RemoveClient(IClientAPI client)
{
try
{
client.Close();
}
catch (Exception e)
{
m_log.Error("[LLUDPSERVER] RemoveClient exception: " + e.ToString());
}
}
private void IncomingPacketHandler()
{
// Set this culture for the thread that incoming packets are received
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
while (base.IsRunning)
{
try
{
IncomingPacket incomingPacket = null;
if (packetInbox.Dequeue(100, ref incomingPacket))
ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
}
Watchdog.UpdateThread();
}
if (packetInbox.Count > 0)
m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
packetInbox.Clear();
Watchdog.RemoveThread();
}
private void OutgoingPacketHandler()
{
// Set this culture for the thread that outgoing packets are sent
// on to en-US to avoid number parsing issues
Culture.SetCurrentCulture();
// Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
// Action generic every round
Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
while (base.IsRunning)
{
try
{
m_packetSent = false;
#region Update Timers
m_resendUnacked = false;
m_sendAcks = false;
m_sendPing = false;
// Update elapsed time
int thisTick = Environment.TickCount & Int32.MaxValue;
if (m_tickLastOutgoingPacketHandler > thisTick)
m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
else
m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
m_tickLastOutgoingPacketHandler = thisTick;
// Check for pending outgoing resends every 100ms
if (m_elapsedMSOutgoingPacketHandler >= 100)
{
m_resendUnacked = true;
m_elapsedMSOutgoingPacketHandler = 0;
m_elapsed100MSOutgoingPacketHandler += 1;
}
// Check for pending outgoing ACKs every 500ms
if (m_elapsed100MSOutgoingPacketHandler >= 5)
{
m_sendAcks = true;
m_elapsed100MSOutgoingPacketHandler = 0;
m_elapsed500MSOutgoingPacketHandler += 1;
}
// Send pings to clients every 5000ms
if (m_elapsed500MSOutgoingPacketHandler >= 10)
{
m_sendPing = true;
m_elapsed500MSOutgoingPacketHandler = 0;
}
#endregion Update Timers
// Handle outgoing packets, resends, acknowledgements, and pings for each
// client. m_packetSent will be set to true if a packet is sent
m_scene.ForEachClient(clientPacketHandler);
// If nothing was sent, sleep for the minimum amount of time before a
// token bucket could get more tokens
if (!m_packetSent)
Thread.Sleep((int)TickCountResolution);
Watchdog.UpdateThread();
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
}
}
Watchdog.RemoveThread();
}
private void ClientOutgoingPacketHandler(IClientAPI client)
{
try
{
if (client is LLClientView)
{
LLUDPClient udpClient = ((LLClientView)client).UDPClient;
if (udpClient.IsConnected)
{
if (m_resendUnacked)
ResendUnacked(udpClient);
if (m_sendAcks)
SendAcks(udpClient);
if (m_sendPing)
SendPing(udpClient);
// Dequeue any outgoing packets that are within the throttle limits
if (udpClient.DequeueOutgoing())
m_packetSent = true;
if (udpClient.PerformDynamicThrottleAdjustment())
m_packetSent = true;
}
}
}
catch (Exception ex)
{
m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
" threw an exception: " + ex.Message, ex);
}
}
private void ProcessInPacket(object state)
{
IncomingPacket incomingPacket = (IncomingPacket)state;
Packet packet = incomingPacket.Packet;
LLUDPClient udpClient = incomingPacket.Client;
IClientAPI client;
// Sanity check
if (packet == null || udpClient == null)
{
m_log.WarnFormat("[LLUDPSERVER]: Processing a packet with incomplete state. Packet=\"{0}\", UDPClient=\"{1}\"",
packet, udpClient);
}
// Make sure this client is still alive
if (m_scene.TryGetClient(udpClient.AgentID, out client))
{
try
{
// Process this packet
client.ProcessInPacket(packet);
}
catch (ThreadAbortException)
{
// If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
Stop();
}
catch (Exception e)
{
// Don't let a failure in an individual client thread crash the whole sim.
m_log.ErrorFormat("[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw an exception", udpClient.AgentID, packet.Type);
m_log.Error(e.Message, e);
}
}
else
{
m_log.DebugFormat("[LLUDPSERVER]: Dropping incoming {0} packet for dead client {1}", packet.Type, udpClient.AgentID);
}
}
protected override void SendCompleted(OutgoingPacket packet)
{
packet.DecRef(_bufferPool);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using Orleans.Runtime;
using Orleans.Runtime.Counters;
using Orleans.Runtime.Configuration;
namespace Orleans.Counter.Control
{
using Orleans.Serialization;
using System.Collections.Generic;
/// <summary>
/// Control Orleans Counters - Register or Unregister the Orleans counter set
/// </summary>
internal class CounterControl
{
public bool Unregister { get; private set; }
public bool BruteForce { get; private set; }
public bool NeedRunAsAdministrator { get; private set; }
public bool IsRunningAsAdministrator { get; private set; }
public bool PauseAtEnd { get; private set; }
public CounterControl()
{
// Check user is Administrator and has granted UAC elevation permission to run this app
var userIdent = WindowsIdentity.GetCurrent();
var userPrincipal = new WindowsPrincipal(userIdent);
IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
public void PrintUsage()
{
using (var usageStr = new StringWriter())
{
usageStr.WriteLine(typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe {command}");
usageStr.WriteLine("Where commands are:");
usageStr.WriteLine(" /? or /help = Display usage info");
usageStr.WriteLine(" /r or /register = Register Windows performance counters for Orleans [default]");
usageStr.WriteLine(" /u or /unregister = Unregister Windows performance counters for Orleans");
usageStr.WriteLine(" /f or /force = Use brute force, if necessary");
usageStr.WriteLine(" /pause = Pause for user key press after operation");
ConsoleText.WriteUsage(usageStr.ToString());
}
}
public bool ParseArguments(string[] args)
{
bool ok = true;
NeedRunAsAdministrator = true;
Unregister = false;
foreach (var arg in args)
{
if (arg.StartsWith("/") || arg.StartsWith("-"))
{
var a = arg.ToLowerInvariant().Substring(1);
switch (a)
{
case "r":
case "register":
Unregister = false;
break;
case "u":
case "unregister":
Unregister = true;
break;
case "f":
case "force":
BruteForce = true;
break;
case "pause":
PauseAtEnd = true;
break;
case "?":
case "help":
NeedRunAsAdministrator = false;
ok = false;
break;
default:
NeedRunAsAdministrator = false;
ok = false;
break;
}
}
else
{
ConsoleText.WriteError("Unrecognised command line option: " + arg);
ok = false;
}
}
return ok;
}
public int Run()
{
if (NeedRunAsAdministrator && !IsRunningAsAdministrator)
{
ConsoleText.WriteError("Need to be running in Administrator role to perform the requested operations.");
return 1;
}
SerializationManager.InitializeForTesting();
InitConsoleLogging();
try
{
if (Unregister)
{
ConsoleText.WriteStatus("Unregistering Orleans performance counters with Windows");
UnregisterWindowsPerfCounters(this.BruteForce);
}
else
{
ConsoleText.WriteStatus("Registering Orleans performance counters with Windows");
RegisterWindowsPerfCounters(true); // Always reinitialize counter registrations, even if already existed
}
ConsoleText.WriteStatus("Operation completed successfully.");
return 0;
}
catch (Exception exc)
{
ConsoleText.WriteError("Error running " + typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe", exc);
if (!BruteForce) return 2;
ConsoleText.WriteStatus("Ignoring error due to brute-force mode");
return 0;
}
}
/// <summary>
/// Initialize log infrastrtucture for Orleans runtime sub-components
/// </summary>
private static void InitConsoleLogging()
{
Trace.Listeners.Clear();
var cfg = new NodeConfiguration { TraceFilePattern = null, TraceToConsole = false };
LogManager.Initialize(cfg);
//TODO: Move it to use the APM APIs
//var logWriter = new LogWriterToConsole(true, true); // Use compact console output & no timestamps / log message metadata
//LogManager.LogConsumers.Add(logWriter);
}
/// <summary>
/// Create the set of Orleans counters, if they do not already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to register Windows perf counters.</remarks>
private static void RegisterWindowsPerfCounters(bool useBruteForce)
{
try
{
if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
{
if (!useBruteForce)
{
ConsoleText.WriteStatus("Orleans counters are already registered -- Use brute-force mode to re-initialize");
return;
}
// Delete any old perf counters
UnregisterWindowsPerfCounters(true);
}
if (GrainTypeManager.Instance == null)
{
var loader = new SiloAssemblyLoader(new Dictionary<string, SearchOption>());
var typeManager = new GrainTypeManager(false, null, loader); // We shouldn't need GrainFactory in this case
GrainTypeManager.Instance.Start(false);
}
// Register perf counters
OrleansPerfCounterManager.InstallCounters();
if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
ConsoleText.WriteStatus("Orleans counters registered successfully");
else
ConsoleText.WriteError("Orleans counters are NOT registered");
}
catch (Exception exc)
{
ConsoleText.WriteError("Error registering Orleans counters - {0}" + exc);
throw;
}
}
/// <summary>
/// Remove the set of Orleans counters, if they already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to unregister Windows perf counters.</remarks>
private static void UnregisterWindowsPerfCounters(bool useBruteForce)
{
if (!OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
{
ConsoleText.WriteStatus("Orleans counters are already unregistered");
return;
}
// Delete any old perf counters
try
{
OrleansPerfCounterManager.DeleteCounters();
}
catch (Exception exc)
{
ConsoleText.WriteError("Error deleting old Orleans counters - {0}" + exc);
if (useBruteForce)
ConsoleText.WriteStatus("Ignoring error deleting Orleans counters due to brute-force mode");
else
throw;
}
}
}
}
| |
/*
* Strings.cs - Implementation of the
* "Microsoft.VisualBasic.Strings" class.
*
* Copyright (C) 2003, 2004 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Microsoft.VisualBasic
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.CompilerServices;
[StandardModule]
public sealed class Strings
{
// This class cannot be instantiated.
private Strings() {}
// Get a character code.
public static int Asc(char String)
{
if(((int)String) < 0x80)
{
return (int)String;
}
char[] charBuf = new char [] {String};
byte[] byteBuf = Encoding.Default.GetBytes(charBuf);
if(byteBuf.Length == 0)
{
return 0;
}
else if(byteBuf.Length == 1)
{
return byteBuf[0];
}
else
{
return (int)(short)((byteBuf[0] << 8) | byteBuf[1]);
}
}
public static int Asc(String String)
{
if(String == null || String.Length == 0)
{
throw new ArgumentException(S._("VB_EmptyString"));
}
return Asc(String[0]);
}
public static int AscW(char String)
{
return (int)String;
}
public static int AscW(String String)
{
if(String == null || String.Length == 0)
{
throw new ArgumentException(S._("VB_EmptyString"));
}
return (int)(String[0]);
}
// Convert an integer character code into a character.
public static char Chr(int CharCode)
{
byte[] byteBuf;
char[] charBuf;
if(CharCode >= 0 && CharCode <= 127)
{
return (char)CharCode;
}
else if(CharCode >= 128 && CharCode <= 255)
{
byteBuf = new byte [] {(byte)CharCode};
}
else if(CharCode >= -32768 && CharCode <= 65535)
{
byteBuf = new byte []
{(byte)(CharCode >> 8), (byte)CharCode};
}
else
{
throw new ArgumentException(S._("VB_ChrRange"));
}
charBuf = Encoding.Default.GetChars(byteBuf);
if(charBuf.Length == 0)
{
return '\u0000';
}
else
{
return charBuf[0];
}
}
public static char ChrW(int CharCode)
{
if(CharCode >= -32768 && CharCode <= 65535)
{
return (char)CharCode;
}
else
{
throw new ArgumentException(S._("VB_ChrRange"));
}
}
// Filter an array of strings on a condition.
public static String[] Filter
(Object[] source, String Match,
[Optional][DefaultValue(true)] bool Include,
[Optional, OptionCompare][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
String[] strSource = new String [source.Length];
int posn;
for(posn = 0; posn < source.Length; ++posn)
{
strSource[posn] = StringType.FromObject(source[posn]);
}
return Filter(strSource, Match, Include, Compare);
}
public static String[] Filter
(String[] source, String Match,
[Optional][DefaultValue(true)] bool Include,
[Optional, OptionCompare][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Match == null || Match.Length == 0)
{
return null;
}
int count = FilterInternal
(source, Match, Include, Compare, null);
String[] result = new String [count];
FilterInternal(source, Match, Include, Compare, result);
return result;
}
private static int FilterInternal
(String[] source, String Match,
bool Include, CompareMethod Compare, String[] result)
{
int count = 0;
CompareInfo compare = CultureInfo.CurrentCulture.CompareInfo;
foreach(String value in source)
{
if(value == null)
{
continue;
}
if(Include)
{
if(Compare == CompareMethod.Binary)
{
if(value.IndexOf(Match) != -1)
{
if(result != null)
{
result[count] = value;
}
++count;
}
}
else if(compare.IndexOf
(value, Match, CompareOptions.IgnoreCase) != -1)
{
if(result != null)
{
result[count] = value;
}
++count;
}
}
else if(Compare == CompareMethod.Binary)
{
if(value == Match)
{
if(result != null)
{
result[count] = value;
}
++count;
}
}
else if(compare.Compare
(value, Match, CompareOptions.IgnoreCase) == 0)
{
if(result != null)
{
result[count] = value;
}
++count;
}
}
return count;
}
// Format an object according to a particular style.
[TODO]
public static String Format
(Object Expression, [Optional][DefaultValue("")] String Style)
{
// TODO
return null;
}
// Format a currency value.
public static String FormatCurrency
(Object Expression,
[Optional][DefaultValue(-1)] int NumDigitsAfterDecimal,
[Optional][DefaultValue(TriState.UseDefault)]
TriState IncludeLeadingDigit,
[Optional][DefaultValue(TriState.UseDefault)]
TriState UseParensForNegativeNumbers,
[Optional][DefaultValue(TriState.UseDefault)]
TriState GroupDigits)
{
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
NumberFormatInfo nfiCurrent = nfi;
if(NumDigitsAfterDecimal != -1)
{
nfi = (NumberFormatInfo)(nfi.Clone());
nfi.CurrencyDecimalDigits = NumDigitsAfterDecimal;
}
if(UseParensForNegativeNumbers != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(UseParensForNegativeNumbers == TriState.False)
{
nfi.CurrencyNegativePattern = 0;
}
else
{
nfi.CurrencyNegativePattern = 1;
}
}
if(GroupDigits != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(GroupDigits == TriState.False)
{
nfi.CurrencyGroupSizes = new int [] {0};
}
else
{
nfi.CurrencyGroupSizes = new int [] {3};
}
}
return DoubleType.FromObject(Expression).ToString("C", nfi);
}
// Format a DateTime value.
public static String FormatDateTime
(DateTime Expression,
[Optional][DefaultValue(DateFormat.GeneralDate)]
DateFormat NamedFormat)
{
String format;
switch(NamedFormat)
{
case DateFormat.GeneralDate: format = "G"; break;
case DateFormat.LongDate: format = "D"; break;
case DateFormat.ShortDate: format = "d"; break;
case DateFormat.LongTime: format = "T"; break;
case DateFormat.ShortTime: format = "t"; break;
default:
{
throw new ArgumentException
(S._("VB_InvalidDateFormat"), "NamedFormat");
}
// Not reached.
}
return Expression.ToString(format);
}
// Format a numeric value.
public static String FormatNumber
(Object Expression,
[Optional][DefaultValue(-1)] int NumDigitsAfterDecimal,
[Optional][DefaultValue(TriState.UseDefault)]
TriState IncludeLeadingDigit,
[Optional][DefaultValue(TriState.UseDefault)]
TriState UseParensForNegativeNumbers,
[Optional][DefaultValue(TriState.UseDefault)]
TriState GroupDigits)
{
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
NumberFormatInfo nfiCurrent = nfi;
if(NumDigitsAfterDecimal != -1)
{
nfi = (NumberFormatInfo)(nfi.Clone());
nfi.NumberDecimalDigits = NumDigitsAfterDecimal;
}
if(UseParensForNegativeNumbers != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(UseParensForNegativeNumbers == TriState.False)
{
nfi.NumberNegativePattern = 0;
}
else
{
nfi.NumberNegativePattern = 1;
}
}
if(GroupDigits != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(GroupDigits == TriState.False)
{
nfi.NumberGroupSizes = new int [] {0};
}
else
{
nfi.NumberGroupSizes = new int [] {3};
}
}
return DoubleType.FromObject(Expression).ToString("N", nfi);
}
// Format a percentage value.
public static String FormatPercent
(Object Expression,
[Optional][DefaultValue(-1)] int NumDigitsAfterDecimal,
[Optional][DefaultValue(TriState.UseDefault)]
TriState IncludeLeadingDigit,
[Optional][DefaultValue(TriState.UseDefault)]
TriState UseParensForNegativeNumbers,
[Optional][DefaultValue(TriState.UseDefault)]
TriState GroupDigits)
{
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
NumberFormatInfo nfiCurrent = nfi;
if(NumDigitsAfterDecimal != -1)
{
nfi = (NumberFormatInfo)(nfi.Clone());
nfi.PercentDecimalDigits = NumDigitsAfterDecimal;
}
if(UseParensForNegativeNumbers != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(UseParensForNegativeNumbers == TriState.False)
{
nfi.PercentNegativePattern = 0;
}
else
{
nfi.PercentNegativePattern = 1;
}
}
if(GroupDigits != TriState.UseDefault)
{
if(nfi == nfiCurrent)
{
nfi = (NumberFormatInfo)(nfi.Clone());
}
if(GroupDigits == TriState.False)
{
nfi.PercentGroupSizes = new int [] {0};
}
else
{
nfi.PercentGroupSizes = new int [] {3};
}
}
return DoubleType.FromObject(Expression).ToString("P", nfi);
}
// Get a particular character within a string.
public static char GetChar(String str, int Index)
{
if(str == null)
{
throw new ArgumentException(S._("VB_ValueIsNull"), "str");
}
if(Index < 1 || Index > str.Length)
{
throw new ArgumentException
(S._("VB_InvalidStringIndex"), "Index");
}
return str[Index - 1];
}
// Find the index of one string within another.
public static int InStr
(String String1, String String2,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
return InStr(1, String1, String2, Compare);
}
public static int InStr
(int Start, String String1, String String2,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Start < 1)
{
throw new ArgumentException
(S._("VB_InvalidStringIndex"), "Start");
}
if(String1 == null || String1.Length == 0)
{
return 0;
}
if(String2 == null || String2.Length == 0)
{
return Start;
}
if(Start >= String1.Length)
{
return 0;
}
if(Compare == CompareMethod.Binary)
{
return (CultureInfo.CurrentCulture.CompareInfo
.IndexOf(String1, String2, Start - 1,
CompareOptions.Ordinal) + 1);
}
else
{
return (CultureInfo.CurrentCulture.CompareInfo
.IndexOf(String1, String2, Start - 1,
CompareOptions.IgnoreWidth |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreCase) + 1);
}
}
public static int InStrRev
(String StringCheck, String StringMatch,
[Optional][DefaultValue(-1)] int Start,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Start < 1 && Start != -1)
{
throw new ArgumentException
(S._("VB_InvalidStringIndex"), "Start");
}
if(StringCheck == null || StringCheck.Length == 0)
{
return 0;
}
if(Start == -1)
{
Start = StringCheck.Length;
}
else if(Start > StringCheck.Length)
{
return 0;
}
if(StringMatch == null || StringMatch.Length == 0)
{
return Start;
}
if(Compare == CompareMethod.Binary)
{
return (CultureInfo.CurrentCulture.CompareInfo
.LastIndexOf(StringCheck, StringMatch, Start - 1,
CompareOptions.Ordinal) + 1);
}
else
{
return (CultureInfo.CurrentCulture.CompareInfo
.LastIndexOf(StringCheck, StringMatch, Start - 1,
CompareOptions.IgnoreWidth |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreCase) + 1);
}
}
// Join an array of strings together.
public static String Join(Object[] SourceArray,
[Optional][DefaultValue(" ")] String Delimiter)
{
if(SourceArray == null)
{
throw new ArgumentNullException("SourceArray");
}
String[] strSource = new String [SourceArray.Length];
int posn;
for(posn = 0; posn < SourceArray.Length; ++posn)
{
strSource[posn] = StringType.FromObject(SourceArray[posn]);
}
return String.Join(Delimiter, strSource);
}
public static String Join(String[] SourceArray,
[Optional][DefaultValue(" ")] String Delimiter)
{
if(SourceArray == null)
{
return null;
}
return String.Join(Delimiter, SourceArray);
}
// Convert a string or character to lower case.
public static String LCase(String Value)
{
if(Value != null)
{
return CultureInfo.CurrentCulture.TextInfo.ToLower(Value);
}
else
{
return null;
}
}
public static char LCase(char Value)
{
return CultureInfo.CurrentCulture.TextInfo.ToLower(Value);
}
// Convert a string or character to upper case.
public static String UCase(String Value)
{
if(Value != null)
{
return CultureInfo.CurrentCulture.TextInfo.ToUpper(Value);
}
else
{
return null;
}
}
public static char UCase(char Value)
{
return CultureInfo.CurrentCulture.TextInfo.ToUpper(Value);
}
// Align a string within a given field length.
public static String LSet(String Source, int Length)
{
if(Source == null)
{
return new String(' ', Length);
}
if(Source.Length >= Length)
{
return Source.Substring(0, Length);
}
else
{
return Source.PadRight(Length);
}
}
public static String RSet(String Source, int Length)
{
if(Source == null)
{
return new String(' ', Length);
}
if(Source.Length >= Length)
{
return Source.Substring(0, Length);
}
else
{
return Source.PadLeft(Length);
}
}
// Trim white space from a string.
public static String LTrim(String str)
{
if(str != null)
{
return str.TrimStart(null);
}
else
{
return String.Empty;
}
}
public static String RTrim(String str)
{
if(str != null)
{
return str.TrimEnd(null);
}
else
{
return String.Empty;
}
}
public static String Trim(String str)
{
if(str != null)
{
return str.Trim();
}
else
{
return String.Empty;
}
}
// Get the left, middle, or right parts of a string.
public static String Left(String Str, int Length)
{
if(Length < 0)
{
throw new ArgumentException
(S._("VB_NonNegative"), "Length");
}
if(Str == null)
{
return String.Empty;
}
if(Str.Length <= Length)
{
return Str;
}
else
{
return Str.Substring(0, Length);
}
}
public static String Mid(String Str, int Start)
{
if(Str == null)
{
return null;
}
else
{
return Mid(Str, Start, Str.Length);
}
}
public static String Mid(String Str, int Start, int Length)
{
if(Start < 1)
{
throw new ArgumentException
(S._("VB_InvalidStringIndex"), "Start");
}
if(Length < 0)
{
throw new ArgumentException
(S._("VB_NonNegative"), "Length");
}
int len = Str.Length;
--Start;
if(Start >= len)
{
return String.Empty;
}
if((Start + Length) < len)
{
len = Start + Length;
}
return Str.Substring(Start, len - Start);
}
public static String Right(String Str, int Length)
{
if(Length < 0)
{
throw new ArgumentException
(S._("VB_NonNegative"), "Length");
}
if(Str == null)
{
return String.Empty;
}
int len = Str.Length;
if(len <= Length)
{
return Str;
}
else
{
return Str.Substring(len - Length, Length);
}
}
// Get the number of bytes to store a value, or the length of a string.
public static int Len(bool Expression)
{
return 2;
}
public static int Len(byte Expression)
{
return 1;
}
public static int Len(short Expression)
{
return 2;
}
public static int Len(char Expression)
{
return 2;
}
public static int Len(int Expression)
{
return 4;
}
public static int Len(long Expression)
{
return 8;
}
public static int Len(float Expression)
{
return 4;
}
public static int Len(double Expression)
{
return 8;
}
public static int Len(DateTime Expression)
{
return 8;
}
public static int Len(Decimal Expression)
{
return 16;
}
public static int Len(String Expression)
{
if(Expression != null)
{
return Expression.Length;
}
else
{
return 0;
}
}
public static int Len(Object Expression)
{
if(Expression == null)
{
return 0;
}
switch(ObjectType.GetTypeCode(Expression))
{
case TypeCode.SByte:
case TypeCode.Byte: return 1;
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16: return 2;
case TypeCode.Single:
case TypeCode.Int32:
case TypeCode.UInt32: return 4;
case TypeCode.Double:
case TypeCode.DateTime:
case TypeCode.Int64:
case TypeCode.UInt64: return 8;
case TypeCode.Decimal: return 16;
case TypeCode.String:
return Len(StringType.FromObject(Expression));
}
if(Expression is char[])
{
return ((char[])Expression).Length;
}
else if(Expression is ValueType)
{
return Marshal.SizeOf(Expression);
}
throw new ArgumentException
(S._("VB_CouldntHandle"), "Expression");
}
// Perform string replacement.
public static String Replace
(String Expression, String Find, String Replacement,
[Optional][DefaultValue(1)] int Start,
[Optional][DefaultValue(-1)] int Count,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Start>1)
{
Expression = Expression.Substring(Start-1);
}
string[] lst;
lst = Split(Expression,Find,Count,Compare);
string res = "";
int bcl = lst.Length;
for(int y = 0; y < bcl; y++)
{
res += lst[y];
if(y + 1 != bcl)
{
res += Replacement;
}
}
return res;
}
// Create a string with "Number" spaces in it.
public static String Space(int Number)
{
if(Number < 0)
{
throw new ArgumentException
(S._("VB_NonNegative"), "Number");
}
else
{
return new String(' ', Number);
}
}
// Split a string using a particular delimiter.
public static String[] Split
(String Expression,
[Optional][DefaultValue(" ")] String Delimiter,
[Optional][DefaultValue(-1)] int Limit,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Expression == null)
{
return null;
}
try {
if(Delimiter == null)
{
Delimiter = " ";
}
if((Limit==-1) || (Limit==0))
{
Limit = Int32.MaxValue; // 0x7fffffff
}
if(Limit <- 1)
{
throw new ArgumentException(S._("VB_InvalidArgument1"), "Limit");// from Strings.StrComp
}
if((Compare != CompareMethod.Binary) && (Compare != CompareMethod.Text))
{
throw new ArgumentException(S._("VB_InvalidCompareMethod"), "Compare");// from Strings.StrComp
}
}
catch(Exception e)
{
throw e;
}
return SplitHelper(Expression,Delimiter,Limit,(int)Compare);
}
private static string[] SplitHelper
(string sSrc,
string sFind,
int cMaxSubStrings,
int Compare)
{
int[] cnt= new int[1];
int nxt = 1;
int theEnd = sSrc.Length;
cnt[0] = -1;
int val = 0;
string modSrc ;
if(Compare == 0)//binary
{
modSrc = sSrc;
}
else // Text ( <>0 and <>1 -> throw exception in Split
{
modSrc = sSrc.ToLower();
sFind = sFind.ToLower();
}
while(val>-1)
{
val = modSrc.IndexOf(sFind,cnt[nxt - 1] + 1);
int[] tmp = new int[cnt.Length + 1];
Array.Copy(cnt, 0, tmp, 0, cnt.Length);
cnt = tmp;
if(val >= 0)
{
cnt[cnt.Length - 1] = val + (sFind.Length - 1);
}
else
{
cnt[cnt.Length - 1] = theEnd;
}
nxt++;
}
string[] res;
int bcl = 0;
if(cMaxSubStrings < cnt.Length - 1)
{
res = new string[cMaxSubStrings];
bcl = cMaxSubStrings;
}
else
{
res = new string[cnt.Length - 1];
bcl = cnt.Length - 1;
}
for(int i = 0; i < bcl; i++)
{
if((i == bcl-1) && (bcl != cnt.Length))
{
res[i] = sSrc.Substring(cnt[i] + 1); // the rest!
break;// stop when Max Substring is reached
}
res[i] = sSrc.Substring((cnt[i] + 1),(cnt[i + 1]-cnt[i] - 1) -(sFind.Length - 1) );
}
return res;
}
// Compare two strings.
public static int StrComp
(String String1, String String2,
[Optional][DefaultValue(CompareMethod.Binary)]
CompareMethod Compare)
{
if(Compare != CompareMethod.Binary &&
Compare != CompareMethod.Text)
{
throw new ArgumentException
(S._("VB_InvalidCompareMethod"), "Compare");
}
return StringType.StrCmp
(String1, String2, (Compare == CompareMethod.Text));
}
// Get the TextInfo object for a given locale.
private static TextInfo GetTextInfo(int LocaleID)
{
if(LocaleID == 0)
{
return CultureInfo.CurrentCulture.TextInfo;
}
#if CONFIG_REFLECTION
if(LocaleID == CultureInfo.CurrentCulture.LCID)
{
return CultureInfo.CurrentCulture.TextInfo;
}
#else
// We don't have LCID, so use GetHashCode() instead.
if(LocaleID == CultureInfo.CurrentCulture.GetHashCode())
{
return CultureInfo.CurrentCulture.TextInfo;
}
#endif
try
{
return (new CultureInfo(LocaleID)).TextInfo;
}
catch(Exception)
{
return CultureInfo.CurrentCulture.TextInfo;
}
}
// Perform a string conversion (we don't support simplified/traditional
// conversions or linguistic casing yet).
public static String StrConv
(String str, VbStrConv Conversion,
[Optional][DefaultValue(0)] int LocaleID)
{
if(str == null)
{
return null;
}
if((Conversion & VbStrConv.Wide) != 0)
{
str = Utils.ToWide(str);
}
else if((Conversion & VbStrConv.Narrow) != 0)
{
str = Utils.ToNarrow(str);
}
if((Conversion & VbStrConv.Katakana) != 0)
{
str = Utils.ToKatakana(str);
}
else if((Conversion & VbStrConv.Hiragana) != 0)
{
str = Utils.ToHiragana(str);
}
switch(Conversion & (VbStrConv)0x0003)
{
case VbStrConv.UpperCase:
{
str = GetTextInfo(LocaleID).ToUpper(str);
}
break;
case VbStrConv.LowerCase:
{
str = GetTextInfo(LocaleID).ToLower(str);
}
break;
case VbStrConv.ProperCase:
{
str = GetTextInfo(LocaleID).ToTitleCase(str);
}
break;
}
return str;
}
// Duplicate a character a particular number of times.
public static String StrDup(int Number, char Character)
{
if(Number >= 0)
{
return new String(Character, Number);
}
else
{
throw new ArgumentNullException
(S._("VB_NonNegative"), "Number");
}
}
public static String StrDup(int Number, String Character)
{
if(Number >= 0)
{
if(Character != null && Character.Length > 0)
{
return new String(Character[0], Number);
}
else
{
throw new ArgumentException
(S._("VB_EmptyString"), "Character");
}
}
else
{
throw new ArgumentException
(S._("VB_NonNegative"), "Number");
}
}
public static Object StrDup(int Number, Object Character)
{
if(Number < 0)
{
throw new ArgumentException
(S._("VB_NonNegative"), "Number");
}
if(Character == null)
{
throw new ArgumentNullException("Character");
}
else if(Character is String)
{
return StrDup(Number, (String)Character);
}
else if(Character is Char)
{
return StrDup(Number, (Char)Character);
}
else
{
try
{
return StrDup(Number, CharType.FromObject(Character));
}
catch(Exception)
{
throw new ArgumentException
(S._("VB_NotAChar"), "Character");
}
}
}
// Reverse the contents of a string.
public static String StrReverse(String Expression)
{
if(Expression == null || Expression.Length == 0)
{
return String.Empty;
}
StringBuilder builder = new StringBuilder();
int posn;
for(posn = Expression.Length - 1; posn >= 0; --posn)
{
builder.Append(Expression[posn]);
}
return builder.ToString();
}
}; // class Strings
}; // namespace Microsoft.VisualBasic
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.IO;
using System.Globalization;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the implementation of the 'Clear-RecycleBin' cmdlet.
/// This cmdlet clear all files in the RecycleBin for the given DriveLetter.
/// If not DriveLetter is specified, then the RecycleBin for all drives are cleared.
/// </summary>
[Cmdlet(VerbsCommon.Clear, "RecycleBin", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=524082", ConfirmImpact = ConfirmImpact.High)]
public class ClearRecycleBinCommand : PSCmdlet
{
private string[] _drivesList;
private DriveInfo[] _availableDrives;
private bool _force;
/// <summary>
/// Property that sets DriveLetter parameter.
/// </summary>
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] DriveLetter
{
get { return _drivesList; }
set { _drivesList = value; }
}
/// <summary>
/// Property that sets force parameter. This will allow to clear the recyclebin.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
/// <summary>
/// This method implements the BeginProcessing method for Clear-RecycleBin command.
/// </summary>
protected override void BeginProcessing()
{
_availableDrives = DriveInfo.GetDrives();
}
/// <summary>
/// This method implements the ProcessRecord method for Clear-RecycleBin command.
/// </summary>
protected override void ProcessRecord()
{
// There are two scenarios:
// 1) The user provides a list of drives.
if (_drivesList != null)
{
foreach (var drive in _drivesList)
{
if (!IsValidPattern(drive))
{
WriteError(new ErrorRecord(
new ArgumentException(
string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveNameFormat, "C", "C:", "C:\\")),
"InvalidDriveNameFormat",
ErrorCategory.InvalidArgument,
drive));
continue;
}
// Get the full path for the drive.
string drivePath = GetDrivePath(drive);
if (ValidDrivePath(drivePath))
{
EmptyRecycleBin(drivePath);
}
}
}
else
{
// 2) No drivesList is provided by the user.
EmptyRecycleBin(null);
}
}
/// <summary>
/// Returns true if the given drive is 'fixed' and its path exist; otherwise, return false.
/// </summary>
/// <param name="drivePath"></param>
/// <returns></returns>
private bool ValidDrivePath(string drivePath)
{
DriveInfo actualDrive = null;
if (_availableDrives != null)
{
foreach (DriveInfo drive in _availableDrives)
{
if (string.Compare(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase) == 0)
{
actualDrive = drive;
break;
}
}
}
// The drive was not found.
if (actualDrive == null)
{
WriteError(new ErrorRecord(
new System.IO.DriveNotFoundException(
string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.DriveNotFound, drivePath, "Get-Volume")),
"DriveNotFound",
ErrorCategory.InvalidArgument,
drivePath));
}
else
{
if (actualDrive.DriveType == DriveType.Fixed)
{
// The drive path exists, and the drive is 'fixed'.
return true;
}
WriteError(new ErrorRecord(
new ArgumentException(
string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.InvalidDriveType, drivePath, "Get-Volume")),
"InvalidDriveType",
ErrorCategory.InvalidArgument,
drivePath));
}
return false;
}
/// <summary>
/// Returns true if the given input is of the form c, c:, c:\, C, C: or C:\
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private bool IsValidPattern(string input)
{
return Regex.IsMatch(input, @"^[a-z]{1}$|^[a-z]{1}:$|^[a-z]{1}:\\$", RegexOptions.IgnoreCase);
}
/// <summary>
/// Returns a drive path of the form C:\ for the given drive driveName.
/// Supports the following inputs: C, C:, C:\
/// </summary>
/// <param name="driveName"></param>
/// <returns></returns>
private string GetDrivePath(string driveName)
{
string drivePath;
if (driveName.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
{
drivePath = driveName;
}
else if (driveName.EndsWith(":", StringComparison.OrdinalIgnoreCase))
{
drivePath = driveName + "\\";
}
else
{
drivePath = driveName + ":\\";
}
return drivePath;
}
/// <summary>
/// Clear the recyclebin for the given drive name.
/// If no driveName is provided, it clears the recyclebin for all drives.
/// </summary>
/// <param name="drivePath"></param>
private void EmptyRecycleBin(string drivePath)
{
string clearRecycleBinShouldProcessTarget;
if (drivePath == null)
{
clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture,
ClearRecycleBinResources.ClearRecycleBinContent);
}
else
{
clearRecycleBinShouldProcessTarget = string.Format(CultureInfo.InvariantCulture,
ClearRecycleBinResources.ClearRecycleBinContentForDrive,
drivePath);
}
if (_force || (ShouldProcess(clearRecycleBinShouldProcessTarget, "Clear-RecycleBin")))
{
// If driveName is null, then clear the recyclebin for all drives; otherwise, just for the specified driveName.
string activity = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinProgressActivity);
string statusDescription;
if (drivePath == null)
{
statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionForAllDrives);
}
else
{
statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionByDrive, drivePath);
}
ProgressRecord progress = new ProgressRecord(0, activity, statusDescription);
progress.PercentComplete = 30;
progress.RecordType = ProgressRecordType.Processing;
WriteProgress(progress);
uint result = NativeMethod.SHEmptyRecycleBin(IntPtr.Zero, drivePath,
NativeMethod.RecycleFlags.SHERB_NOCONFIRMATION |
NativeMethod.RecycleFlags.SHERB_NOPROGRESSUI |
NativeMethod.RecycleFlags.SHERB_NOSOUND);
int lastError = Marshal.GetLastWin32Error();
// update the progress bar to completed
progress.PercentComplete = 100;
progress.RecordType = ProgressRecordType.Completed;
WriteProgress(progress);
// 0 is for a successful operation
// 203 comes up when trying to empty an already emptied recyclebin
// 18 comes up when there are no more files in the given recyclebin
if (!(lastError == 0 || lastError == 203 || lastError == 18))
{
Win32Exception exception = new Win32Exception(lastError);
WriteError(new ErrorRecord(exception, "FailedToClearRecycleBin", ErrorCategory.InvalidOperation, "RecycleBin"));
}
}
}
}
internal static class NativeMethod
{
// Internal code to SHEmptyRecycleBin
internal enum RecycleFlags : uint
{
SHERB_NOCONFIRMATION = 0x00000001,
SHERB_NOPROGRESSUI = 0x00000002,
SHERB_NOSOUND = 0x00000004
}
[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// a set of lightweight static helpers for lazy initialization.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Threading
{
/// <summary>
/// Provides lazy initialization routines.
/// </summary>
/// <remarks>
/// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
/// references to ensure targets have been initialized as they are accessed.
/// </remarks>
public static class LazyInitializer
{
/// <summary>
/// Initializes a target reference type with the type's default constructor if the target has not
/// already been initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="System.MissingMemberException">Type <typeparamref name="T"/> does not have a default
/// constructor.</exception>
/// <exception cref="System.MemberAccessException">
/// Permissions to access the constructor of type <typeparamref name="T"/> were missing.
/// </exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types. To ensure initialization of value
/// types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>([NotNull] ref T? target) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target);
/// <summary>
/// Initializes a target reference type with the type's default constructor (slow path)
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>([NotNull] ref T? target) where T : class
{
try
{
Interlocked.CompareExchange(ref target, Activator.CreateInstance<T>(), null!);
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference type using the specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <param name="valueFactory">The <see cref="System.Func{T}"/> invoked to initialize the
/// reference.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="System.MissingMemberException">Type <typeparamref name="T"/> does not have a
/// default constructor.</exception>
/// <exception cref="System.InvalidOperationException"><paramref name="valueFactory"/> returned
/// null.</exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types, and <paramref name="valueFactory"/> may
/// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or
/// to allow null reference types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory);
/// <summary>
/// Initialize the target using the given delegate (slow path).
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <param name="valueFactory">The delegate that will be executed to initialize the target</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class
{
T value = valueFactory();
if (value == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
Interlocked.CompareExchange(ref target, value, null!);
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference or value type with its default constructor if it has not already
/// been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the type's default constructor to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
try
{
target = Activator.CreateInstance<T>();
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference or value type with a specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="System.Func{T}"/> invoked to initialize the
/// reference or value.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock, Func<T> valueFactory)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock, Func<T> valueFactory)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
target = valueFactory();
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference type with a specified function if it has not already been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="System.Func{T}"/> invoked to initialize the reference.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>([NotNull] ref T? target, [NotNull] ref object? syncLock, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
/// Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>([NotNull] ref T? target, [NotNull] ref object? syncLock, Func<T> valueFactory) where T : class
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (Volatile.Read(ref target) == null)
{
Volatile.Write(ref target, valueFactory());
if (target == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
}
}
return target!; // TODO-NULLABLE: Compiler can't infer target's non-nullness (https://github.com/dotnet/roslyn/issues/37300)
}
/// <summary>
/// Ensure the lock object is initialized.
/// </summary>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <returns>Initialized lock object.</returns>
private static object EnsureLockInitialized([NotNull] ref object? syncLock) =>
syncLock ??
Interlocked.CompareExchange(ref syncLock, new object(), null) ??
syncLock;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.