context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: Context.cs ** ** ** Purpose: Remoting Context core implementation. ** ** ===========================================================*/ namespace System.Runtime.Remoting.Contexts { using System; using System.Security; using System.Security.Permissions; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Globalization; using System.Diagnostics.Contracts; // CallBacks provide a facility to request execution of some code // in another context. // CrossContextDelegate type is defined for context call backs. // Each context has a CallBackObject which can be used to perform // callbacks on the context. The delegate used to request a callback // through the CallBackObject must be of CrossContextDelegate type. /// <internalonly/> [System.Runtime.InteropServices.ComVisible(true)] public delegate void CrossContextDelegate(); /// <internalonly/> // deliberately not [serializable] [System.Runtime.InteropServices.ComVisible(true)] public class Context { // flags to mark the state of the context object // marks the context as the default context internal const int CTX_DEFAULT_CONTEXT = 0x00000001; // marks the context as frozen internal const int CTX_FROZEN = 0x00000002; // Tells the context channel that the context has properties // that use the threadPool themselves. // In that case, the channel does not itself use threadPool. // This is OFF by default internal const int CTX_THREADPOOL_AWARE = 0x00000004; private const int GROW_BY = 0x8; private const int STATICS_BUCKET_SIZE = 0x8; private IContextProperty[] _ctxProps; // array of name-value pairs of properties private DynamicPropertyHolder _dphCtx; // Support for Dynamic Sinks private volatile LocalDataStoreHolder _localDataStore; private IMessageSink _serverContextChain; private IMessageSink _clientContextChain; private AppDomain _appDomain; // AppDomain property of the context private Object[] _ctxStatics; // Holder for context statics //********************** // This needs to be the first NON-OBJECT field! private IntPtr _internalContext; // address of the VM context object! //********************** // at this point we just differentiate contexts based on context ID private int _ctxID; private int _ctxFlags; private int _numCtxProps; // current count of properties // Context statics stuff private int _ctxStaticsCurrentBucket; private int _ctxStaticsFreeIndex; // Support for dynamic properties. private static DynamicPropertyHolder _dphGlobal = new DynamicPropertyHolder(); // Support for Context Local Storage private static LocalDataStoreMgr _localDataStoreMgr = new LocalDataStoreMgr(); // ContextID counter (for public context id) private static int _ctxIDCounter = 0; // < /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public Context() : this(0) { } [System.Security.SecurityCritical] // auto-generated private Context(int flags) { _ctxFlags = flags; if ((_ctxFlags & CTX_DEFAULT_CONTEXT) != 0) { _ctxID = 0; // ID 0 == default context } else { _ctxID = Interlocked.Increment(ref _ctxIDCounter); } // Every context inherits the appdomain level properties // Get the properties for the appdomain and add it to // this context. DomainSpecificRemotingData data = Thread.GetDomain().RemotingData; if(null != data) { IContextProperty[] ctxProps = data.AppDomainContextProperties; if(null != ctxProps) { for(int i = 0; i < ctxProps.Length; i++) { SetProperty(ctxProps[i]); } } } // Freeze the default context now if ((_ctxFlags & CTX_DEFAULT_CONTEXT) != 0) { this.Freeze(); } // This call will set up the cycles between the VM & managed context // It will also set the managed context's AppDomain property to // the current AppDomain.Will also publish ifthe default ctx, so should be // in the very end SetupInternalContext((_ctxFlags&CTX_DEFAULT_CONTEXT) == CTX_DEFAULT_CONTEXT); Message.DebugOut("Creating Context with ID " + _ctxID + " and flags " + flags + " " + Environment.NewLine); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void SetupInternalContext(bool bDefault); /// <internalonly/> [System.Security.SecuritySafeCritical] // auto-generated ~Context() { // We clean up the backing objects only for the non-default // contexts. For default contexts these are cleaned up during // AppDomain shutdown. if (_internalContext != IntPtr.Zero && (_ctxFlags & CTX_DEFAULT_CONTEXT) == 0) { CleanupInternalContext(); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void CleanupInternalContext(); /// <internalonly/> public virtual Int32 ContextID { [System.Security.SecurityCritical] // auto-generated_required get { return _ctxID; } } internal virtual IntPtr InternalContextID { get { return _internalContext; } } internal virtual AppDomain AppDomain { get {return _appDomain;} } internal bool IsDefaultContext { get { return _ctxID == 0; } } /// <internalonly/> public static Context DefaultContext { [System.Security.SecurityCritical] // auto-generated_required get { return Thread.GetDomain().GetDefaultContext(); } } [System.Security.SecurityCritical] // auto-generated internal static Context CreateDefaultContext() { return new Context(CTX_DEFAULT_CONTEXT); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public virtual IContextProperty GetProperty(String name) { if (_ctxProps == null || name == null) { return null; } IContextProperty prop = null; for (int i=0; i<_numCtxProps; i++) { if (_ctxProps[i].Name.Equals(name)) { prop = _ctxProps[i]; break; } } return prop; } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public virtual void SetProperty(IContextProperty prop) { // We do not let people add properties to the default context. /* We allow appdomain level properties to be added to the default context if ((_ctxFlags & CTX_DEFAULT_CONTEXT) != 0) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AddContextFrozen")); } */ if (prop == null || prop.Name == null) { throw new ArgumentNullException((prop==null) ? "prop" : "property name"); } Contract.EndContractBlock(); if ((_ctxFlags & CTX_FROZEN) != 0) { throw new InvalidOperationException( Environment.GetResourceString("InvalidOperation_AddContextFrozen")); } lock (this) { // Check if we have a property by this name CheckPropertyNameClash(prop.Name, _ctxProps, _numCtxProps); // check if we need to grow the array. if (_ctxProps == null || _numCtxProps == _ctxProps.Length) { _ctxProps = GrowPropertiesArray(_ctxProps); } // now add the property _ctxProps[_numCtxProps++] = prop; } } [System.Security.SecurityCritical] // auto-generated internal virtual void InternalFreeze() { _ctxFlags |= CTX_FROZEN; // From this point on attempts to add properties will throw // So we don't need to take a lock. for (int i=0; i<_numCtxProps; i++) { _ctxProps[i].Freeze(this); } } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public virtual void Freeze() { lock(this) { if ((_ctxFlags & CTX_FROZEN) != 0) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ContextAlreadyFrozen")); } InternalFreeze(); } } internal virtual void SetThreadPoolAware() { // Cannot turn off ThreadPool support for the default context Contract.Assert( (_ctxFlags & CTX_DEFAULT_CONTEXT) == 0, "This operation is not allowed on the default context!"); _ctxFlags |= CTX_THREADPOOL_AWARE; } internal virtual bool IsThreadPoolAware { get { return (_ctxFlags & CTX_THREADPOOL_AWARE) == CTX_THREADPOOL_AWARE;} } /// <internalonly/> public virtual IContextProperty[] ContextProperties { // we return a copy of the current set of properties // the user may iterate from 0 to array.length on it. [System.Security.SecurityCritical] // auto-generated_required get { if (_ctxProps == null) { return null; } lock (this) { IContextProperty[] retProps = new IContextProperty[_numCtxProps]; Array.Copy(_ctxProps, retProps, _numCtxProps); return retProps; } } } [System.Security.SecurityCritical] // auto-generated internal static void CheckPropertyNameClash(String name, IContextProperty[] props, int count) { for (int i=0; i<count; i++) { if (props[i].Name.Equals(name)) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_DuplicatePropertyName")); } } } internal static IContextProperty[] GrowPropertiesArray(IContextProperty[] props) { // grow the array of IContextProperty objects int newSize = (props != null ? props.Length : 0) + GROW_BY; IContextProperty[] newProps = new IContextProperty[newSize]; if (props != null) { // Copy existing properties over. Array.Copy(props, newProps, props.Length); } return newProps; } [System.Security.SecurityCritical] // auto-generated internal virtual IMessageSink GetServerContextChain() { if (_serverContextChain == null) { // a bare chain would have just this one sink. IMessageSink newServerContextChain = ServerContextTerminatorSink.MessageSink; // now loop over properties to add some real sinks. Object prop = null; int iSink = _numCtxProps; while (iSink-- > 0) { // see if this property wants to contribute a ServerContextSink // we have to start chaining in the reverse order prop = _ctxProps[iSink]; IContributeServerContextSink sink = prop as IContributeServerContextSink; if (null != sink ) { // yes, chain the sink ahead of the chain of sinks constructed so far. newServerContextChain = sink.GetServerContextSink( newServerContextChain); if (newServerContextChain == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Contexts_BadProperty")); } } } lock (this) { if (_serverContextChain == null) { _serverContextChain = newServerContextChain; } } } return _serverContextChain; } [System.Security.SecurityCritical] // auto-generated internal virtual IMessageSink GetClientContextChain() { Message.DebugOut("Context::GetClientContextChain: IN _ctxID =" + _ctxID + Environment.NewLine); if (_clientContextChain == null) { Message.DebugOut("Context::GetClientContextChain: _clientContextChain == null, creating chain" + Environment.NewLine); // a bare chain would have just this one sink. IMessageSink newClientContextChain = ClientContextTerminatorSink.MessageSink; // now loop over properties to add some real sinks. // Note that for the client chain we go through the properties // in the reverse order as compared to the server chain. // Thus if a lock was taken as the last action of an incoming // call, it is released as the first action of an outgoing call. Object prop = null; int iSink = 0; while (iSink < _numCtxProps) { Message.DebugOut("Context::GetClientContextChain: checking property " + _ctxProps[iSink].Name + Environment.NewLine); // see if this property wants to contribute a ClientContextSink // we have to start chaining in the reverse order prop = _ctxProps[iSink]; IContributeClientContextSink sink = prop as IContributeClientContextSink; if (null != sink) { Message.DebugOut("Context::GetClientContextChain: calling GetClientContextSink on " + _ctxProps[iSink].Name + Environment.NewLine); // yes, chain the sink ahead of the chain of sinks constructed so far. newClientContextChain = sink.GetClientContextSink(newClientContextChain); if (newClientContextChain == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Contexts_BadProperty")); } } iSink++; } // now check if we ----d and set appropriately lock (this) { if (_clientContextChain==null) { _clientContextChain = newClientContextChain; } // else the chain we created should get GC-ed. } } return _clientContextChain; } [System.Security.SecurityCritical] // auto-generated internal virtual IMessageSink CreateServerObjectChain(MarshalByRefObject serverObj) { // a bare chain would just be the dispatcher sink IMessageSink serverObjectChain = new ServerObjectTerminatorSink(serverObj); // now loop over properties to add some real sinks. Object prop = null; int iSink = _numCtxProps; while (iSink-- > 0) { // see if this property wants to contribute a ServerObjectSink // we have to start chaining in the reverse order prop = _ctxProps[iSink]; IContributeObjectSink sink = prop as IContributeObjectSink; if (null != sink) { // yes, chain the sink ahead of the chain of sinks constructed so far. serverObjectChain = sink.GetObjectSink( serverObj, serverObjectChain); if (serverObjectChain == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Contexts_BadProperty")); } } } return serverObjectChain; } [System.Security.SecurityCritical] // auto-generated internal virtual IMessageSink CreateEnvoyChain(MarshalByRefObject objectOrProxy) { // a bare chain would just be the dispatcher sink IMessageSink envoyChain = EnvoyTerminatorSink.MessageSink; // now loop over properties to add some real sinks. // Note: the sinks in the envoy chain should be in mirror image // order relative to sinks on the server side Object prop = null; int iSink = 0; MarshalByRefObject exposedObj = objectOrProxy; while (iSink < _numCtxProps) { // see if this property wants to contribute a ClientContextSink // we have to start chaining in the reverse order prop = _ctxProps[iSink]; IContributeEnvoySink sink = prop as IContributeEnvoySink; if (null != sink) { // yes, chain the sink ahead of the chain of sinks constructed so far. envoyChain = sink.GetEnvoySink(exposedObj, envoyChain); if (envoyChain == null) { throw new RemotingException( Environment.GetResourceString( "Remoting_Contexts_BadProperty")); } } iSink++; } return envoyChain; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~ Activation Support ~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [System.Security.SecurityCritical] // auto-generated internal IMessage NotifyActivatorProperties( IMessage msg, bool bServerSide) { Contract.Assert( (msg is IConstructionCallMessage) || (msg is IConstructionReturnMessage), "Bad activation msg type"); Contract.Assert( !((msg is IConstructionCallMessage) && (msg is IConstructionReturnMessage)), "Activation message cannot be both call & return type"); Contract.Assert((_ctxFlags & CTX_FROZEN) == CTX_FROZEN, "ServerContext not frozen during activation!"); // Any exception thrown by the notifications is caught and // folded into a return message to return to the caller. IMessage errMsg = null; try { // Since the context is frozen the properties array is in // effect read-only! int iProp = _numCtxProps; Object prop = null; while (iProp-- != 0) { // see if this property is interested in Activation prop = _ctxProps[iProp]; IContextPropertyActivator activator = prop as IContextPropertyActivator; if (null != activator) { // yes, notify as appropriate IConstructionCallMessage ccm = msg as IConstructionCallMessage; if (null != ccm) { // IConsructionCallMessage on its way forward if (!bServerSide) { // activation starting at client side activator.CollectFromClientContext(ccm); } else { // activation starting at server side // activator.DeliverClientContextToServerContext(ccm); } } else { // IConstructionReturnMessage on its way back if (bServerSide) { // activation returning from server side activator.CollectFromServerContext((IConstructionReturnMessage)msg); } else { // activation back at client side // < activator.DeliverServerContextToClientContext((IConstructionReturnMessage)msg); } } } } } catch (Exception e) { IMethodCallMessage mcm = null; if (msg is IConstructionCallMessage) { mcm = (IMethodCallMessage) msg; } else { mcm = new ErrorMessage(); } errMsg = new ReturnMessage(e, mcm); if (msg != null) { ((ReturnMessage)errMsg).SetLogicalCallContext( (LogicalCallContext) msg.Properties[Message.CallContextKey]); } } return errMsg; } /// <internalonly/> public override String ToString() { return "ContextID: " + _ctxID; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~ Transition Support ~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This is the simple cross-context call back function invoke on // the context to do a call-back in. /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public void DoCallBack(CrossContextDelegate deleg) { /*DBG Console.WriteLine("public DoCallBack: targetCtx: " + Int32.Format(this.InternalContextID,"x")); DBG*/ if (deleg == null) { throw new ArgumentNullException("deleg"); } Contract.EndContractBlock(); if ((_ctxFlags & CTX_FROZEN) == 0) { throw new RemotingException( Environment.GetResourceString( "Remoting_Contexts_ContextNotFrozenForCallBack")); } Context currCtx = Thread.CurrentContext; if (currCtx == this) { // We are already in the target context, just execute deleg // NOTE: If in the future we decide to leave the context // and reenter it for this case we will need to change // Context::RequestCallBack method in VM also! deleg(); } else { // We pass 0 for target domain ID for x-context case. currCtx.DoCallBackGeneric(this.InternalContextID, deleg); GC.KeepAlive(this); } } // This is called when EE needs to do a transition and execute some // code. Before calling, EE determines if this is a x-domain case. // targetDomainID will be 0 if it is a simple x-context call. //< [System.Security.SecurityCritical] // auto-generated internal static void DoCallBackFromEE( IntPtr targetCtxID, IntPtr privateData, int targetDomainID) { Contract.Assert(targetCtxID != IntPtr.Zero, "Bad transition context"); /*DBG Console.WriteLine("private DoCallBackFromEE: targetCtx: " + Int32.Format(targetCtxID,"x") + " PvtData: " + Int32.Format(privateData,"x"));DBG*/ if (targetDomainID == 0) { CallBackHelper cb = new CallBackHelper( privateData, true /*fromEE*/, targetDomainID); CrossContextDelegate ctxDel = new CrossContextDelegate(cb.Func); Thread.CurrentContext.DoCallBackGeneric(targetCtxID, ctxDel); } else { // for x-appdomain calls, we can't pass a delegate since that // would require us to deserialize it on the other side which // is not allowed for non-public methods. TransitionCall msgCall = new TransitionCall(targetCtxID, privateData, targetDomainID); Message.PropagateCallContextFromThreadToMessage(msgCall); //DBG Console.WriteLine("CallBackGeneric starting!"); IMessage retMsg = Thread.CurrentContext.GetClientContextChain().SyncProcessMessage(msgCall); Message.PropagateCallContextFromMessageToThread(retMsg); IMethodReturnMessage msg = retMsg as IMethodReturnMessage; if (null != msg) { if (msg.Exception != null) throw msg.Exception; } } } // DoCallBackFromEE // This is called by both the call back functions above. [System.Security.SecurityCritical] // auto-generated internal void DoCallBackGeneric( IntPtr targetCtxID, CrossContextDelegate deleg) { TransitionCall msgCall = new TransitionCall(targetCtxID, deleg); Message.PropagateCallContextFromThreadToMessage(msgCall); //DBG Console.WriteLine("CallBackGeneric starting!"); IMessage retMsg = this.GetClientContextChain().SyncProcessMessage(msgCall); if (null != retMsg) { Message.PropagateCallContextFromMessageToThread(retMsg); } IMethodReturnMessage msg = retMsg as IMethodReturnMessage; if (null != msg) { if (msg.Exception != null) throw msg.Exception; } //DBG Console.WriteLine("CallBackGeneric finished!"); } // This is the E-Call that we route the EE-CallBack request to [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void ExecuteCallBackInEE(IntPtr privateData); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~ Context Local Store ~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private LocalDataStore MyLocalStore { get { if (_localDataStore == null) { // It's OK to lock the manager here because it is going to lock // itself anyway. lock (_localDataStoreMgr) { if (_localDataStore == null) { // The local store has not yet been created for this thread. _localDataStore = _localDataStoreMgr.CreateLocalDataStore(); } } } return _localDataStore.Store; } } // All of these are exact shadows of corresponding ThreadLocalStore // APIs. /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static LocalDataStoreSlot AllocateDataSlot() { return _localDataStoreMgr.AllocateDataSlot(); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static LocalDataStoreSlot AllocateNamedDataSlot(String name) { return _localDataStoreMgr.AllocateNamedDataSlot(name); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static LocalDataStoreSlot GetNamedDataSlot(String name) { return _localDataStoreMgr.GetNamedDataSlot(name); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static void FreeNamedDataSlot(String name) { _localDataStoreMgr.FreeNamedDataSlot(name); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static void SetData(LocalDataStoreSlot slot, Object data) { Thread.CurrentContext.MyLocalStore.SetData(slot, data); } /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required public static Object GetData(LocalDataStoreSlot slot) { return Thread.CurrentContext.MyLocalStore.GetData(slot); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~ Context Statics ~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private int ReserveSlot() { // This will be called with the context crst held so we // don't take a lock here) if (_ctxStatics == null) { // allocate the first bucket _ctxStatics = new Object[STATICS_BUCKET_SIZE]; // set next bucket field to null _ctxStatics[0] = null; _ctxStaticsFreeIndex = 1; _ctxStaticsCurrentBucket = 0; } // See if we have to allocate a new bucket if (_ctxStaticsFreeIndex == STATICS_BUCKET_SIZE) { Object[] newBucket = new Object[STATICS_BUCKET_SIZE]; // walk the chain to locate the last bucket Object[] bucket = _ctxStatics; while (bucket[0] != null) { bucket = (Object[]) bucket[0]; } // chain in the new bucket bucket[0] = newBucket; _ctxStaticsFreeIndex = 1; _ctxStaticsCurrentBucket++; } // bucket# in highWord, index in lowWord return _ctxStaticsFreeIndex++|_ctxStaticsCurrentBucket<<16; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~ End Context Statics ~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~ Dynamic Sink Support ~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This allows people to register a property implementing IContributeDynamicSink // with the remoting service. Based on the obj and ctx parameters, the property // is asked to contribute a sink that is placed at some location in the path of // remoting calls. // The property may be unregistered, which implies that the sink will be dropped // for subsequent remoting calls. // If multiple properties are registered, their sinks may be called in an // arbitrary order which may change between calls. // // If obj is non null then: // - if it is a proxy, all calls made on the proxy are intercepted // - if it is a real object, all calls on the object are intercepted // - the ctx argument must be null // If ctx is non-null then: // - the obj argument must be null // - all calls entering and leaving the context are intercepted // If both ctx and obj are null then: // - all calls entering and leaving all contexts are intercepted // /// <internalonly/> [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.Infrastructure)] public static bool RegisterDynamicProperty(IDynamicProperty prop, ContextBoundObject obj, Context ctx) { bool fRegistered = false; if (prop == null || prop.Name == null || !(prop is IContributeDynamicSink)) { throw new ArgumentNullException("prop"); } if (obj != null && ctx != null) { // Exactly one of these is allowed to be non-null. throw new ArgumentException(Environment.GetResourceString("Argument_NonNullObjAndCtx")); } if (obj != null) { // ctx is ignored and must be null. fRegistered = IdentityHolder.AddDynamicProperty(obj, prop); } else { // ctx may or may not be null fRegistered = Context.AddDynamicProperty(ctx, prop); } return fRegistered; } /// <internalonly/> [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.Infrastructure)] public static bool UnregisterDynamicProperty(String name, ContextBoundObject obj, Context ctx) { // name, obj, ctx arguments should be exactly the same as a previous // RegisterDynamicProperty call if (name == null) { throw new ArgumentNullException("name"); } if (obj != null && ctx != null) { throw new ArgumentException(Environment.GetResourceString("Argument_NonNullObjAndCtx")); } Contract.EndContractBlock(); bool fUnregister = false; if (obj != null) { // ctx is ignored and must be null. fUnregister = IdentityHolder.RemoveDynamicProperty(obj, name); } else { // ctx may or may not be null fUnregister = Context.RemoveDynamicProperty(ctx, name); } return fUnregister; } /* * Support for dynamic sinks at context level * */ [System.Security.SecurityCritical] // auto-generated internal static bool AddDynamicProperty(Context ctx, IDynamicProperty prop) { // Check if we have a property by this name if (ctx != null) { return ctx.AddPerContextDynamicProperty(prop); } else { // We have to add a sink that should fire for all contexts return AddGlobalDynamicProperty(prop); } } [System.Security.SecurityCritical] // auto-generated private bool AddPerContextDynamicProperty(IDynamicProperty prop) { if (_dphCtx == null) { DynamicPropertyHolder dph = new DynamicPropertyHolder(); lock (this) { if (_dphCtx == null) { _dphCtx = dph; } } } return _dphCtx.AddDynamicProperty(prop); } [System.Security.SecurityCritical] // auto-generated private static bool AddGlobalDynamicProperty(IDynamicProperty prop) { return _dphGlobal.AddDynamicProperty(prop); } [System.Security.SecurityCritical] // auto-generated internal static bool RemoveDynamicProperty(Context ctx, String name) { if (ctx != null) { return ctx.RemovePerContextDynamicProperty(name); } else { // We have to remove a global property return RemoveGlobalDynamicProperty(name); } } [System.Security.SecurityCritical] // auto-generated private bool RemovePerContextDynamicProperty(String name) { // We have to remove a property for this context if (_dphCtx == null) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Contexts_NoProperty"), name )); } return _dphCtx.RemoveDynamicProperty(name); } [System.Security.SecurityCritical] // auto-generated private static bool RemoveGlobalDynamicProperty(String name) { return _dphGlobal.RemoveDynamicProperty(name); } /* * Returns an array of context specific dynamic properties * registered for this context. The number of such properties * is designated by length of the returned array. */ internal virtual IDynamicProperty[] PerContextDynamicProperties { get { if (_dphCtx == null) { return null; } else { return _dphCtx.DynamicProperties; } } } /* * Returns an array of global dynamic properties * registered (for all contexts). The number of such properties * is designated by length of the returned array. */ internal static ArrayWithSize GlobalDynamicSinks { [System.Security.SecurityCritical] // auto-generated get { return _dphGlobal.DynamicSinks; } } internal virtual ArrayWithSize DynamicSinks { [System.Security.SecurityCritical] // auto-generated get { if (_dphCtx == null) { return null; } else { return _dphCtx.DynamicSinks; } } } [System.Security.SecurityCritical] // auto-generated internal virtual bool NotifyDynamicSinks( IMessage msg, bool bCliSide, bool bStart, bool bAsync, bool bNotifyGlobals) { bool bHasDynamicSinks = false; if (bNotifyGlobals && (_dphGlobal.DynamicProperties != null)) { ArrayWithSize globalSinks = GlobalDynamicSinks; if (globalSinks != null) { DynamicPropertyHolder.NotifyDynamicSinks( msg, globalSinks, bCliSide, bStart, bAsync); bHasDynamicSinks = true; } } ArrayWithSize perCtxSinks = DynamicSinks; if (perCtxSinks != null) { DynamicPropertyHolder.NotifyDynamicSinks( msg, perCtxSinks, bCliSide, bStart, bAsync); bHasDynamicSinks = true; } return bHasDynamicSinks; } // NotifyDynamicSinks //******************** END: Dynamic Sink Support ******************** } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~ More Transition Support ~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // This class is used as the backing object that implements a delegate // function to be used for internal call-backs. The delegate type must // be CrossContextDelegate (void Func(void) below) since we are using // the DoCallBackGeneric also as the underlying mechanism for the // exposed cross-context callbacks. [Serializable] internal class CallBackHelper { // Some flag definitions internal const int RequestedFromEE = 0x00000001; // callBack from EE internal const int XDomainTransition= 0x00000100; // going x-domain internal bool IsEERequested { get {return (_flags&RequestedFromEE)==RequestedFromEE;} set {if (value) {_flags |= RequestedFromEE;}} } internal bool IsCrossDomain { set {if (value) {_flags |= XDomainTransition;}} } int _flags; IntPtr _privateData; internal CallBackHelper(IntPtr privateData, bool bFromEE, int targetDomainID) { this.IsEERequested = bFromEE; this.IsCrossDomain = (targetDomainID!=0); _privateData = privateData; } [System.Security.SecurityCritical] // auto-generated internal void Func() { /*DBG Console.WriteLine("DelegHelper::Func CTX:" + Int32.Format(Thread.CurrentContext.InternalContextID,"x") +Environment.NewLine + "DMN: " + Int32.Format(Thread.GetDomainID(),"x")); DBG*/ if (IsEERequested) { //DBG Console.WriteLine("Executing EE callback "); // EE requested this call back, call EE with its private data Context.ExecuteCallBackInEE(_privateData); //DBG Console.WriteLine("Execute CallBackInEE returned: " + Int32.Format(_retVal,"x")); } else { //DBG Console.WriteLine("Executing non-EE internal callback"); } } } // class CallBackHelper } //nameSpace Remoting
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO namespace NLog.UnitTests.Config { using System; using System.IO; using System.Threading; using NLog.Config; using Xunit; public class ReloadTests : NLogTestBase { public ReloadTests() { if (LogManager.LogFactory != null) { LogManager.LogFactory.ResetLoggerCache(); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestNoAutoReload(bool useExplicitFileLoading) { string config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "noreload.nlog"); WriteConfigFile(configFilePath, config1); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } private static void SetLogManagerConfiguration(bool useExplicitFileLoading, string configFilePath) { if (useExplicitFileLoading) LogManager.Configuration = new XmlLoggingConfiguration(configFilePath); else LogManager.LogFactory.SetCandidateConfigFilePaths(new string[] { configFilePath }); } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileChange(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileChange because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string badConfig = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false); logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); ChangeAndReloadConfigFile(configFilePath, config2); logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileMove(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileMove because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempPath, "other.nlog"); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(configFilePath, otherFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Move(otherFilePath, configFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestAutoReloadOnFileCopy(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileCopy because we are running in Travis"); return; } #endif string config1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string configFilePath = Path.Combine(tempPath, "reload.nlog"); WriteConfigFile(configFilePath, config1); string otherFilePath = Path.Combine(tempPath, "other.nlog"); try { SetLogManagerConfiguration(useExplicitFileLoading, configFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Delete(configFilePath); reloadWaiter.WaitForReload(); } logger.Debug("bbb"); // Assert that config1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(otherFilePath, config2); using (var reloadWaiter = new ConfigurationReloadWaiter()) { File.Copy(otherFilePath, configFilePath); File.Delete(otherFilePath); reloadWaiter.WaitForReload(); Assert.True(reloadWaiter.DidReload); } logger.Debug("ccc"); // Assert that config2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestIncludedConfigNoReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false); logger.Debug("ccc"); // Assert that includedConfig1 is still loaded. AssertDebugLastMessage("debug", "ccc"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestIncludedConfigReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog> <include file='included.nlog' /> <rules><logger name='*' minlevel='Info' writeTo='debug' /></rules> </nlog>"; string includedConfig1 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string includedConfig2 = @"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string includedConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(includedConfigFilePath, includedConfig1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false); logger.Debug("bbb"); // Assert that mainConfig1 is still loaded. AssertDebugLastMessage("debug", "bbb"); WriteConfigFile(mainConfigFilePath, mainConfig1); ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2); logger.Debug("ccc"); // Assert that includedConfig2 is loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestMainConfigReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2); logger.Debug("ccc"); // Assert that included2Config2 is loaded. AssertDebugLastMessage("debug", "(ccc)"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Theory] [InlineData(true)] [InlineData(false)] public void TestMainConfigReloadIncludedConfigNoReload(bool useExplicitFileLoading) { #if NETSTANDARD || MONO if (IsLinux()) { Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis"); return; } #endif string mainConfig1 = @"<nlog autoReload='true'> <include file='included.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string mainConfig2 = @"<nlog autoReload='true'> <include file='included2.nlog' /> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"; string included1Config = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string included2Config1 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='[${message}]' /></targets> </nlog>"; string included2Config2 = @"<nlog autoReload='false'> <targets><target name='debug' type='Debug' layout='(${message})' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); string mainConfigFilePath = Path.Combine(tempPath, "main.nlog"); WriteConfigFile(mainConfigFilePath, mainConfig1); string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog"); WriteConfigFile(included1ConfigFilePath, included1Config); string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog"); WriteConfigFile(included2ConfigFilePath, included2Config1); try { SetLogManagerConfiguration(useExplicitFileLoading, mainConfigFilePath); var logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2); logger.Debug("bbb"); // Assert that mainConfig2 is loaded (which refers to included2.nlog). AssertDebugLastMessage("debug", "[bbb]"); ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false); logger.Debug("ccc"); // Assert that included2Config1 is still loaded. AssertDebugLastMessage("debug", "[ccc]"); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void TestKeepVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); logFactory.Configuration = configuration; logFactory.Configuration.Variables["var1"] = "new_value"; logFactory.Configuration.Variables["var3"] = "new_value3"; configLoader.ReloadConfigOnTimer(configuration); var nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("new_value", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); logFactory.Setup().ReloadConfiguration(); Assert.Equal("new_value", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); } [Fact] public void TestKeepVariablesOnReloadAllowUpdate() { string config1 = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='old_value2' /> <targets><target name='mem' type='memory' layout='${var:var2}' /></targets> <rules><logger name='*' writeTo='mem' /></rules> </nlog>"; string config2 = @"<nlog autoReload='true' keepVariablesOnReload='true'> <variable name='var1' value='' /> <variable name='var2' value='new_value2' /> <targets><target name='mem' type='memory' layout='${var:var2}' /></targets> <rules><logger name='*' writeTo='mem' /></rules> </nlog>"; var logFactory = new LogFactory(); var xmlConfig = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config1); logFactory.Configuration = xmlConfig; // Act logFactory.Configuration.Variables.Remove("var1"); logFactory.Configuration.Variables.Add("var3", "new_value3"); xmlConfig.ConfigXml = config2; logFactory.Configuration = xmlConfig.Reload(); // Assert var nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("new_value2", logFactory.Configuration.Variables["var2"].Render(nullEvent)); Assert.Equal("new_value3", logFactory.Configuration.Variables["var3"].Render(nullEvent)); } [Fact] public void TestResetVariablesOnReload() { string config = @"<nlog autoReload='true' keepVariablesOnReload='false'> <variable name='var1' value='' /> <variable name='var2' value='keep_value' /> </nlog>"; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); logFactory.Configuration = configuration; logFactory.Configuration.Variables["var1"] = "new_value"; logFactory.Configuration.Variables["var3"] = "new_value3"; configLoader.ReloadConfigOnTimer(configuration); LogEventInfo nullEvent = LogEventInfo.CreateNullEvent(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); logFactory.Configuration = configuration.Reload(); Assert.Equal("", logFactory.Configuration.Variables["var1"].Render(nullEvent)); Assert.Equal("keep_value", logFactory.Configuration.Variables["var2"].Render(nullEvent)); } [Fact] public void KeepVariablesOnReloadWithStaticMode() { // Arrange string config = @"<nlog autoReload='true'> <variable name='maxArchiveDays' value='7' /> <targets> <target name='logfile' type='file' fileName='test.log' maxArchiveDays='${maxArchiveDays}' /> </targets> <rules> <logger name='*' minLevel='Debug' writeTo='logfile' /> </rules> </nlog>"; var logFactory = new LogFactory(); logFactory.Configuration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, config); var fileTarget = logFactory.Configuration.AllTargets[0] as NLog.Targets.FileTarget; var beforeValue = fileTarget.MaxArchiveDays; // Act logFactory.Configuration.Variables["MaxArchiveDays"] = "42"; logFactory.Configuration = logFactory.Configuration.Reload(); fileTarget = logFactory.Configuration.AllTargets[0] as NLog.Targets.FileTarget; var afterValue = fileTarget.MaxArchiveDays; // Assert Assert.Equal(7, beforeValue); Assert.Equal(42, afterValue); } [Fact] public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent() { var called = false; LoggingConfigurationReloadedEventArgs arguments = null; object calledBy = null; var configLoader = new LoggingConfigurationWatchableFileLoader(LogFactory.DefaultAppEnvironment); var logFactory = new LogFactory(configLoader); var loggingConfiguration = XmlLoggingConfigurationMock.CreateFromXml(logFactory, "<nlog></nlog>"); logFactory.Configuration = loggingConfiguration; logFactory.ConfigurationReloaded += (sender, args) => { called = true; calledBy = sender; arguments = args; }; configLoader.ReloadConfigOnTimer(loggingConfiguration); Assert.True(called); Assert.Same(calledBy, logFactory); Assert.True(arguments.Succeeded); } [Fact] public void TestReloadingInvalidConfiguration() { var validXmlConfig = @"<nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"; var invalidXmlConfig = @"<nlog autoReload='true' internalLogLevel='debug' internalLogLevel='error'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); try { using (new NoThrowNLogExceptions()) { var nlogConfigFile = Path.Combine(tempPath, "NLog.config"); LogFactory logFactory = new LogFactory(); logFactory.SetCandidateConfigFilePaths(new[] { nlogConfigFile }); var config = logFactory.Configuration; Assert.Null(config); WriteConfigFile(nlogConfigFile, invalidXmlConfig); config = logFactory.Configuration; Assert.NotNull(config); Assert.Empty(config.AllTargets); // Failed to load Assert.Single(config.FileNamesToWatch); // But file-watcher is active WriteConfigFile(nlogConfigFile, validXmlConfig); config = logFactory.Configuration.Reload(); Assert.Single(config.AllTargets); } } finally { if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } [Fact] public void TestThrowExceptionWhenInvalidXml() { var invalidXmlConfig = @"<nlog throwExceptions='true' internalLogLevel='debug' internalLogLevel='error'> </nlog>"; string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); try { using (new NoThrowNLogExceptions()) { var nlogConfigFile = Path.Combine(tempPath, "NLog.config"); WriteConfigFile(nlogConfigFile, invalidXmlConfig); LogFactory logFactory = new LogFactory(); logFactory.SetCandidateConfigFilePaths(new[] { nlogConfigFile }); Assert.Throws<NLogConfigurationException>(() => logFactory.GetLogger("Hello")); } } finally { if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } private static void WriteConfigFile(string configFilePath, string config) { using (StreamWriter writer = File.CreateText(configFilePath)) writer.Write(config); } private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true) { using (var reloadWaiter = new ConfigurationReloadWaiter()) { WriteConfigFile(configFilePath, config); reloadWaiter.WaitForReload(); if (assertDidReload) Assert.True(reloadWaiter.DidReload, $"Config '{configFilePath}' did not reload."); } } private class ConfigurationReloadWaiter : IDisposable { private ManualResetEvent counterEvent = new ManualResetEvent(false); public ConfigurationReloadWaiter() { LogManager.ConfigurationReloaded += SignalCounterEvent(counterEvent); } public bool DidReload => counterEvent.WaitOne(0); public void Dispose() { LogManager.ConfigurationReloaded -= SignalCounterEvent(counterEvent); } public void WaitForReload() { counterEvent.WaitOne(3000); } private static EventHandler<LoggingConfigurationReloadedEventArgs> SignalCounterEvent(ManualResetEvent counterEvent) { return (sender, e) => { counterEvent.Set(); }; } } } /// <summary> /// Xml config with reload without file-reads for performance /// </summary> public class XmlLoggingConfigurationMock : XmlLoggingConfiguration { public string ConfigXml { get; set; } private XmlLoggingConfigurationMock(LogFactory logFactory, string configXml) :base(logFactory) { ConfigXml = configXml; } public override LoggingConfiguration Reload() { var newConfig = new XmlLoggingConfigurationMock(LogFactory, ConfigXml); newConfig.PrepareForReload(this); newConfig.LoadFromXmlContent(ConfigXml, null); return newConfig; } public static XmlLoggingConfigurationMock CreateFromXml(LogFactory logFactory, string configXml) { var newConfig = new XmlLoggingConfigurationMock(logFactory, configXml); newConfig.LoadFromXmlContent(configXml, null); return newConfig; } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageRepositoryTest { [Fact] public void FindByIdReturnsPackage() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "A"); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); } [Fact] public void FindByIdReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package = repo.FindPackage(packageId: "X"); // Assert Assert.Null(package); } [Fact] public void FindByIdAndVersionReturnsPackage() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.0")); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package1 = repo.FindPackage(packageId: "X", version: SemanticVersion.Parse("1.0")); var package2 = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.1")); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindByIdAndVersionRangeReturnsPackage() { // Arrange var repo = GetRemoteRepository(); var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]"); // Act var package = repo.FindPackage("A", versionSpec, allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound() { // Arrange var repo = GetLocalRepository(); // Act var package1 = repo.FindPackage("X", VersionUtility.ParseVersionSpec("[0.9, 1.1]"), allowPrereleaseVersions: false, allowUnlisted: true); var package2 = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[1.4, 1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.Null(package1 ?? package2); } [Fact] public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull() { // Arrange var repo = GetRemoteRepository(); // Act var package = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[0.6, 1.1.5]"), allowPrereleaseVersions: false, allowUnlisted: true); // Assert Assert.NotNull(package); Assert.Equal("A", package.Id); Assert.Equal(SemanticVersion.Parse("1.0"), package.Version); } [Fact] public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId() { // Arrange var term = "TAG"; var repo = new MockPackageRepository(); repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG ")); repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags")); repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it")); repo.Add(CreateMockPackage("D", "1.0", "Description")); repo.Add(CreateMockPackage("TagCloud", "1.0", "Description")); // Act var packages = repo.GetPackages().Find(term).ToList(); // Assert Assert.Equal(3, packages.Count); Assert.Equal("A", packages[0].Id); Assert.Equal("C", packages[1].Id); Assert.Equal("TagCloud", packages[2].Id); } [Fact] public void FindPackagesReturnsPrereleasePackagesIfTheFlagIsSetToTrue() { // Arrange var term = "B"; var repo = GetRemoteRepository(includePrerelease: true); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(0).Version, new SemanticVersion("1.0")); Assert.Equal(packages.ElementAt(1).Id, "B"); Assert.Equal(packages.ElementAt(1).Version, new SemanticVersion("1.0-beta")); } [Fact] public void FindPackagesReturnsPackagesWithTerm() { // Arrange var term = "B xaml"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.Equal(packages.Count(), 2); packages = packages.OrderBy(p => p.Id); Assert.Equal(packages.ElementAt(0).Id, "B"); Assert.Equal(packages.ElementAt(1).Id, "C"); } [Fact] public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm() { // Arrange var term = "does-not-exist"; var repo = GetRemoteRepository(); // Act var packages = repo.GetPackages().Find(term); // Assert Assert.False(packages.Any()); } [Fact] public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty() { // Arrange var repo = GetLocalRepository(); // Act var packages1 = repo.GetPackages().Find(String.Empty); var packages2 = repo.GetPackages().Find(null); var packages3 = repo.GetPackages(); // Assert Assert.Equal(packages1.ToList(), packages2.ToList()); Assert.Equal(packages2.ToList(), packages3.ToList()); } [Fact] public void SearchUsesInterfaceIfImplementedByRepository() { // Arrange var repo = new Mock<MockPackageRepository>(MockBehavior.Strict); repo.Setup(m => m.GetPackages()).Returns(Enumerable.Empty<IPackage>().AsQueryable()); repo.As<IServiceBasedRepository>().Setup(m => m.Search(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), false)) .Returns(new[] { PackageUtility.CreatePackage("A") }.AsQueryable()); // Act var packages = repo.Object.Search("Hello", new[] { ".NETFramework" }, allowPrereleaseVersions: false).ToList(); // Assert Assert.Equal(1, packages.Count); Assert.Equal("A", packages[0].Id); } [Fact] public void GetUpdatesReturnsPackagesWithUpdates() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetRemoteRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.True(packages.Any()); Assert.Equal(packages.First().Id, "A"); Assert.Equal(packages.First().Version, SemanticVersion.Parse("1.2")); } [Fact] public void GetUpdatesDoesNotInvokeServiceMethodIfLocalRepositoryDoesNotHaveAnyPackages() { // Arrange var localRepo = new MockPackageRepository(); var serviceRepository = new Mock<IServiceBasedRepository>(MockBehavior.Strict); var remoteRepo = serviceRepository.As<IPackageRepository>().Object; // Act remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert serviceRepository.Verify(s => s.GetUpdates(It.IsAny<IEnumerable<IPackage>>(), false, false, It.IsAny<IEnumerable<FrameworkName>>(), It.IsAny<IEnumerable<IVersionSpec>>()), Times.Never()); } [Fact] public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty() { // Arrange var localRepo = GetLocalRepository(); var remoteRepo = GetEmptyRepository(); // Act var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false); // Assert Assert.False(packages.Any()); } [Fact] public void FindDependencyPicksHighestVersionIfNotSpecified() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; var dependency = new PackageDependency("B"); // Act IPackage package = repository.ResolveDependency(dependency, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("2.0"), package.Version); } [Fact] public void FindPackageNormalizesVersionBeforeComparing() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "1.0.0"), PackageUtility.CreatePackage("B", "1.0.0.1") }; // Act IPackage package = repository.FindPackage("B", new SemanticVersion("1.0")); // Assert Assert.Equal("B", package.Id); Assert.Equal(new SemanticVersion("1.0.0"), package.Version); } [Fact] public void FindDependencyPicksLowestMajorAndMinorVersion() { // Arrange var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0"), PackageUtility.CreatePackage("B", "1.0"), PackageUtility.CreatePackage("B", "1.0.1"), PackageUtility.CreatePackage("B", "1.0.9"), PackageUtility.CreatePackage("B", "1.1") }; // B >= 1.0 PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0"); // B >= 1.0.0 PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0"); // B >= 1.0.0.0 PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0"); // B = 1.0 PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]"); // B >= 1.0.0 && <= 1.0.8 PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]"); // Act IPackage package1 = repository.ResolveDependency(dependency1, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package2 = repository.ResolveDependency(dependency2, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package3 = repository.ResolveDependency(dependency3, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package4 = repository.ResolveDependency(dependency4, allowPrereleaseVersions: false, preferListedPackages: false); IPackage package5 = repository.ResolveDependency(dependency5, allowPrereleaseVersions: false, preferListedPackages: false); // Assert Assert.Equal("B", package1.Id); Assert.Equal(new SemanticVersion("1.0"), package1.Version); Assert.Equal("B", package2.Id); Assert.Equal(new SemanticVersion("1.0"), package2.Version); Assert.Equal("B", package3.Id); Assert.Equal(new SemanticVersion("1.0"), package3.Version); Assert.Equal("B", package4.Id); Assert.Equal(new SemanticVersion("1.0"), package4.Version); Assert.Equal("B", package5.Id); Assert.Equal(new SemanticVersion("1.0"), package5.Version); } private static IPackageRepository GetEmptyRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable()); return repository.Object; } private static IPackageRepository GetRemoteRepository(bool includePrerelease = false) { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new List<IPackage> { CreateMockPackage("A", "1.0", "scripts style"), CreateMockPackage("B", "1.0", "testing"), CreateMockPackage("C", "2.0", "xaml"), CreateMockPackage("A", "1.2", "a updated desc") }; if (includePrerelease) { packages.Add(CreateMockPackage("A", "2.0-alpha", "a prerelease package")); packages.Add(CreateMockPackage("B", "1.0-beta", "another prerelease package")); } repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackageRepository GetLocalRepository() { Mock<IPackageRepository> repository = new Mock<IPackageRepository>(); var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") }; repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable()); return repository.Object; } private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null) { Mock<IPackage> package = new Mock<IPackage>(); package.SetupGet(p => p.Id).Returns(name); package.SetupGet(p => p.Version).Returns(SemanticVersion.Parse(version)); package.SetupGet(p => p.Description).Returns(desc); package.SetupGet(p => p.Tags).Returns(tags); package.SetupGet(p => p.Listed).Returns(true); return package.Object; } } }
using System; using System.Linq; using System.Collections.Generic; using Content.Client.Stylesheets; using Content.Shared.Input; using Robust.Client.AutoGenerated; using Robust.Client.Input; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.XAML; using Robust.Shared; using Robust.Shared.Configuration; using Robust.Shared.Input; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Timing; using Robust.Shared.Utility; using Robust.Shared.Log; using static Robust.Client.UserInterface.Controls.BoxContainer; using Robust.Client.UserInterface.CustomControls; namespace Content.Client.EscapeMenu.UI.Tabs { [GenerateTypedNameReferences] public sealed partial class KeyRebindTab : Control { // List of key functions that must be registered as toggle instead. private static readonly HashSet<BoundKeyFunction> ToggleFunctions = new() { EngineKeyFunctions.ShowDebugMonitors, EngineKeyFunctions.HideUI, }; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IConfigurationManager _cfg = default!; private BindButton? _currentlyRebinding; private readonly Dictionary<BoundKeyFunction, KeyControl> _keyControls = new(); private readonly List<Action> _deferCommands = new(); private void HandleToggleUSQWERTYCheckbox(BaseButton.ButtonToggledEventArgs args) { _cfg.SetCVar(CVars.DisplayUSQWERTYHotkeys, args.Pressed); _cfg.SaveToFile(); } public KeyRebindTab() { IoCManager.InjectDependencies(this); RobustXamlLoader.Load(this); ResetAllButton.OnPressed += _ => { _deferCommands.Add(() => { _inputManager.ResetAllBindings(); _inputManager.SaveToUserData(); }); }; var first = true; void AddHeader(string headerContents) { if (!first) { KeybindsContainer.AddChild(new Control {MinSize = (0, 8)}); } first = false; KeybindsContainer.AddChild(new Label { Text = Loc.GetString(headerContents), FontColorOverride = StyleNano.NanoGold, StyleClasses = {StyleNano.StyleClassLabelKeyText} }); } void AddButton(BoundKeyFunction function) { var control = new KeyControl(this, function); KeybindsContainer.AddChild(control); _keyControls.Add(function, control); } void AddCheckBox(string checkBoxName, bool currentState, Action<BaseButton.ButtonToggledEventArgs>? callBackOnClick) { CheckBox newCheckBox = new CheckBox() { Text = Loc.GetString(checkBoxName)}; newCheckBox.Pressed = currentState; newCheckBox.OnToggled += callBackOnClick; KeybindsContainer.AddChild(newCheckBox); } AddHeader("ui-options-header-general"); AddCheckBox("ui-options-hotkey-keymap", _cfg.GetCVar(CVars.DisplayUSQWERTYHotkeys), HandleToggleUSQWERTYCheckbox); AddHeader("ui-options-header-movement"); AddButton(EngineKeyFunctions.MoveUp); AddButton(EngineKeyFunctions.MoveLeft); AddButton(EngineKeyFunctions.MoveDown); AddButton(EngineKeyFunctions.MoveRight); AddButton(EngineKeyFunctions.Walk); AddHeader("ui-options-header-interaction-basic"); AddButton(EngineKeyFunctions.Use); AddButton(ContentKeyFunctions.WideAttack); AddButton(ContentKeyFunctions.ActivateItemInHand); AddButton(ContentKeyFunctions.AltActivateItemInHand); AddButton(ContentKeyFunctions.ActivateItemInWorld); AddButton(ContentKeyFunctions.AltActivateItemInWorld); AddButton(ContentKeyFunctions.Drop); AddButton(ContentKeyFunctions.ExamineEntity); AddButton(ContentKeyFunctions.SwapHands); AddHeader("ui-options-header-interaction-adv"); AddButton(ContentKeyFunctions.SmartEquipBackpack); AddButton(ContentKeyFunctions.SmartEquipBelt); AddButton(ContentKeyFunctions.ThrowItemInHand); AddButton(ContentKeyFunctions.TryPullObject); AddButton(ContentKeyFunctions.MovePulledObject); AddButton(ContentKeyFunctions.ReleasePulledObject); AddButton(ContentKeyFunctions.Point); AddHeader("ui-options-header-ui"); AddButton(ContentKeyFunctions.FocusChat); AddButton(ContentKeyFunctions.FocusLocalChat); AddButton(ContentKeyFunctions.FocusWhisperChat); AddButton(ContentKeyFunctions.FocusRadio); AddButton(ContentKeyFunctions.FocusOOC); AddButton(ContentKeyFunctions.FocusAdminChat); AddButton(ContentKeyFunctions.FocusDeadChat); AddButton(ContentKeyFunctions.FocusConsoleChat); AddButton(ContentKeyFunctions.CycleChatChannelForward); AddButton(ContentKeyFunctions.CycleChatChannelBackward); AddButton(ContentKeyFunctions.OpenCharacterMenu); AddButton(ContentKeyFunctions.OpenContextMenu); AddButton(ContentKeyFunctions.OpenCraftingMenu); AddButton(ContentKeyFunctions.OpenInventoryMenu); AddButton(ContentKeyFunctions.OpenInfo); AddButton(ContentKeyFunctions.OpenActionsMenu); AddButton(ContentKeyFunctions.OpenEntitySpawnWindow); AddButton(ContentKeyFunctions.OpenSandboxWindow); AddButton(ContentKeyFunctions.OpenTileSpawnWindow); AddButton(ContentKeyFunctions.OpenDecalSpawnWindow); AddButton(ContentKeyFunctions.OpenAdminMenu); AddHeader("ui-options-header-misc"); AddButton(ContentKeyFunctions.TakeScreenshot); AddButton(ContentKeyFunctions.TakeScreenshotNoUI); AddHeader("ui-options-header-hotbar"); AddButton(ContentKeyFunctions.Hotbar1); AddButton(ContentKeyFunctions.Hotbar2); AddButton(ContentKeyFunctions.Hotbar3); AddButton(ContentKeyFunctions.Hotbar4); AddButton(ContentKeyFunctions.Hotbar5); AddButton(ContentKeyFunctions.Hotbar6); AddButton(ContentKeyFunctions.Hotbar7); AddButton(ContentKeyFunctions.Hotbar8); AddButton(ContentKeyFunctions.Hotbar9); AddButton(ContentKeyFunctions.Hotbar0); AddButton(ContentKeyFunctions.Loadout1); AddButton(ContentKeyFunctions.Loadout2); AddButton(ContentKeyFunctions.Loadout3); AddButton(ContentKeyFunctions.Loadout4); AddButton(ContentKeyFunctions.Loadout5); AddButton(ContentKeyFunctions.Loadout6); AddButton(ContentKeyFunctions.Loadout7); AddButton(ContentKeyFunctions.Loadout8); AddButton(ContentKeyFunctions.Loadout9); AddHeader("ui-options-header-map-editor"); AddButton(EngineKeyFunctions.EditorPlaceObject); AddButton(EngineKeyFunctions.EditorCancelPlace); AddButton(EngineKeyFunctions.EditorGridPlace); AddButton(EngineKeyFunctions.EditorLinePlace); AddButton(EngineKeyFunctions.EditorRotateObject); AddHeader("ui-options-header-dev"); AddButton(EngineKeyFunctions.ShowDebugConsole); AddButton(EngineKeyFunctions.ShowDebugMonitors); AddButton(EngineKeyFunctions.HideUI); foreach (var control in _keyControls.Values) { UpdateKeyControl(control); } } private void UpdateKeyControl(KeyControl control) { var activeBinds = _inputManager.GetKeyBindings(control.Function); IKeyBinding? bind1 = null; IKeyBinding? bind2 = null; if (activeBinds.Count > 0) { bind1 = activeBinds[0]; if (activeBinds.Count > 1) { bind2 = activeBinds[1]; } } control.BindButton1.Binding = bind1; control.BindButton1.UpdateText(); control.BindButton2.Binding = bind2; control.BindButton2.UpdateText(); control.BindButton2.Button.Disabled = activeBinds.Count == 0; control.ResetButton.Disabled = !_inputManager.IsKeyFunctionModified(control.Function); } protected override void EnteredTree() { base.EnteredTree(); _inputManager.FirstChanceOnKeyEvent += InputManagerOnFirstChanceOnKeyEvent; _inputManager.OnKeyBindingAdded += OnKeyBindAdded; _inputManager.OnKeyBindingRemoved += OnKeyBindRemoved; } protected override void ExitedTree() { base.ExitedTree(); _inputManager.FirstChanceOnKeyEvent -= InputManagerOnFirstChanceOnKeyEvent; _inputManager.OnKeyBindingAdded -= OnKeyBindAdded; _inputManager.OnKeyBindingRemoved -= OnKeyBindRemoved; } private void OnKeyBindRemoved(IKeyBinding obj) { OnKeyBindModified(obj, true); } private void OnKeyBindAdded(IKeyBinding obj) { OnKeyBindModified(obj, false); } private void OnKeyBindModified(IKeyBinding bind, bool removal) { if (!_keyControls.TryGetValue(bind.Function, out var keyControl)) { return; } if (removal && _currentlyRebinding?.KeyControl == keyControl) { // Don't do update if the removal was from initiating a rebind. return; } UpdateKeyControl(keyControl); if (_currentlyRebinding == keyControl.BindButton1 || _currentlyRebinding == keyControl.BindButton2) { _currentlyRebinding = null; } } private void InputManagerOnFirstChanceOnKeyEvent(KeyEventArgs keyEvent, KeyEventType type) { DebugTools.Assert(IsInsideTree); if (_currentlyRebinding == null) { return; } keyEvent.Handle(); if (type != KeyEventType.Up) { return; } var key = keyEvent.Key; // Figure out modifiers based on key event. // TODO: this won't allow for combinations with keys other than the standard modifier keys, // even though the input system totally supports it. var mods = new Keyboard.Key[3]; var i = 0; if (keyEvent.Control && key != Keyboard.Key.Control) { mods[i] = Keyboard.Key.Control; i += 1; } if (keyEvent.Shift && key != Keyboard.Key.Shift) { mods[i] = Keyboard.Key.Shift; i += 1; } if (keyEvent.Alt && key != Keyboard.Key.Alt) { mods[i] = Keyboard.Key.Alt; i += 1; } // The input system can only handle 3 modifier keys so if you hold all 4 of the modifier keys // then system gets the shaft, I guess. if (keyEvent.System && i != 3 && key != Keyboard.Key.LSystem && key != Keyboard.Key.RSystem) { mods[i] = Keyboard.Key.LSystem; } var function = _currentlyRebinding.KeyControl.Function; var bindType = KeyBindingType.State; if (ToggleFunctions.Contains(function)) { bindType = KeyBindingType.Toggle; } var registration = new KeyBindingRegistration { Function = function, BaseKey = key, Mod1 = mods[0], Mod2 = mods[1], Mod3 = mods[2], Priority = 0, Type = bindType, CanFocus = key == Keyboard.Key.MouseLeft || key == Keyboard.Key.MouseRight || key == Keyboard.Key.MouseMiddle, CanRepeat = false }; _inputManager.RegisterBinding(registration); // OnKeyBindModified will cause _currentlyRebinding to be reset and the UI to update. _inputManager.SaveToUserData(); } private void RebindButtonPressed(BindButton button) { if (_currentlyRebinding != null) { return; } _currentlyRebinding = button; _currentlyRebinding.Button.Text = Loc.GetString("ui-options-key-prompt"); if (button.Binding != null) { _deferCommands.Add(() => { // Have to do defer this or else there will be an exception in InputManager. // Because this IS fired from an input event. _inputManager.RemoveBinding(button.Binding); }); } } protected override void FrameUpdate(FrameEventArgs args) { base.FrameUpdate(args); if (_deferCommands.Count == 0) { return; } foreach (var command in _deferCommands) { command(); } _deferCommands.Clear(); } private sealed class KeyControl : Control { public readonly BoundKeyFunction Function; public readonly BindButton BindButton1; public readonly BindButton BindButton2; public readonly Button ResetButton; public KeyControl(KeyRebindTab parent, BoundKeyFunction function) { Function = function; var name = new Label { Text = Loc.GetString( $"ui-options-function-{CaseConversion.PascalToKebab(function.FunctionName)}"), HorizontalExpand = true, HorizontalAlignment = HAlignment.Left }; BindButton1 = new BindButton(parent, this, StyleBase.ButtonOpenRight); BindButton2 = new BindButton(parent, this, StyleBase.ButtonOpenLeft); ResetButton = new Button {Text = Loc.GetString("ui-options-bind-reset"), StyleClasses = {StyleBase.ButtonCaution}}; var hBox = new BoxContainer { Orientation = LayoutOrientation.Horizontal, Children = { new Control {MinSize = (5, 0)}, name, BindButton1, BindButton2, new Control {MinSize = (10, 0)}, ResetButton } }; ResetButton.OnPressed += args => { parent._deferCommands.Add(() => { parent._inputManager.ResetBindingsFor(function); parent._inputManager.SaveToUserData(); }); }; AddChild(hBox); } } private sealed class BindButton : Control { private readonly KeyRebindTab _tab; public readonly KeyControl KeyControl; public readonly Button Button; public IKeyBinding? Binding; public BindButton(KeyRebindTab tab, KeyControl keyControl, string styleClass) { _tab = tab; KeyControl = keyControl; Button = new Button {StyleClasses = {styleClass}}; UpdateText(); AddChild(Button); Button.OnPressed += args => { tab.RebindButtonPressed(this); }; Button.OnKeyBindDown += ButtonOnOnKeyBindDown; MinSize = (200, 0); } protected override void EnteredTree() { base.EnteredTree(); _tab._inputManager.OnInputModeChanged += UpdateText; } protected override void ExitedTree() { base.ExitedTree(); _tab._inputManager.OnInputModeChanged -= UpdateText; } private void ButtonOnOnKeyBindDown(GUIBoundKeyEventArgs args) { if (args.Function == EngineKeyFunctions.UIRightClick) { if (Binding != null) { _tab._deferCommands.Add(() => { _tab._inputManager.RemoveBinding(Binding); _tab._inputManager.SaveToUserData(); }); } args.Handle(); } } public void UpdateText() { Button.Text = Binding?.GetKeyString() ?? Loc.GetString("ui-options-unbound"); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPrinter { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPrinter() : base() { Load += frmPrinter_Load; KeyPress += frmPrinter_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.RadioButton _optType_0; public System.Windows.Forms.RadioButton _optType_3; public System.Windows.Forms.RadioButton _optType_2; public System.Windows.Forms.RadioButton _optType_1; public System.Windows.Forms.GroupBox Frame1; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNext; public System.Windows.Forms.Button cmdNext { get { return withEventsField_cmdNext; } set { if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click -= cmdNext_Click; } withEventsField_cmdNext = value; if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click += cmdNext_Click; } } } private System.Windows.Forms.ListBox withEventsField_lstPrinter; public System.Windows.Forms.ListBox lstPrinter { get { return withEventsField_lstPrinter; } set { if (withEventsField_lstPrinter != null) { withEventsField_lstPrinter.DoubleClick -= lstPrinter_DoubleClick; withEventsField_lstPrinter.KeyPress -= lstPrinter_KeyPress; } withEventsField_lstPrinter = value; if (withEventsField_lstPrinter != null) { withEventsField_lstPrinter.DoubleClick += lstPrinter_DoubleClick; withEventsField_lstPrinter.KeyPress += lstPrinter_KeyPress; } } } public System.Windows.Forms.Label Label3; //Public WithEvents optType As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPrinter)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.Frame1 = new System.Windows.Forms.GroupBox(); this._optType_0 = new System.Windows.Forms.RadioButton(); this._optType_3 = new System.Windows.Forms.RadioButton(); this._optType_2 = new System.Windows.Forms.RadioButton(); this._optType_1 = new System.Windows.Forms.RadioButton(); this.cmdExit = new System.Windows.Forms.Button(); this.cmdNext = new System.Windows.Forms.Button(); this.lstPrinter = new System.Windows.Forms.ListBox(); this.Label3 = new System.Windows.Forms.Label(); //Me.optType = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components) this.Frame1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.optType, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Printer"; this.ClientSize = new System.Drawing.Size(316, 316); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPrinter"; this.Frame1.Text = "NOTE: Please select your printer type before clicking 'Next'"; this.Frame1.ForeColor = System.Drawing.Color.Blue; this.Frame1.Size = new System.Drawing.Size(295, 49); this.Frame1.Location = new System.Drawing.Point(8, 192); this.Frame1.TabIndex = 4; this.Frame1.BackColor = System.Drawing.SystemColors.Control; this.Frame1.Enabled = true; this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame1.Visible = true; this.Frame1.Padding = new System.Windows.Forms.Padding(0); this.Frame1.Name = "Frame1"; this._optType_0.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_0.Text = "no spec"; this._optType_0.Size = new System.Drawing.Size(97, 17); this._optType_0.Location = new System.Drawing.Point(184, 48); this._optType_0.TabIndex = 8; this._optType_0.Visible = false; this._optType_0.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_0.BackColor = System.Drawing.SystemColors.Control; this._optType_0.CausesValidation = true; this._optType_0.Enabled = true; this._optType_0.ForeColor = System.Drawing.SystemColors.ControlText; this._optType_0.Cursor = System.Windows.Forms.Cursors.Default; this._optType_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optType_0.Appearance = System.Windows.Forms.Appearance.Normal; this._optType_0.TabStop = true; this._optType_0.Checked = false; this._optType_0.Name = "_optType_0"; this._optType_3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_3.Text = "Other barcode printer"; this._optType_3.Size = new System.Drawing.Size(121, 17); this._optType_3.Location = new System.Drawing.Point(168, 24); this._optType_3.TabIndex = 7; this._optType_3.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_3.BackColor = System.Drawing.SystemColors.Control; this._optType_3.CausesValidation = true; this._optType_3.Enabled = true; this._optType_3.ForeColor = System.Drawing.SystemColors.ControlText; this._optType_3.Cursor = System.Windows.Forms.Cursors.Default; this._optType_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optType_3.Appearance = System.Windows.Forms.Appearance.Normal; this._optType_3.TabStop = true; this._optType_3.Checked = false; this._optType_3.Visible = true; this._optType_3.Name = "_optType_3"; this._optType_2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_2.Text = "Argox printer"; this._optType_2.Size = new System.Drawing.Size(121, 17); this._optType_2.Location = new System.Drawing.Point(80, 24); this._optType_2.TabIndex = 6; this._optType_2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_2.BackColor = System.Drawing.SystemColors.Control; this._optType_2.CausesValidation = true; this._optType_2.Enabled = true; this._optType_2.ForeColor = System.Drawing.SystemColors.ControlText; this._optType_2.Cursor = System.Windows.Forms.Cursors.Default; this._optType_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optType_2.Appearance = System.Windows.Forms.Appearance.Normal; this._optType_2.TabStop = true; this._optType_2.Checked = false; this._optType_2.Visible = true; this._optType_2.Name = "_optType_2"; this._optType_1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_1.Text = "A4 printer"; this._optType_1.Size = new System.Drawing.Size(97, 17); this._optType_1.Location = new System.Drawing.Point(8, 24); this._optType_1.TabIndex = 5; this._optType_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this._optType_1.BackColor = System.Drawing.SystemColors.Control; this._optType_1.CausesValidation = true; this._optType_1.Enabled = true; this._optType_1.ForeColor = System.Drawing.SystemColors.ControlText; this._optType_1.Cursor = System.Windows.Forms.Cursors.Default; this._optType_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._optType_1.Appearance = System.Windows.Forms.Appearance.Normal; this._optType_1.TabStop = true; this._optType_1.Checked = false; this._optType_1.Visible = true; this._optType_1.Name = "_optType_1"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(9, 256); this.cmdExit.TabIndex = 2; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNext.Text = "&Next"; this.cmdNext.Size = new System.Drawing.Size(97, 52); this.cmdNext.Location = new System.Drawing.Point(207, 256); this.cmdNext.TabIndex = 1; this.cmdNext.TabStop = false; this.cmdNext.BackColor = System.Drawing.SystemColors.Control; this.cmdNext.CausesValidation = true; this.cmdNext.Enabled = true; this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNext.Name = "cmdNext"; this.lstPrinter.Size = new System.Drawing.Size(295, 176); this.lstPrinter.Location = new System.Drawing.Point(9, 9); this.lstPrinter.TabIndex = 0; this.lstPrinter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lstPrinter.BackColor = System.Drawing.SystemColors.Window; this.lstPrinter.CausesValidation = true; this.lstPrinter.Enabled = true; this.lstPrinter.ForeColor = System.Drawing.SystemColors.WindowText; this.lstPrinter.IntegralHeight = true; this.lstPrinter.Cursor = System.Windows.Forms.Cursors.Default; this.lstPrinter.SelectionMode = System.Windows.Forms.SelectionMode.One; this.lstPrinter.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstPrinter.Sorted = false; this.lstPrinter.TabStop = true; this.lstPrinter.Visible = true; this.lstPrinter.MultiColumn = false; this.lstPrinter.Name = "lstPrinter"; this.Label3.Text = "Only printers with the word \"Label\" in the name would be regarded as true Barcode printers. All other printers would be regarded as an \"A4\" printer. If you are not sure, please rename the printer accordingly."; this.Label3.Size = new System.Drawing.Size(369, 49); this.Label3.Location = new System.Drawing.Point(8, 328); this.Label3.TabIndex = 3; this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label3.BackColor = System.Drawing.SystemColors.Control; this.Label3.Enabled = true; this.Label3.ForeColor = System.Drawing.SystemColors.ControlText; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.UseMnemonic = true; this.Label3.Visible = true; this.Label3.AutoSize = false; this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label3.Name = "Label3"; this.Controls.Add(Frame1); this.Controls.Add(cmdExit); this.Controls.Add(cmdNext); this.Controls.Add(lstPrinter); this.Controls.Add(Label3); this.Frame1.Controls.Add(_optType_0); this.Frame1.Controls.Add(_optType_3); this.Frame1.Controls.Add(_optType_2); this.Frame1.Controls.Add(_optType_1); //Me.optType.SetIndex(_optType_0, CType(0, Short)) //Me.optType.SetIndex(_optType_3, CType(3, Short)) //Me.optType.SetIndex(_optType_2, CType(2, Short)) //Me.optType.SetIndex(_optType_1, CType(1, Short)) //CType(Me.optType, System.ComponentModel.ISupportInitialize).EndInit() this.Frame1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.Job { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.AspNetCore.Razor.Language.Syntax; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal class ImplicitExpressionEditHandler : SpanEditHandler { private readonly ISet<string> _keywords; private readonly IReadOnlyCollection<string> _readOnlyKeywords; public ImplicitExpressionEditHandler(Func<string, IEnumerable<Syntax.InternalSyntax.SyntaxToken>> tokenizer, ISet<string> keywords, bool acceptTrailingDot) : base(tokenizer) { _keywords = keywords ?? new HashSet<string>(); // HashSet<T> implements IReadOnlyCollection<T> as of 4.6, but does not for 4.5.1. If the runtime cast // succeeds, avoid creating a new collection. _readOnlyKeywords = (_keywords as IReadOnlyCollection<string>) ?? _keywords.ToArray(); AcceptTrailingDot = acceptTrailingDot; } public bool AcceptTrailingDot { get; } public IReadOnlyCollection<string> Keywords { get { return _readOnlyKeywords; } } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0};ImplicitExpression[{1}];K{2}", base.ToString(), AcceptTrailingDot ? "ATD" : "RTD", Keywords.Count); } public override bool Equals(object obj) { var other = obj as ImplicitExpressionEditHandler; return base.Equals(other) && AcceptTrailingDot == other.AcceptTrailingDot; } public override int GetHashCode() { // Hash code should include only immutable properties and base has none. var hashCodeCombiner = HashCodeCombiner.Start(); hashCodeCombiner.Add(AcceptTrailingDot); return hashCodeCombiner; } protected override PartialParseResultInternal CanAcceptChange(SyntaxNode target, SourceChange change) { if (AcceptedCharacters == AcceptedCharactersInternal.Any) { return PartialParseResultInternal.Rejected; } // In some editors intellisense insertions are handled as "dotless commits". If an intellisense selection is confirmed // via something like '.' a dotless commit will append a '.' and then insert the remaining intellisense selection prior // to the appended '.'. This 'if' statement attempts to accept the intermediate steps of a dotless commit via // intellisense. It will accept two cases: // 1. '@foo.' -> '@foobaz.'. // 2. '@foobaz..' -> '@foobaz.bar.'. Includes Sub-cases '@foobaz()..' -> '@foobaz().bar.' etc. // The key distinction being the double '.' in the second case. if (IsDotlessCommitInsertion(target, change)) { return HandleDotlessCommitInsertion(target); } if (IsAcceptableIdentifierReplacement(target, change)) { return TryAcceptChange(target, change); } if (IsAcceptableReplace(target, change)) { return HandleReplacement(target, change); } var changeRelativePosition = change.Span.AbsoluteIndex - target.Position; // Get the edit context char? lastChar = null; if (changeRelativePosition > 0 && target.FullWidth > 0) { lastChar = target.GetContent()[changeRelativePosition - 1]; } // Don't support 0->1 length edits if (lastChar == null) { return PartialParseResultInternal.Rejected; } // Accepts cases when insertions are made at the end of a span or '.' is inserted within a span. if (IsAcceptableInsertion(target, change)) { // Handle the insertion return HandleInsertion(target, lastChar.Value, change); } if (IsAcceptableInsertionInBalancedParenthesis(target, change)) { return PartialParseResultInternal.Accepted; } if (IsAcceptableDeletion(target, change)) { return HandleDeletion(target, lastChar.Value, change); } if (IsAcceptableDeletionInBalancedParenthesis(target, change)) { return PartialParseResultInternal.Accepted; } return PartialParseResultInternal.Rejected; } // A dotless commit is the process of inserting a '.' with an intellisense selection. private static bool IsDotlessCommitInsertion(SyntaxNode target, SourceChange change) { return IsNewDotlessCommitInsertion(target, change) || IsSecondaryDotlessCommitInsertion(target, change); } // Completing 'DateTime' in intellisense with a '.' could result in: '@DateT' -> '@DateT.' -> '@DateTime.' which is accepted. private static bool IsNewDotlessCommitInsertion(SyntaxNode target, SourceChange change) { return !IsAtEndOfSpan(target, change) && change.Span.AbsoluteIndex > 0 && change.NewText.Length > 0 && target.GetContent().Last() == '.' && ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false) && (change.Span.Length == 0 || ParserHelpers.IsIdentifier(change.GetOriginalText(target), requireIdentifierStart: false)); } // Once a dotless commit has been performed you then have something like '@DateTime.'. This scenario is used to detect the // situation when you try to perform another dotless commit resulting in a textchange with '..'. Completing 'DateTime.Now' // in intellisense with a '.' could result in: '@DateTime.' -> '@DateTime..' -> '@DateTime.Now.' which is accepted. private static bool IsSecondaryDotlessCommitInsertion(SyntaxNode target, SourceChange change) { // Do not need to worry about other punctuation, just looking for double '.' (after change) return change.NewText.Length == 1 && change.NewText == "." && !string.IsNullOrEmpty(target.GetContent()) && target.GetContent().Last() == '.' && change.Span.Length == 0; } private static bool IsAcceptableReplace(SyntaxNode target, SourceChange change) { return IsEndReplace(target, change) || (change.IsReplace && RemainingIsWhitespace(target, change)); } private bool IsAcceptableIdentifierReplacement(SyntaxNode target, SourceChange change) { if (!change.IsReplace) { return false; } var tokens = target.DescendantNodes().Where(n => n.IsToken).Cast<SyntaxToken>().ToArray(); for (var i = 0; i < tokens.Length; i++) { var token = tokens[i]; if (token == null) { break; } var tokenStartIndex = token.Position; var tokenEndIndex = token.EndPosition; // We're looking for the first token that contains the SourceChange. if (tokenEndIndex > change.Span.AbsoluteIndex) { if (tokenEndIndex >= change.Span.AbsoluteIndex + change.Span.Length && token.Kind == SyntaxKind.Identifier) { // The token we're changing happens to be an identifier. Need to check if its transformed state is also one. // We do this transformation logic to capture the case that the new text change happens to not be an identifier; // i.e. "5". Alone, it's numeric, within an identifier it's classified as identifier. var transformedContent = change.GetEditedContent(token.Content, change.Span.AbsoluteIndex - tokenStartIndex); var newTokens = Tokenizer(transformedContent); if (newTokens.Count() != 1) { // The transformed content resulted in more than one token; we can only replace a single identifier with // another single identifier. break; } var newToken = newTokens.First(); if (newToken.Kind == SyntaxKind.Identifier) { return true; } } // Change is touching a non-identifier token or spans multiple tokens. break; } } return false; } private static bool IsAcceptableDeletion(SyntaxNode target, SourceChange change) { return IsEndDeletion(target, change) || (change.IsDelete && RemainingIsWhitespace(target, change)); } // Acceptable insertions can occur at the end of a span or when a '.' is inserted within a span. private static bool IsAcceptableInsertion(SyntaxNode target, SourceChange change) { return change.IsInsert && (IsAcceptableEndInsertion(target, change) || IsAcceptableInnerInsertion(target, change)); } // Internal for testing internal static bool IsAcceptableDeletionInBalancedParenthesis(SyntaxNode target, SourceChange change) { if (!change.IsDelete) { return false; } var changeStart = change.Span.AbsoluteIndex; var changeLength = change.Span.Length; var changeEnd = changeStart + changeLength; var tokens = target.DescendantNodes().Where(n => n.IsToken).Cast<SyntaxToken>().ToArray(); if (!IsInsideParenthesis(changeStart, tokens) || !IsInsideParenthesis(changeEnd, tokens)) { // Either the start or end of the delete does not fall inside of parenthesis, unacceptable inner deletion. return false; } var relativePosition = changeStart - target.Position; var deletionContent = new StringSegment(target.GetContent(), relativePosition, changeLength); if (deletionContent.IndexOfAny(new[] { '(', ')' }) >= 0) { // Change deleted some parenthesis return false; } return true; } // Internal for testing internal static bool IsAcceptableInsertionInBalancedParenthesis(SyntaxNode target, SourceChange change) { if (!change.IsInsert) { return false; } if (change.NewText.IndexOfAny(new[] { '(', ')' }) >= 0) { // Insertions of parenthesis aren't handled by us. If someone else wants to accept it, they can. return false; } var tokens = target.DescendantNodes().Where(n => n.IsToken).Cast<SyntaxToken>().ToArray(); if (IsInsideParenthesis(change.Span.AbsoluteIndex, tokens)) { return true; } return false; } // Internal for testing internal static bool IsInsideParenthesis(int position, IReadOnlyList<SyntaxToken> tokens) { var balanceCount = 0; var foundInsertionPoint = false; for (var i = 0; i < tokens.Count; i++) { var currentToken = tokens[i]; if (ContainsPosition(position, currentToken)) { if (balanceCount == 0) { // Insertion point is outside of parenthesis, i.e. inserting at the pipe: @Foo|Baz() return false; } foundInsertionPoint = true; } if (!TryUpdateBalanceCount(currentToken, ref balanceCount)) { // Couldn't update the count. This usually occurrs when we run into a ')' outside of any parenthesis. return false; } if (foundInsertionPoint && balanceCount == 0) { // Once parenthesis become balanced after the insertion point we return true, no need to go further. // If they get unbalanced down the line the expression was already unbalanced to begin with and this // change happens prior to any ambiguity. return true; } } // Unbalanced parenthesis return false; } // Internal for testing internal static bool ContainsPosition(int position, SyntaxToken currentToken) { var tokenStart = currentToken.Position; if (tokenStart == position) { // Token is exactly at the insertion point. return true; } var tokenEnd = tokenStart + currentToken.Content.Length; if (tokenStart < position && tokenEnd > position) { // Insertion point falls in the middle of the current token. return true; } return false; } // Internal for testing internal static bool TryUpdateBalanceCount(SyntaxToken token, ref int count) { var updatedCount = count; if (token.Kind == SyntaxKind.LeftParenthesis) { updatedCount++; } else if (token.Kind == SyntaxKind.RightParenthesis) { if (updatedCount == 0) { return false; } updatedCount--; } else if (token.Kind == SyntaxKind.StringLiteral) { var content = token.Content; if (content.Length > 0 && content[content.Length - 1] != '"') { // Incomplete string literal may have consumed some of our parenthesis and usually occurr during auto-completion of '"' => '""'. if (!TryUpdateCountFromContent(content, ref updatedCount)) { return false; } } } else if (token.Kind == SyntaxKind.CharacterLiteral) { var content = token.Content; if (content.Length > 0 && content[content.Length - 1] != '\'') { // Incomplete character literal may have consumed some of our parenthesis and usually occurr during auto-completion of "'" => "''". if (!TryUpdateCountFromContent(content, ref updatedCount)) { return false; } } } if (updatedCount < 0) { return false; } count = updatedCount; return true; } // Internal for testing internal static bool TryUpdateCountFromContent(string content, ref int count) { var updatedCount = count; for (var i = 0; i < content.Length; i++) { if (content[i] == '(') { updatedCount++; } else if (content[i] == ')') { if (updatedCount == 0) { // Unbalanced parenthesis, i.e. @Foo) return false; } updatedCount--; } } count = updatedCount; return true; } // Accepts character insertions at the end of spans. AKA: '@foo' -> '@fooo' or '@foo' -> '@foo ' etc. private static bool IsAcceptableEndInsertion(SyntaxNode target, SourceChange change) { Debug.Assert(change.IsInsert); return IsAtEndOfSpan(target, change) || RemainingIsWhitespace(target, change); } // Accepts '.' insertions in the middle of spans. Ex: '@foo.baz.bar' -> '@foo..baz.bar' // This is meant to allow intellisense when editing a span. private static bool IsAcceptableInnerInsertion(SyntaxNode target, SourceChange change) { Debug.Assert(change.IsInsert); // Ensure that we're actually inserting in the middle of a span and not at the end. // This case will fail if the IsAcceptableEndInsertion does not capture an end insertion correctly. Debug.Assert(!IsAtEndOfSpan(target, change)); return change.Span.AbsoluteIndex > 0 && change.NewText == "."; } private static bool RemainingIsWhitespace(SyntaxNode target, SourceChange change) { var offset = (change.Span.AbsoluteIndex - target.Position) + change.Span.Length; return string.IsNullOrWhiteSpace(target.GetContent().Substring(offset)); } private PartialParseResultInternal HandleDotlessCommitInsertion(SyntaxNode target) { var result = PartialParseResultInternal.Accepted; if (!AcceptTrailingDot && target.GetContent().LastOrDefault() == '.') { result |= PartialParseResultInternal.Provisional; } return result; } private PartialParseResultInternal HandleReplacement(SyntaxNode target, SourceChange change) { // Special Case for IntelliSense commits. // When IntelliSense commits, we get two changes (for example user typed "Date", then committed "DateTime" by pressing ".") // 1. Insert "." at the end of this span // 2. Replace the "Date." at the end of the span with "DateTime." // We need partial parsing to accept case #2. var oldText = change.GetOriginalText(target); var result = PartialParseResultInternal.Rejected; if (EndsWithDot(oldText) && EndsWithDot(change.NewText)) { result = PartialParseResultInternal.Accepted; if (!AcceptTrailingDot) { result |= PartialParseResultInternal.Provisional; } } return result; } private PartialParseResultInternal HandleDeletion(SyntaxNode target, char previousChar, SourceChange change) { // What's left after deleting? if (previousChar == '.') { return TryAcceptChange(target, change, PartialParseResultInternal.Accepted | PartialParseResultInternal.Provisional); } else if (ParserHelpers.IsIdentifierPart(previousChar)) { return TryAcceptChange(target, change); } else if (previousChar == '(') { var changeRelativePosition = change.Span.AbsoluteIndex - target.Position; if (target.GetContent()[changeRelativePosition] == ')') { return PartialParseResultInternal.Accepted | PartialParseResultInternal.Provisional; } } return PartialParseResultInternal.Rejected; } private PartialParseResultInternal HandleInsertion(SyntaxNode target, char previousChar, SourceChange change) { // What are we inserting after? if (previousChar == '.') { return HandleInsertionAfterDot(target, change); } else if (ParserHelpers.IsIdentifierPart(previousChar) || previousChar == ')' || previousChar == ']') { return HandleInsertionAfterIdPart(target, change); } else if (previousChar == '(') { return HandleInsertionAfterOpenParenthesis(target, change); } else { return PartialParseResultInternal.Rejected; } } private PartialParseResultInternal HandleInsertionAfterIdPart(SyntaxNode target, SourceChange change) { // If the insertion is a full identifier part, accept it if (ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false)) { return TryAcceptChange(target, change); } else if (IsDoubleParenthesisInsertion(change) || IsOpenParenthesisInsertion(change)) { // Allow inserting parens after an identifier - this is needed to support signature // help intellisense in VS. return TryAcceptChange(target, change); } else if (EndsWithDot(change.NewText)) { // Accept it, possibly provisionally var result = PartialParseResultInternal.Accepted; if (!AcceptTrailingDot) { result |= PartialParseResultInternal.Provisional; } return TryAcceptChange(target, change, result); } else { return PartialParseResultInternal.Rejected; } } private PartialParseResultInternal HandleInsertionAfterOpenParenthesis(SyntaxNode target, SourceChange change) { if (IsCloseParenthesisInsertion(change)) { return TryAcceptChange(target, change); } return PartialParseResultInternal.Rejected; } private PartialParseResultInternal HandleInsertionAfterDot(SyntaxNode target, SourceChange change) { // If the insertion is a full identifier or another dot, accept it if (ParserHelpers.IsIdentifier(change.NewText) || change.NewText == ".") { return TryAcceptChange(target, change); } return PartialParseResultInternal.Rejected; } private PartialParseResultInternal TryAcceptChange(SyntaxNode target, SourceChange change, PartialParseResultInternal acceptResult = PartialParseResultInternal.Accepted) { var content = change.GetEditedContent(target); if (StartsWithKeyword(content)) { return PartialParseResultInternal.Rejected | PartialParseResultInternal.SpanContextChanged; } return acceptResult; } private static bool IsDoubleParenthesisInsertion(SourceChange change) { return change.IsInsert && change.NewText.Length == 2 && change.NewText == "()"; } private static bool IsOpenParenthesisInsertion(SourceChange change) { return change.IsInsert && change.NewText.Length == 1 && change.NewText == "("; } private static bool IsCloseParenthesisInsertion(SourceChange change) { return change.IsInsert && change.NewText.Length == 1 && change.NewText == ")"; } private static bool EndsWithDot(string content) { return (content.Length == 1 && content[0] == '.') || (content[content.Length - 1] == '.' && content.Take(content.Length - 1).All(ParserHelpers.IsIdentifierPart)); } private bool StartsWithKeyword(string newContent) { using (var reader = new StringReader(newContent)) { return _keywords.Contains(reader.ReadWhile(ParserHelpers.IsIdentifierPart)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; namespace Artem.Data.Access { public partial class DataAccess { /// <summary> /// /// </summary> public static class Object { #region Static Methods ////////////////////////////////////////////////////// /// <summary> /// Converts the specified data row. /// </summary> /// <param name="dataRow">The data row.</param> /// <returns></returns> public static T Convert<T>(DataRow dataRow) { Type type = typeof(T); System.Reflection.ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor != null) { T dataObject = (T)constructor.Invoke(null); foreach (string fieldName in ObjectHelper.GetAllFields(type)) { ObjectHelper.SetFieldValue(dataObject, fieldName, dataRow[fieldName]); } return dataObject; } else { throw new Exception(string.Format( @"Type '{0}' does not have a default(parameterless) public constructor! ", type)); } } /// <summary> /// Fetches the array. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> internal static T[] FetchArray<T>(IDataReader reader) { DataAccessView<T> list = FetchCollection<T>(reader); T[] array = new T[list.Count]; list.CopyTo(array, 0); return array; } /// <summary> /// Fetches the collection. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> internal static DataAccessView<T> FetchCollection<T>(IDataReader reader) { DataAccessView<T> list = new DataAccessView<T>(); Type type = typeof(T); T current = default(T); System.Reflection.ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor != null) { // get all db fields List<string> allFields = new List<string>(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) { allFields.Add(reader.GetName(i).ToLower()); } // get all object db fields and intersect string __fieldName; List<string> fields = new List<string>(reader.FieldCount); foreach (string fieldName in ObjectHelper.GetAllFields(type)) { __fieldName = fieldName.ToLower(); if (allFields.Contains(__fieldName)) fields.Add(__fieldName); } // now fetch reader while (reader.Read()) { current = (T)constructor.Invoke(null); foreach (string fieldName in fields) { ObjectHelper.SetFieldValue(current, fieldName, reader[fieldName]); } list.Add(current); } return list;//.ToArray(type); } else { throw new Exception(string.Format( @"Type '{0}' does not have a default(parameterless) public constructor! ", type)); } } /// <summary> /// Fetches the object. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> internal static T FetchObject<T>(IDataReader reader) { Type type = typeof(T); System.Reflection.ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor != null) { // get all db fields List<string> allFields = new List<string>(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) { allFields.Add(reader.GetName(i).ToLower()); } // get all object db fields and intersect string __fieldName; List<string> fields = new List<string>(reader.FieldCount); foreach (string fieldName in ObjectHelper.GetAllFields(type)) { __fieldName = fieldName.ToLower(); if (allFields.Contains(__fieldName)) fields.Add(__fieldName); } // now fetch reader T current = default(T); if (reader.Read()) { current = (T)constructor.Invoke(null); foreach (string fieldName in fields) { ObjectHelper.SetFieldValue(current, fieldName, reader[fieldName]); } } return current; } else { throw new Exception(string.Format( @"Type '{0}' does not have a default(parameteless) public constructor! ", type)); } } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="reader"></param> internal static void FetchObject(object obj, IDataReader reader) { Type type = obj.GetType(); // get all db fields List<string> allFields = new List<string>(reader.FieldCount); for (int i = 0; i < reader.FieldCount; i++) { allFields.Add(reader.GetName(i).ToLower()); } // get all object db fields and intersect string __fieldName; List<string> fields = new List<string>(reader.FieldCount); foreach (string fieldName in ObjectHelper.GetAllFields(type)) { __fieldName = fieldName.ToLower(); if (allFields.Contains(__fieldName)) fields.Add(__fieldName); } // now fetch reader if (reader.Read()) { foreach (string fieldName in fields) { ObjectHelper.SetFieldValue(obj, fieldName, reader[fieldName]); } } } /// <summary> /// Gets the specified command. /// </summary> /// <param name="command">The command.</param> /// <returns></returns> public static T Get<T>(string command) { Type type = typeof(T); DbCommandAttribute attribute = ObjectHelper.FindCommand(type, command); using (DataAccess db = new DataAccess(attribute.CommandText)) { db.CommandType = attribute.CommandType; using (IDataReader reader = db.ExecuteReader()) { return FetchObject<T>(reader); } } } /// <summary> /// Gets this instance. /// </summary> /// <returns></returns> public static T Get<T>() { return Get<T>("get"); } /// <summary> /// Inserts the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <param name="command">The command.</param> /// <returns></returns> public static T Insert<T>(T dataObject, string command) { Type type = dataObject.GetType(); DbCommandAttribute attribute = ObjectHelper.FindCommand(type, command); using (DataAccess db = new DataAccess(attribute.CommandText)) { db.CommandType = attribute.CommandType; foreach (string parameterName in attribute.Parameters) { db.AddParameter(parameterName, ObjectHelper.GetParameterValue(dataObject, parameterName)); } dataObject = db.FetchObject<T>(); } return dataObject; } /// <summary> /// Inserts the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <returns></returns> public static T Insert<T>(T dataObject) { return Insert<T>(dataObject, "insert"); } /// <summary> /// Selects the specified command. /// </summary> /// <param name="command">The command.</param> /// <returns></returns> public static DataAccessView<T> Select<T>(string command) { Type type = typeof(T); DbCommandAttribute attribute = ObjectHelper.FindCommand(type, command); using (DataAccess db = new DataAccess(attribute.CommandText)) { db.CommandType = attribute.CommandType; using (IDataReader reader = db.ExecuteReader()) { return FetchCollection<T>(reader); } } } /// <summary> /// Selects this instance. /// </summary> /// <returns></returns> public static DataAccessView<T> Select<T>() { return Select<T>("select"); } /// <summary> /// Updates the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <param name="command">The command.</param> /// <returns></returns> public static T Update<T>(T dataObject, string command) { Type type = dataObject.GetType(); DbCommandAttribute attribute = ObjectHelper.FindCommand(type, command); using (DataAccess db = new DataAccess(attribute.CommandText)) { db.CommandType = attribute.CommandType; foreach (string parameterName in attribute.Parameters) { db.AddParameter(parameterName, ObjectHelper.GetParameterValue(dataObject, parameterName)); } dataObject = db.FetchObject<T>(); } return dataObject; } /// <summary> /// Updates the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <returns></returns> public static T Update<T>(T dataObject) { return Update<T>(dataObject, "update"); } /// <summary> /// Deletes the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <param name="command">The command.</param> /// <returns></returns> public static int Delete<T>(T dataObject, string command) { Type type = dataObject.GetType(); DbCommandAttribute attribute = ObjectHelper.FindCommand(type, command); using (DataAccess db = new DataAccess(attribute.CommandText)) { db.CommandType = attribute.CommandType; foreach (string parameterName in attribute.Parameters) { db.AddParameter(parameterName, ObjectHelper.GetParameterValue(dataObject, parameterName)); } return db.ExecuteNonQuery(); } } /// <summary> /// Deletes the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <returns></returns> public static int Delete<T>(T dataObject) { return Delete<T>(dataObject, "delete"); } #endregion } } }
// // MRSiteChit.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System.Collections; using AssemblyCSharp; namespace PortableRealm { public static class SiteChitExtensions { public static int ClearingNumber(this MRMapChit.eSiteChitType type) { switch (type) { case MRMapChit.eSiteChitType.Altar: return 1; case MRMapChit.eSiteChitType.Cairns: return 5; case MRMapChit.eSiteChitType.Hoard: return 6; case MRMapChit.eSiteChitType.Lair: return 3; case MRMapChit.eSiteChitType.Pool: return 6; case MRMapChit.eSiteChitType.Shrine: return 4; case MRMapChit.eSiteChitType.Statue: return 2; case MRMapChit.eSiteChitType.Vault: return 3; } return 1; } } public class MRSiteChit : MRMapChit { #region Properties public MRMapChit.eSiteChitType SiteType { get{ return mSiteType; } set{ mSiteType = value; switch (mSiteType) { case MRMapChit.eSiteChitType.Altar: LongName = "ALTAR\n" + ClearingNumber; ShortName = "AL" + ClearingNumber; break; case MRMapChit.eSiteChitType.Cairns: LongName = "CAIRNS\n" + ClearingNumber; ShortName = "CA" + ClearingNumber; break; case MRMapChit.eSiteChitType.Hoard: LongName = "HOARD\n" + ClearingNumber; ShortName = "HO" + ClearingNumber; break; case MRMapChit.eSiteChitType.Lair: LongName = "LAIR\n" + ClearingNumber; ShortName = "LA" + ClearingNumber; break; case MRMapChit.eSiteChitType.Pool: LongName = "POOL\n" + ClearingNumber; ShortName = "PO" + ClearingNumber; break; case MRMapChit.eSiteChitType.Shrine: LongName = "SHRINE\n" + ClearingNumber; ShortName = "SH" + ClearingNumber; break; case MRMapChit.eSiteChitType.Statue: LongName = "STATUE\n" + ClearingNumber; ShortName = "ST" + ClearingNumber; break; case MRMapChit.eSiteChitType.Vault: LongName = "VAULT\n" + ClearingNumber; ShortName = "VA" + ClearingNumber; break; } } } public int ClearingNumber { get{ return SiteType.ClearingNumber(); } } public override int SummonSortIndex { get{ // site chits only summon one box, so the order doesn't matter return 0; } } public static bool VaultOpened { get{ return msVaultOpened; } set{ msVaultOpened = value; } } #endregion #region Methods static MRSiteChit() { MapChitTypes[eMapChitType.Site] = typeof(MRSiteChit); } // dummy function to reference the class static public void Init() {} // Use this for initialization public override void Start () { mChitType = eMapChitType.Site; base.Start(); } // Update is called once per frame public override void Update () { base.Update(); } public void OnLooted(bool success, MRIControllable looter) { if (looter is MRCharacter) { MRCharacter character = (MRCharacter)looter; if (mSiteType == eSiteChitType.Cairns) character.SetFatigueBalance(1); if (mSiteType == eSiteChitType.Pool && success) character.SetFatigueBalance(1); else if (mSiteType == eSiteChitType.Vault && !msVaultOpened) { msVaultOpened = true; if (!character.HasActiveItem(MRItem.GetItem(MRUtility.IdForName("lost keys"))) && !character.HasActiveItem(MRItem.GetItem(MRUtility.IdForName("7-league boots"))) && !character.HasActiveItem(MRItem.GetItem(MRUtility.IdForName("gloves of strength")))) { character.SetFatigueBalance(1, MRActionChit.eType.Any, MRGame.eStrength.Tremendous); } } } } public override bool Load(JSONObject root) { base.Load(root); if (root["site"] is JSONNumber) { SiteType = (MRMapChit.eSiteChitType)((JSONNumber)root["site"]).IntValue; } else if (root["site"] is JSONString) { if (MRMapChit.ChitSiteMap.TryGetValue(((JSONString)root["site"]).Value, out mSiteType)) { SiteType = mSiteType; } else { return false; } } else { return false; } return true; } public override void Save(JSONObject root) { base.Save(root); root["site"] = new JSONNumber((int)SiteType); } #endregion #region Members private MRMapChit.eSiteChitType mSiteType; private static bool msVaultOpened = false; #endregion } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorLogPage.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CultureInfo = System.Globalization.CultureInfo; using ArrayList = System.Collections.ArrayList; #endregion /// <summary> /// Renders an HTML page displaying a page of errors from the error log. /// </summary> internal sealed class ErrorLogPage : ErrorPageBase { private int _pageIndex; private int _pageSize; private int _totalCount; private ArrayList _errorEntryList; private const int _defaultPageSize = 15; private const int _maximumPageSize = 100; protected override void OnLoad(EventArgs e) { // // Get the page index and size parameters within their bounds. // _pageSize = Convert.ToInt32(this.Request.QueryString["size"], CultureInfo.InvariantCulture); _pageSize = Math.Min(_maximumPageSize, Math.Max(0, _pageSize)); if (_pageSize == 0) { _pageSize = _defaultPageSize; } _pageIndex = Convert.ToInt32(this.Request.QueryString["page"], CultureInfo.InvariantCulture); _pageIndex = Math.Max(1, _pageIndex) - 1; // // Read the error records. // _errorEntryList = new ArrayList(_pageSize); _totalCount = this.ErrorLog.GetErrors(_pageIndex, _pageSize, _errorEntryList); // // Set the title of the page. // string hostName = Environment.TryGetMachineName(Context); this.PageTitle = string.Format( hostName.Length > 0 ? "Error log for {0} on {2} (Page #{1})" : "Error log for {0} (Page #{1})", this.ApplicationName, (_pageIndex + 1).ToString("N0"), hostName); base.OnLoad(e); } protected override void RenderHead(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); base.RenderHead(writer); // // Write a <link> tag to relate the RSS feed. // #if NET_1_0 || NET_1_1 writer.AddAttribute("rel", HtmlLinkType.Alternate); #else writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); #endif writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/rss+xml"); writer.AddAttribute(HtmlTextWriterAttribute.Title, "RSS"); writer.AddAttribute(HtmlTextWriterAttribute.Href, this.BasePageName + "/rss"); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); writer.WriteLine(); // // If on the first page, then enable auto-refresh every minute // by issuing the following markup: // // <meta http-equiv="refresh" content="60"> // if (_pageIndex == 0) { writer.AddAttribute("http-equiv", "refresh"); writer.AddAttribute("content", "60"); writer.RenderBeginTag(HtmlTextWriterTag.Meta); writer.RenderEndTag(); writer.WriteLine(); } } protected override void RenderContents(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); // // Write out the page title and speed bar in the body. // RenderTitle(writer); SpeedBar.Render(writer, SpeedBar.RssFeed.Format(BasePageName), SpeedBar.RssDigestFeed.Format(BasePageName), SpeedBar.DownloadLog.Format(BasePageName), SpeedBar.Help, SpeedBar.About.Format(BasePageName)); if (_errorEntryList.Count != 0) { // // Write error number range displayed on this page and the // total available in the log, followed by stock // page sizes. // writer.RenderBeginTag(HtmlTextWriterTag.P); RenderStats(writer); RenderStockPageSizes(writer); writer.RenderEndTag(); // </p> writer.WriteLine(); // // Write out the main table to display the errors. // RenderErrors(writer); // // Write out page navigation links. // RenderPageNavigators(writer); } else { // // No errors found in the log, so display a corresponding // message. // RenderNoErrors(writer); } base.RenderContents(writer); } private void RenderPageNavigators(HtmlTextWriter writer) { Debug.Assert(writer != null); // // If not on the last page then render a link to the next page. // writer.RenderBeginTag(HtmlTextWriterTag.P); int nextPageIndex = _pageIndex + 1; bool moreErrors = nextPageIndex * _pageSize < _totalCount; if (moreErrors) RenderLinkToPage(writer, HtmlLinkType.Next, "Next errors", nextPageIndex); // // If not on the first page then render a link to the firs page. // if (_pageIndex > 0 && _totalCount > 0) { if (moreErrors) writer.Write("; "); RenderLinkToPage(writer, HtmlLinkType.Start, "Back to first page", 0); } writer.RenderEndTag(); // </p> writer.WriteLine(); } private void RenderStockPageSizes(HtmlTextWriter writer) { Debug.Assert(writer != null); // // Write out a set of stock page size choices. Note that // selecting a stock page size re-starts the log // display from the first page to get the right paging. // writer.Write("Start with "); int[] stockSizes = new int[] { 10, 15, 20, 25, 30, 50, 100 }; for (int stockSizeIndex = 0; stockSizeIndex < stockSizes.Length; stockSizeIndex++) { int stockSize = stockSizes[stockSizeIndex]; if (stockSizeIndex > 0) writer.Write(stockSizeIndex + 1 < stockSizes.Length ? ", " : " or "); RenderLinkToPage(writer, HtmlLinkType.Start, stockSize.ToString(), 0, stockSize); } writer.Write(" errors per page."); } private void RenderStats(HtmlTextWriter writer) { Debug.Assert(writer != null); int firstErrorNumber = _pageIndex * _pageSize + 1; int lastErrorNumber = firstErrorNumber + _errorEntryList.Count - 1; int totalPages = (int) Math.Ceiling((double) _totalCount / _pageSize); writer.Write("Errors {0} to {1} of total {2} (page {3} of {4}). ", firstErrorNumber.ToString("N0"), lastErrorNumber.ToString("N0"), _totalCount.ToString("N0"), (_pageIndex + 1).ToString("N0"), totalPages.ToString("N0")); } private void RenderTitle(HtmlTextWriter writer) { Debug.Assert(writer != null); // // If the application name matches the APPL_MD_PATH then its // of the form /LM/W3SVC/.../<name>. In this case, use only the // <name> part to reduce the noise. The full application name is // still made available through a tooltip. // string simpleName = this.ApplicationName; if (string.Compare(simpleName, this.Request.ServerVariables["APPL_MD_PATH"], true, CultureInfo.InvariantCulture) == 0) { int lastSlashIndex = simpleName.LastIndexOf('/'); if (lastSlashIndex > 0) simpleName = simpleName.Substring(lastSlashIndex + 1); } writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle"); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write("Error Log for "); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ApplicationName"); writer.AddAttribute(HtmlTextWriterAttribute.Title, this.Server.HtmlEncode(this.ApplicationName)); writer.RenderBeginTag(HtmlTextWriterTag.Span); Server.HtmlEncode(simpleName, writer); string hostName = Environment.TryGetMachineName(Context); if (hostName.Length > 0) { writer.Write(" on "); Server.HtmlEncode(hostName, writer); } writer.RenderEndTag(); // </span> writer.RenderEndTag(); // </h1> writer.WriteLine(); } private void RenderNoErrors(HtmlTextWriter writer) { Debug.Assert(writer != null); writer.RenderBeginTag(HtmlTextWriterTag.P); writer.Write("No errors found. "); // // It is possible that there are no error at the requested // page in the log (especially if it is not the first page). // However, if there are error in the log // if (_pageIndex > 0 && _totalCount > 0) { RenderLinkToPage(writer, HtmlLinkType.Start, "Go to first page", 0); writer.Write(". "); } writer.RenderEndTag(); writer.WriteLine(); } private void RenderErrors(HtmlTextWriter writer) { Debug.Assert(writer != null); // // Create a table to display error information in each row. // Table table = new Table(); table.ID = "ErrorLog"; table.CellSpacing = 0; // // Create the table row for headings. // TableRow headRow = new TableRow(); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Host", "host-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Code", "code-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Type", "type-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Error", "error-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "User", "user-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Date", "date-col")); headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Time", "time-col")); table.Rows.Add(headRow); // // Generate a table body row for each error. // for (int errorIndex = 0; errorIndex < _errorEntryList.Count; errorIndex++) { ErrorLogEntry errorEntry = (ErrorLogEntry) _errorEntryList[errorIndex]; Error error = errorEntry.Error; TableRow bodyRow = new TableRow(); bodyRow.CssClass = errorIndex % 2 == 0 ? "even-row" : "odd-row"; // // Format host and status code cells. // bodyRow.Cells.Add(FormatCell(new TableCell(), error.HostName, "host-col")); bodyRow.Cells.Add(FormatCell(new TableCell(), error.StatusCode.ToString(), "code-col", Mask.NullString(HttpWorkerRequest.GetStatusDescription(error.StatusCode)))); bodyRow.Cells.Add(FormatCell(new TableCell(), ErrorDisplay.HumaneExceptionErrorType(error), "type-col", error.Type)); // // Format the message cell, which contains the message // text and a details link pointing to the page where // all error details can be viewed. // TableCell messageCell = new TableCell(); messageCell.CssClass = "error-col"; Label messageLabel = new Label(); messageLabel.Text = this.Server.HtmlEncode(error.Message); HyperLink detailsLink = new HyperLink(); detailsLink.NavigateUrl = BasePageName + "/detail?id=" + HttpUtility.UrlEncode(errorEntry.Id); detailsLink.Text = "Details&hellip;"; messageCell.Controls.Add(messageLabel); messageCell.Controls.Add(new LiteralControl(" ")); messageCell.Controls.Add(detailsLink); bodyRow.Cells.Add(messageCell); // // Format the user, date and time cells. // bodyRow.Cells.Add(FormatCell(new TableCell(), error.User, "user-col")); bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortDateString(), "date-col", error.Time.ToLongDateString())); bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortTimeString(), "time-col", error.Time.ToLongTimeString())); // // Finally, add the row to the table. // table.Rows.Add(bodyRow); } table.RenderControl(writer); } private TableCell FormatCell(TableCell cell, string contents, string cssClassName) { return FormatCell(cell, contents, cssClassName, string.Empty); } private TableCell FormatCell(TableCell cell, string contents, string cssClassName, string toolTip) { Debug.Assert(cell != null); Debug.AssertStringNotEmpty(cssClassName); cell.Wrap = false; cell.CssClass = cssClassName; if (contents.Length == 0) { cell.Text = "&nbsp;"; } else { string encodedContents = this.Server.HtmlEncode(contents); if (toolTip.Length == 0) { cell.Text = encodedContents; } else { Label label = new Label(); label.ToolTip = toolTip; label.Text = encodedContents; cell.Controls.Add(label); } } return cell; } private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex) { RenderLinkToPage(writer, type, text, pageIndex, _pageSize); } private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex, int pageSize) { Debug.Assert(writer != null); Debug.Assert(text != null); Debug.Assert(pageIndex >= 0); Debug.Assert(pageSize >= 0); string href = string.Format("{0}?page={1}&size={2}", BasePageName, (pageIndex + 1).ToString(CultureInfo.InvariantCulture), pageSize.ToString(CultureInfo.InvariantCulture)); writer.AddAttribute(HtmlTextWriterAttribute.Href, href); if (type != null && type.Length > 0) #if NET_1_0 || NET_1_1 writer.AddAttribute("rel", type); #else writer.AddAttribute(HtmlTextWriterAttribute.Rel, type); #endif writer.RenderBeginTag(HtmlTextWriterTag.A); this.Server.HtmlEncode(text, writer); writer.RenderEndTag(); } } }
// 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! namespace Google.Apis.BigtableAdmin.v1 { /// <summary>The BigtableAdmin Service.</summary> public class BigtableAdminService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public BigtableAdminService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public BigtableAdminService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "bigtableadmin"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://bigtableadmin.googleapis.com/"; #else "https://bigtableadmin.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://bigtableadmin.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif } /// <summary>A base abstract class for BigtableAdmin requests.</summary> public abstract class BigtableAdminBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new BigtableAdminBaseServiceRequest instance.</summary> protected BigtableAdminBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes BigtableAdmin parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } namespace Google.Apis.BigtableAdmin.v1.Data { /// <summary>A backup of a Cloud Bigtable table.</summary> public class Backup : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. The encryption information for the backup.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encryptionInfo")] public virtual EncryptionInfo EncryptionInfo { get; set; } /// <summary> /// Output only. `end_time` is the time that the backup was finished. The row data in the backup will be no /// newer than this timestamp. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary> /// Required. The expiration time of the backup, with microseconds granularity that must be at least 6 hours and /// at most 30 days from the time the request is received. Once the `expire_time` has passed, Cloud Bigtable /// will delete the backup and free the resources used by the backup. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("expireTime")] public virtual object ExpireTime { get; set; } /// <summary> /// A globally unique identifier for the backup which cannot be changed. Values are of the form /// `projects/{project}/instances/{instance}/clusters/{cluster}/ backups/_a-zA-Z0-9*` The final segment of the /// name must be between 1 and 50 characters in length. The backup is stored in the cluster identified by the /// prefix of the backup name of the form `projects/{project}/instances/{instance}/clusters/{cluster}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Output only. Size of the backup in bytes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sizeBytes")] public virtual System.Nullable<long> SizeBytes { get; set; } /// <summary> /// Required. Immutable. Name of the table from which this backup was created. This needs to be in the same /// instance as the backup. Values are of the form /// `projects/{project}/instances/{instance}/tables/{source_table}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceTable")] public virtual string SourceTable { get; set; } /// <summary> /// Output only. `start_time` is the time that the backup was started (i.e. approximately the time the /// CreateBackup request is received). The row data in this backup will be no older than this timestamp. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>Output only. The current state of the backup.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Information about a backup.</summary> public class BackupInfo : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. Name of the backup.</summary> [Newtonsoft.Json.JsonPropertyAttribute("backup")] public virtual string Backup { get; set; } /// <summary> /// Output only. This time that the backup was finished. Row data in the backup will be no newer than this /// timestamp. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary>Output only. Name of the table the backup was created from.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceTable")] public virtual string SourceTable { get; set; } /// <summary> /// Output only. The time that the backup was started. Row data in the backup will be no older than this /// timestamp. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A resizable group of nodes in a particular cloud location, capable of serving all Tables in the parent Instance. /// </summary> public class Cluster : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Immutable. The type of storage used by this cluster to serve its parent instance's tables, unless explicitly /// overridden. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("defaultStorageType")] public virtual string DefaultStorageType { get; set; } /// <summary>Immutable. The encryption configuration for CMEK-protected clusters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encryptionConfig")] public virtual EncryptionConfig EncryptionConfig { get; set; } /// <summary> /// Immutable. The location where this cluster's nodes and storage reside. For best performance, clients should /// be located as close as possible to this cluster. Currently only zones are supported, so values should be of /// the form `projects/{project}/locations/{zone}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// The unique name of the cluster. Values are of the form /// `projects/{project}/instances/{instance}/clusters/a-z*`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// Required. The number of nodes allocated to this cluster. More nodes enable higher throughput and more /// consistent performance. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("serveNodes")] public virtual System.Nullable<int> ServeNodes { get; set; } /// <summary>Output only. The current state of the cluster.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata type for the operation returned by CreateBackup.</summary> public class CreateBackupMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If set, the time at which this operation finished or was cancelled.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary>The name of the backup being created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The name of the table the backup is created from.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceTable")] public virtual string SourceTable { get; set; } /// <summary>The time at which this operation started.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The metadata for the Operation returned by CreateCluster.</summary> public class CreateClusterMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time at which the operation failed or was completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTime")] public virtual object FinishTime { get; set; } /// <summary>The request that prompted the initiation of this CreateCluster operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalRequest")] public virtual CreateClusterRequest OriginalRequest { get; set; } /// <summary>The time at which the original request was received.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestTime")] public virtual object RequestTime { get; set; } /// <summary> /// Keys: the full `name` of each table that existed in the instance when CreateCluster was first called, i.e. /// `projects//instances//tables/`. Any table added to the instance by a later API call will be created in the /// new cluster by that API call, not this one. Values: information on how much of a table's data has been /// copied to the newly-created cluster so far. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("tables")] public virtual System.Collections.Generic.IDictionary<string, TableProgress> Tables { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for BigtableInstanceAdmin.CreateCluster.</summary> public class CreateClusterRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The cluster to be created. Fields marked `OutputOnly` must be left blank.</summary> [Newtonsoft.Json.JsonPropertyAttribute("cluster")] public virtual Cluster Cluster { get; set; } /// <summary> /// Required. The ID to be used when referring to the new cluster within its instance, e.g., just `mycluster` /// rather than `projects/myproject/instances/myinstance/clusters/mycluster`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("clusterId")] public virtual string ClusterId { get; set; } /// <summary> /// Required. The unique name of the instance in which to create the new cluster. Values are of the form /// `projects/{project}/instances/{instance}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("parent")] public virtual string Parent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The metadata for the Operation returned by CreateInstance.</summary> public class CreateInstanceMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time at which the operation failed or was completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTime")] public virtual object FinishTime { get; set; } /// <summary>The request that prompted the initiation of this CreateInstance operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalRequest")] public virtual CreateInstanceRequest OriginalRequest { get; set; } /// <summary>The time at which the original request was received.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestTime")] public virtual object RequestTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for BigtableInstanceAdmin.CreateInstance.</summary> public class CreateInstanceRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. The clusters to be created within the instance, mapped by desired cluster ID, e.g., just /// `mycluster` rather than `projects/myproject/instances/myinstance/clusters/mycluster`. Fields marked /// `OutputOnly` must be left blank. Currently, at most four clusters can be specified. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("clusters")] public virtual System.Collections.Generic.IDictionary<string, Cluster> Clusters { get; set; } /// <summary>Required. The instance to create. Fields marked `OutputOnly` must be left blank.</summary> [Newtonsoft.Json.JsonPropertyAttribute("instance")] public virtual Instance Instance { get; set; } /// <summary> /// Required. The ID to be used when referring to the new instance within its project, e.g., just `myinstance` /// rather than `projects/myproject/instances/myinstance`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("instanceId")] public virtual string InstanceId { get; set; } /// <summary> /// Required. The unique name of the project in which to create the new instance. Values are of the form /// `projects/{project}`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("parent")] public virtual string Parent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Cloud Key Management Service (Cloud KMS) settings for a CMEK-protected cluster.</summary> public class EncryptionConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Describes the Cloud KMS encryption key that will be used to protect the destination Bigtable cluster. The /// requirements for this key are: 1) The Cloud Bigtable service account associated with the project that /// contains this cluster must be granted the `cloudkms.cryptoKeyEncrypterDecrypter` role on the CMEK key. 2) /// Only regional keys can be used and the region of the CMEK key must match the region of the cluster. 3) All /// clusters within an instance must use the same CMEK key. Values are of the form /// `projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("kmsKeyName")] public virtual string KmsKeyName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Encryption information for a given resource. If this resource is protected with customer managed encryption, the /// in-use Cloud Key Management Service (Cloud KMS) key version is specified along with its status. /// </summary> public class EncryptionInfo : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Output only. The status of encrypt/decrypt calls on underlying data for this resource. Regardless of status, /// the existing data is always encrypted at rest. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("encryptionStatus")] public virtual Status EncryptionStatus { get; set; } /// <summary>Output only. The type of encryption used to protect this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encryptionType")] public virtual string EncryptionType { get; set; } /// <summary> /// Output only. The version of the Cloud KMS key specified in the parent cluster that is in use for the data /// underlying this table. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("kmsKeyVersion")] public virtual string KmsKeyVersion { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Added to the error payload.</summary> public class FailureTrace : Google.Apis.Requests.IDirectResponseSchema { [Newtonsoft.Json.JsonPropertyAttribute("frames")] public virtual System.Collections.Generic.IList<Frame> Frames { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class Frame : Google.Apis.Requests.IDirectResponseSchema { [Newtonsoft.Json.JsonPropertyAttribute("targetName")] public virtual string TargetName { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("workflowGuid")] public virtual string WorkflowGuid { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("zoneId")] public virtual string ZoneId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A collection of Bigtable Tables and the resources that serve them. All tables in an instance are served from all /// Clusters in the instance. /// </summary> public class Instance : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. A server-assigned timestamp representing when this Instance was created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary> /// Required. The descriptive name for this instance as it appears in UIs. Can be changed at any time, but /// should be kept globally unique to avoid confusion. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary> /// Required. Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that /// reflect a customer's organizational needs and deployment strategies. They can be used to filter resources /// and aggregate metrics. * Label keys must be between 1 and 63 characters long and must conform to the regular /// expression: `\p{Ll}\p{Lo}{0,62}`. * Label values must be between 0 and 63 characters long and must conform /// to the regular expression: `[\p{Ll}\p{Lo}\p{N}_-]{0,63}`. * No more than 64 labels can be associated with a /// given resource. * Keys and values must both be under 128 bytes. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary> /// The unique name of the instance. Values are of the form `projects/{project}/instances/a-z+[a-z0-9]`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Output only. The current state of the instance.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>Required. The type of the instance. Defaults to `PRODUCTION`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Encapsulates progress related information for a Cloud Bigtable long running operation.</summary> public class OperationProgress : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If set, the time at which this operation failed or was completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary>Percent completion of the operation. Values are between 0 and 100 inclusive.</summary> [Newtonsoft.Json.JsonPropertyAttribute("progressPercent")] public virtual System.Nullable<int> ProgressPercent { get; set; } /// <summary>Time the request was received.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Metadata type for the long-running operation used to track the progress of optimizations performed on a newly /// restored table. This long-running operation is automatically created by the system after the successful /// completion of a table restore, and cannot be cancelled. /// </summary> public class OptimizeRestoredTableMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Name of the restored table being optimized.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The progress of the post-restore optimizations.</summary> [Newtonsoft.Json.JsonPropertyAttribute("progress")] public virtual OperationProgress Progress { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for BigtableInstanceAdmin.PartialUpdateInstance.</summary> public class PartialUpdateInstanceRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The Instance which will (partially) replace the current value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("instance")] public virtual Instance Instance { get; set; } /// <summary>Required. The subset of Instance fields which should be replaced. Must be explicitly set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("updateMask")] public virtual object UpdateMask { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata type for the long-running operation returned by RestoreTable.</summary> public class RestoreTableMetadata : Google.Apis.Requests.IDirectResponseSchema { [Newtonsoft.Json.JsonPropertyAttribute("backupInfo")] public virtual BackupInfo BackupInfo { get; set; } /// <summary>Name of the table being created and restored to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// If exists, the name of the long-running operation that will be used to track the post-restore optimization /// process to optimize the performance of the restored table. The metadata type of the long-running operation /// is OptimizeRestoreTableMetadata. The response type is Empty. This long-running operation may be /// automatically created by the system if applicable after the RestoreTable long-running operation completes /// successfully. This operation may not be created if the table is already optimized or the restore was not /// successful. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("optimizeTableOperationName")] public virtual string OptimizeTableOperationName { get; set; } /// <summary>The progress of the RestoreTable operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("progress")] public virtual OperationProgress Progress { get; set; } /// <summary>The type of the restore source.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceType")] public virtual string SourceType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The `Status` type defines a logical error model that is suitable for different programming environments, /// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains /// three pieces of data: error code, error message, and error details. You can find out more about this error model /// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). /// </summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary> /// A list of messages that carry the error details. There is a common set of message types for APIs to use. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; } /// <summary> /// A developer-facing error message, which should be in English. Any user-facing error message should be /// localized and sent in the google.rpc.Status.details field, or localized by the client. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Progress info for copying a table's data to the new cluster.</summary> public class TableProgress : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Estimate of the number of bytes copied so far for this table. This will eventually reach /// 'estimated_size_bytes' unless the table copy is CANCELLED. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("estimatedCopiedBytes")] public virtual System.Nullable<long> EstimatedCopiedBytes { get; set; } /// <summary>Estimate of the size of the table to be copied.</summary> [Newtonsoft.Json.JsonPropertyAttribute("estimatedSizeBytes")] public virtual System.Nullable<long> EstimatedSizeBytes { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The metadata for the Operation returned by UpdateAppProfile.</summary> public class UpdateAppProfileMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The metadata for the Operation returned by UpdateCluster.</summary> public class UpdateClusterMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time at which the operation failed or was completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTime")] public virtual object FinishTime { get; set; } /// <summary>The request that prompted the initiation of this UpdateCluster operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalRequest")] public virtual Cluster OriginalRequest { get; set; } /// <summary>The time at which the original request was received.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestTime")] public virtual object RequestTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The metadata for the Operation returned by UpdateInstance.</summary> public class UpdateInstanceMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The time at which the operation failed or was completed successfully.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTime")] public virtual object FinishTime { get; set; } /// <summary>The request that prompted the initiation of this UpdateInstance operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("originalRequest")] public virtual PartialUpdateInstanceRequest OriginalRequest { get; set; } /// <summary>The time at which the original request was received.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestTime")] public virtual object RequestTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer; using NuGet.Dialog.PackageManagerUI; using NuGet.VisualStudio; namespace NuGet.Dialog.Providers { internal class UpdatesProvider : OnlineProvider { private readonly Project _project; private readonly IUpdateAllUIService _updateAllUIService; public UpdatesProvider( Project project, IPackageRepository localRepository, ResourceDictionary resources, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, IVsPackageManagerFactory packageManagerFactory, ProviderServices providerServices, IProgressProvider progressProvider, ISolutionManager solutionManager) : base( project, localRepository, resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, progressProvider, solutionManager) { _project = project; _updateAllUIService = providerServices.UpdateAllUIService; } public override string Name { get { return Resources.Dialog_UpdateProvider; } } public override float SortOrder { get { return 3.0f; } } public override bool RefreshOnNodeSelection { get { return true; } } public override bool SupportsExecuteAllCommand { get { return true; } } public override string OperationName { get { return RepositoryOperationNames.Update; } } protected override PackagesTreeNodeBase CreateTreeNodeForPackageSource(PackageSource source, IPackageRepository sourceRepository) { return new UpdatesTreeNode(this, source.Name, RootNode, LocalRepository, sourceRepository); } public override bool CanExecute(PackageItem item) { IPackage package = item.PackageIdentity; if (package == null) { return false; } // only enable command on a Package in the Update provider if it not updated yet. // the specified package can be updated if the local repository contains a package // with matching id and smaller version number. // Optimization due to bug #2008: if the LocalRepository is backed by a packages.config file, // check the packages information directly from the file, instead of going through // the IPackageRepository interface, which could potentially connect to TFS. var packageLookup = LocalRepository as ILatestPackageLookup; if (packageLookup != null) { SemanticVersion localPackageVersion; return packageLookup.TryFindLatestPackageById(item.Id, out localPackageVersion) && localPackageVersion < package.Version; } return LocalRepository.GetPackages().Any( p => p.Id.Equals(package.Id, StringComparison.OrdinalIgnoreCase) && p.Version < package.Version); } protected override void ExecuteCommand(IProjectManager projectManager, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations) { activePackageManager.UpdatePackages( projectManager, new [] { item.PackageIdentity }, operations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); } protected override bool ExecuteAllCore() { if (SelectedNode == null || SelectedNode.Extensions == null || SelectedNode.Extensions.Count == 0) { return false; } ShowProgressWindow(); IVsPackageManager activePackageManager = GetActivePackageManager(); Debug.Assert(activePackageManager != null); IDisposable action = activePackageManager.SourceRepository.StartOperation(OperationName, mainPackageId: null, mainPackageVersion: null); IProjectManager projectManager = activePackageManager.GetProjectManager(_project); IList<PackageOperation> allOperations; IList<IPackage> allUpdatePackagesByDependencyOrder; bool accepted = ShowLicenseAgreementForAllPackages(activePackageManager, out allOperations, out allUpdatePackagesByDependencyOrder); if (!accepted) { return false; } try { RegisterPackageOperationEvents(activePackageManager, projectManager); activePackageManager.UpdatePackages( projectManager, allUpdatePackagesByDependencyOrder, allOperations, updateDependencies: true, allowPrereleaseVersions: IncludePrerelease, logger: this); return true; } finally { UnregisterPackageOperationEvents(activePackageManager, projectManager); action.Dispose(); } } protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager, out IList<PackageOperation> allOperations, out IList<IPackage> packagesByDependencyOrder) { allOperations = new List<PackageOperation>(); var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease); if (_project.SupportsINuGetProjectSystem()) { packagesByDependencyOrder = allPackages.ToList(); foreach (var package in allPackages) { allOperations.Add(new PackageOperation(package, PackageAction.Install)); } } else { var installWalker = new InstallWalker( LocalRepository, activePackageManager.SourceRepository, _project.GetTargetFrameworkName(), logger: this, ignoreDependencies: false, allowPrereleaseVersions: IncludePrerelease, dependencyVersion: activePackageManager.DependencyVersion); allOperations = installWalker.ResolveOperations(allPackages, out packagesByDependencyOrder); } return ShowLicenseAgreement(activePackageManager, allOperations); } protected override void OnExecuteCompleted(PackageItem item) { base.OnExecuteCompleted(item); // When this was the Update All command execution, // an individual Update command may have updated all remaining packages. // If there are no more updates left, we hide the Update All button. // // However, we only want to do so if there's only one page of result, because // we don't want to download all packages in all pages just to check for this condition. if (SelectedNode != null && SelectedNode.TotalNumberOfPackages > 1 && SelectedNode.TotalPages == 1) { if (SelectedNode.Extensions.OfType<PackageItem>().All(p => !p.IsEnabled)) { _updateAllUIService.Hide(); } } } public override void OnPackageLoadCompleted(PackagesTreeNodeBase selectedNode) { base.OnPackageLoadCompleted(selectedNode); UpdateNumberOfPackages(selectedNode); } private void UpdateNumberOfPackages(PackagesTreeNodeBase selectedNode) { // OnPackageLoadCompleted(selectedNode), which calls this method, is called by QueryExecutionCompleted // QueryExecutionCompleted is called when an asynchronous query execution completes // And, queries are executed from several places including SortSelectionChanged on the node which is always // called by default on the first node, not necessarily, the selected node by VsExtensionsProvider // This means the selectedNode, here, may not actually be THE selectedNode at this point // So, check if it is indeed selected before doing anything. Note that similar check is performed on QueryExecutionCompleted too if (selectedNode != null && selectedNode.IsSelected) { if (!selectedNode.IsSearchResultsNode && selectedNode.TotalNumberOfPackages > 1) { // After performing Update All, if user switches to another page, we don't want to show // the Update All button again. Here we check to make sure there's at least one enabled package. if (selectedNode.Extensions.OfType<PackageItem>().Any(p => p.IsEnabled)) { _updateAllUIService.Show(); } else { _updateAllUIService.Hide(); } } else { _updateAllUIService.Hide(); } } } public override IVsExtension CreateExtension(IPackage package) { var localPackage = LocalRepository.FindPackagesById(package.Id) .OrderByDescending(p => p.Version) .FirstOrDefault(); return new PackageItem(this, package, localPackage != null ? localPackage.Version : null) { CommandName = Resources.Dialog_UpdateButton, TargetFramework = _project.GetTargetFrameworkName() }; } public override string NoItemsMessage { get { return Resources.Dialog_UpdatesProviderNoItem; } } public override string ProgressWindowTitle { get { return Dialog.Resources.Dialog_UpdateProgress; } } protected override string GetProgressMessage(IPackage package) { if (package == null) { return Resources.Dialog_UpdateAllProgress; } return Resources.Dialog_UpdateProgress + package.ToString(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System.Globalization; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; namespace System.Xml { // ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods internal enum ExceptionType { ArgumentException, XmlException, } // Options for serializing and deserializing DateTime public enum XmlDateTimeSerializationMode { Local, Utc, Unspecified, RoundtripKind, } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert"]/*' /> /// <devdoc> /// Encodes and decodes XML names according to /// the "Encoding of arbitrary Unicode Characters in XML Names" specification. /// </devdoc> public static class XmlConvert { // // Static fields with implicit initialization // private static XmlCharType s_xmlCharType = XmlCharType.Instance; /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeName"]/*' /> /// <devdoc> /// <para> /// Converts names, such /// as DataTable or /// DataColumn names, that contain characters that are not permitted in /// XML names to valid names.</para> /// </devdoc> public static string EncodeName(string name) { return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeNmToken"]/*' /> /// <devdoc> /// <para> Verifies the name is valid /// according to production [7] in the XML spec.</para> /// </devdoc> public static string EncodeNmToken(string name) { return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.EncodeLocalName"]/*' /> /// <devdoc> /// <para>Converts names, such as DataTable or DataColumn names, that contain /// characters that are not permitted in XML names to valid names.</para> /// </devdoc> public static string EncodeLocalName(string name) { return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/); } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.DecodeName"]/*' /> /// <devdoc> /// <para> /// Transforms an XML name into an object name (such as DataTable or DataColumn).</para> /// </devdoc> public static string DecodeName(string name) { if (name == null || name.Length == 0) return name; StringBuilder bufBld = null; int length = name.Length; int copyPosition = 0; int underscorePos = name.IndexOf('_'); MatchCollection mc = null; IEnumerator en = null; if (underscorePos >= 0) { if (s_decodeCharPattern == null) { s_decodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_decodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } else { return name; } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index; } for (int position = 0; position < length - s_encodedCharLength + 1; position++) { if (position == matchPos) { if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index; } if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append(name, copyPosition, position - copyPosition); if (name[position + 6] != '_') { //_x1234_ Int32 u = FromHex(name[position + 2]) * 0x10000000 + FromHex(name[position + 3]) * 0x1000000 + FromHex(name[position + 4]) * 0x100000 + FromHex(name[position + 5]) * 0x10000 + FromHex(name[position + 6]) * 0x1000 + FromHex(name[position + 7]) * 0x100 + FromHex(name[position + 8]) * 0x10 + FromHex(name[position + 9]); if (u >= 0x00010000) { if (u <= 0x0010ffff) { //convert to two chars copyPosition = position + s_encodedCharLength + 4; char lowChar, highChar; XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar); bufBld.Append(highChar); bufBld.Append(lowChar); } //else bad ucs-4 char dont convert } else { //convert to single char copyPosition = position + s_encodedCharLength + 4; bufBld.Append((char)u); } position += s_encodedCharLength - 1 + 4; //just skip } else { copyPosition = position + s_encodedCharLength; bufBld.Append((char)( FromHex(name[position + 2]) * 0x1000 + FromHex(name[position + 3]) * 0x100 + FromHex(name[position + 4]) * 0x10 + FromHex(name[position + 5]))); position += s_encodedCharLength - 1; } } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld.Append(name, copyPosition, length - copyPosition); } return bufBld.ToString(); } } private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local) { if (string.IsNullOrEmpty(name)) { return name; } StringBuilder bufBld = null; int length = name.Length; int copyPosition = 0; int position = 0; int underscorePos = name.IndexOf('_'); MatchCollection mc = null; IEnumerator en = null; if (underscorePos >= 0) { if (s_encodeCharPattern == null) { s_encodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_encodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } if (first) { if ((!s_xmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) || matchPos == 0) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append("_x"); if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1])) { int x = name[0]; int y = name[1]; Int32 u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); position++; copyPosition = 2; } else { bufBld.Append(((Int32)name[0]).ToString("X4", CultureInfo.InvariantCulture)); copyPosition = 1; } bufBld.Append('_'); position++; if (matchPos == 0) if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } } } for (; position < length; position++) { if ((local && !s_xmlCharType.IsNCNameCharXml4e(name[position])) || (!local && !s_xmlCharType.IsNameCharXml4e(name[position])) || (matchPos == position)) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } if (matchPos == position) if (en.MoveNext()) { Match m = (Match)en.Current; matchPos = m.Index - 1; } bufBld.Append(name, copyPosition, position - copyPosition); bufBld.Append("_x"); if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) { int x = name[position]; int y = name[position + 1]; Int32 u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); copyPosition = position + 2; position++; } else { bufBld.Append(((Int32)name[position]).ToString("X4", CultureInfo.InvariantCulture)); copyPosition = position + 1; } bufBld.Append('_'); } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld.Append(name, copyPosition, length - copyPosition); } return bufBld.ToString(); } } private static readonly int s_encodedCharLength = 7; // ("_xFFFF_".Length); private static volatile Regex s_encodeCharPattern; private static volatile Regex s_decodeCharPattern; private static int FromHex(char digit) { return (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); } internal static byte[] FromBinHexString(string s) { return FromBinHexString(s, true); } internal static byte[] FromBinHexString(string s, bool allowOddCount) { if (s == null) { throw new ArgumentNullException("s"); } return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } internal static string ToBinHexString(byte[] inArray) { if (inArray == null) { throw new ArgumentNullException("inArray"); } return BinHexEncoder.Encode(inArray, 0, inArray.Length); } // // Verification methods for strings // /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyName"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyName(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentNullException("name", SR.Xml_EmptyName); } // parse name int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { // did not parse to the end -> there is invalid character at endPos throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException); } return name; } internal static string VerifyQName(string name, ExceptionType exceptionType) { if (name == null || name.Length == 0) { throw new ArgumentNullException("name"); } int colonPosition = -1; int endPos = ValidateNames.ParseQName(name, 0, out colonPosition); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNCName"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNCName(string name) { return VerifyNCName(name, ExceptionType.XmlException); } internal static string VerifyNCName(string name, ExceptionType exceptionType) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentNullException("name", SR.Xml_EmptyLocalName); } int end = ValidateNames.ParseNCName(name, 0); if (end != name.Length) { // If the string is not a valid NCName, then throw or return false throw CreateInvalidNameCharException(name, end, exceptionType); } return name; } /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNMTOKEN"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNMTOKEN(string name) { return VerifyNMTOKEN(name, ExceptionType.XmlException); } internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } // Verification method for XML characters as defined in XML spec production [2] Char. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyXmlChars(string content) { if (content == null) { throw new ArgumentNullException("content"); } VerifyCharData(content, ExceptionType.XmlException); return content; } // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyPublicId(string publicId) { if (publicId == null) { throw new ArgumentNullException("publicId"); } // returns the position of invalid character or -1 int pos = s_xmlCharType.IsPublicId(publicId); if (pos != -1) { throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException); } return publicId; } // Verification method for XML whitespace characters as defined in XML spec production [3] S. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyWhitespace(string content) { if (content == null) { throw new ArgumentNullException("content"); } // returns the position of invalid character or -1 int pos = s_xmlCharType.IsOnlyWhitespaceWithPos(content); if (pos != -1) { throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1); } return content; } #if XML10_FIFTH_EDITION public static bool IsStartNCNameSurrogatePair(char lowChar, char highChar) { return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar); } #endif #if XML10_FIFTH_EDITION public static bool IsNCNameSurrogatePair(char lowChar, char highChar) { return xmlCharType.IsNCNameSurrogateChar(lowChar, highChar); } #endif // Value convertors: // // String representation of Base types in XML (xsd) sometimes differ from // one common language runtime offer and for all types it has to be locale independent. // o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo // x -- means we doing something special to make a convertion. // // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid // ------------------------------------------------------------------------------ // Boolean x // Char o // SByte o // Byte o // Int16 o // UInt16 o // Int32 o // UInt32 o // Int64 o // UInt64 o // Single x // Double x // Decimal o // DateTime x // String x o o o o o o o o o o x x o o x // Guid x // ----------------------------------------------------------------------------- ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Boolean value) { return value ? "true" : "false"; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Char value) { return value.ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Decimal value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(SByte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int16 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int32 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Int64 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Byte value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt16 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString8"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt32 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static string ToString(UInt64 value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString9"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Single value) { if (Single.IsNegativeInfinity(value)) return "-INF"; if (Single.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero((double)value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString10"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Double value) { if (Double.IsNegativeInfinity(value)) return "-INF"; if (Double.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero(value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString11"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(TimeSpan value) { return new XsdDuration(value).ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString14"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) { switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: value = SwitchToLocalTime(value); break; case XmlDateTimeSerializationMode.Utc: value = SwitchToUtcTime(value); break; case XmlDateTimeSerializationMode.Unspecified: value = new DateTime(value.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption")); } XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value) { XsdDateTime xsdDateTime = new XsdDateTime(value); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value, string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToString15"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(Guid value) { return value.ToString(); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToBoolean"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Boolean ToBoolean(string s) { s = TrimString(s); if (s == "1" || s == "true") return true; if (s == "0" || s == "false") return false; throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToChar"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Char ToChar(string s) { if (s == null) { throw new ArgumentNullException("s"); } if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); } return s[0]; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDecimal"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Decimal ToDecimal(string s) { return Decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSByte"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static SByte ToSByte(string s) { return SByte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int16 ToInt16(string s) { return Int16.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt32"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int32 ToInt32(string s) { return Int32.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToInt64"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Int64 ToInt64(string s) { return Int64.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToByte"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Byte ToByte(string s) { return Byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt16 ToUInt16(string s) { return UInt16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt32"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt32 ToUInt32(string s) { return UInt32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToUInt64"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public static UInt64 ToUInt64(string s) { return UInt64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToSingle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Single ToSingle(string s) { s = TrimString(s); if (s == "-INF") return Single.NegativeInfinity; if (s == "INF") return Single.PositiveInfinity; float f = Single.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo); if (f == 0 && s[0] == '-') { return -0f; } return f; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDouble"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Double ToDouble(string s) { s = TrimString(s); if (s == "-INF") return Double.NegativeInfinity; if (s == "INF") return Double.PositiveInfinity; double dVal = Double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); if (dVal == 0 && s[0] == '-') { return -0d; } return dVal; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static TimeSpan ToTimeSpan(string s) { XsdDuration duration; TimeSpan timeSpan; try { duration = new XsdDuration(s); } catch (Exception) { // Remap exception for v1 compatibility throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "TimeSpan")); } timeSpan = duration.ToTimeSpan(); return timeSpan; } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToDateTime3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTime dt = (DateTime)xsdDateTime; switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: dt = SwitchToLocalTime(dt); break; case XmlDateTimeSerializationMode.Utc: dt = SwitchToUtcTime(dt); break; case XmlDateTimeSerializationMode.Unspecified: dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, "dateTimeOption")); } return dt; } public static DateTimeOffset ToDateTimeOffset(string s) { if (s == null) { throw new ArgumentNullException("s"); } XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime; return dateTimeOffset; } public static DateTimeOffset ToDateTimeOffset(string s, string format) { if (s == null) { throw new ArgumentNullException("s"); } return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTimeOffset ToDateTimeOffset(string s, string[] formats) { if (s == null) { throw new ArgumentNullException("s"); } return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } ///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToGuid"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static Guid ToGuid(string s) { return new Guid(s); } private static DateTime SwitchToLocalTime(DateTime value) { switch (value.Kind) { case DateTimeKind.Local: return value; case DateTimeKind.Unspecified: return new DateTime(value.Ticks, DateTimeKind.Local); case DateTimeKind.Utc: return value.ToLocalTime(); } return value; } private static DateTime SwitchToUtcTime(DateTime value) { switch (value.Kind) { case DateTimeKind.Utc: return value; case DateTimeKind.Unspecified: return new DateTime(value.Ticks, DateTimeKind.Utc); case DateTimeKind.Local: return value.ToUniversalTime(); } return value; } internal static Uri ToUri(string s) { if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } Uri uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return uri; } // Compares the given character interval and string and returns true if the characters are identical internal static bool StrEqual(char[] chars, int strPos1, int strLen1, string str2) { if (strLen1 != str2.Length) { return false; } int i = 0; while (i < strLen1 && chars[strPos1 + i] == str2[i]) { i++; } return i == strLen1; } // XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec> internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // Trim a string using XML whitespace characters internal static string TrimString(string value) { return value.Trim(WhitespaceChars); } // Trim beginning of a string using XML whitespace characters internal static string TrimStringStart(string value) { return value.TrimStart(WhitespaceChars); } // Trim end of a string using XML whitespace characters internal static string TrimStringEnd(string value) { return value.TrimEnd(WhitespaceChars); } // Split a string into a whitespace-separated list of tokens internal static string[] SplitString(string value) { return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries); } internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) { return value.Split(WhitespaceChars, splitStringOptions); } internal static bool IsNegativeZero(double value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead if (value == 0 && DoubleToInt64Bits(value) == DoubleToInt64Bits(-0e0)) { return true; } return false; } #if !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecuritySafeCritical] #endif private static unsafe long DoubleToInt64Bits(double value) { // NOTE: BitConverter.DoubleToInt64Bits is missing in Silverlight return *((long*)&value); } internal static void VerifyCharData(string data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } internal static void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (data == null || data.Length == 0) { return; } int i = 0; int len = data.Length; for (; ;) { while (i < len && s_xmlCharType.IsCharData(data[i])) { i++; } if (i == len) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == len) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1); } } throw CreateInvalidCharException(data, i, invCharExceptionType); } } internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) { if (data == null || len == 0) { return; } int i = offset; int endPos = offset + len; for (; ;) { while (i < endPos && s_xmlCharType.IsCharData(data[i])) { i++; } if (i == endPos) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == endPos) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1); } } throw CreateInvalidCharException(data, len, i, exceptionType); } } internal static Exception CreateException(string res, ExceptionType exceptionType) { return CreateException(res, exceptionType, 0, 0); } internal static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(res); case ExceptionType.XmlException: default: return new XmlException(res, string.Empty, lineNo, linePos); } } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType) { return CreateException(res, arg, exceptionType, 0, 0); } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(SR.Format(res, arg)); case ExceptionType.XmlException: default: return new XmlException(res, arg, lineNo, linePos); } } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType) { return CreateException(res, args, exceptionType, 0, 0); } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(SR.Format(res, args)); case ExceptionType.XmlException: default: return new XmlException(res, args, lineNo, linePos); } } internal static Exception CreateInvalidSurrogatePairException(char low, char hi) { return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) { return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos) { string[] args = new string[] { ((uint)hi).ToString( "X", CultureInfo.InvariantCulture ), ((uint)low).ToString( "X", CultureInfo.InvariantCulture ) }; return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos); } internal static Exception CreateInvalidHighSurrogateCharException(char hi) { return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType) { return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos) { return CreateInvalidCharException(data, length, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(string data, int invCharPos) { return CreateInvalidCharException(data, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(char invChar, char nextChar) { return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char invChar, char nextChar, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType); } internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) { return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1); } internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName) { return (name == null) ? new ArgumentNullException(argumentName) : new ArgumentException(SR.Xml_EmptyName, argumentName); } } }
//--------------------------------------------------------------------- // <copyright file="ColumnCollection.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; /// <summary> /// Collection of column information related to a <see cref="TableInfo"/> or /// <see cref="View"/>. /// </summary> internal sealed class ColumnCollection : ICollection<ColumnInfo> { private IList<ColumnInfo> columns; private string formatString; /// <summary> /// Creates a new ColumnCollection based on a specified list of columns. /// </summary> /// <param name="columns">columns to be added to the new collection</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ColumnCollection(ICollection<ColumnInfo> columns) { if (columns == null) { throw new ArgumentNullException("columns"); } this.columns = new List<ColumnInfo>(columns); } /// <summary> /// Creates a new ColumnCollection that is associated with a database table. /// </summary> /// <param name="view">view that contains the columns</param> internal ColumnCollection(View view) { if (view == null) { throw new ArgumentNullException("view"); } this.columns = ColumnCollection.GetViewColumns(view); } /// <summary> /// Gets the number of columns in the collection. /// </summary> /// <value>number of columns in the collection</value> public int Count { get { return this.columns.Count; } } /// <summary> /// Gets a boolean value indicating whether the collection is read-only. /// A ColumnCollection is read-only if it is associated with a <see cref="View"/> /// or a read-only <see cref="Database"/>. /// </summary> /// <value>read-only status of the collection</value> public bool IsReadOnly { get { return true; } } /// <summary> /// Gets information about a specific column in the collection. /// </summary> /// <param name="columnIndex">1-based index into the column collection</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="columnIndex"/> is less /// than 1 or greater than the number of columns in the collection</exception> public ColumnInfo this[int columnIndex] { get { if (columnIndex >= 0 && columnIndex < this.columns.Count) { return this.columns[columnIndex]; } else { throw new ArgumentOutOfRangeException("columnIndex"); } } } /// <summary> /// Gets information about a specific column in the collection. /// </summary> /// <param name="columnName">case-sensitive name of a column collection</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="columnName"/> does /// not exist in the collection</exception> public ColumnInfo this[string columnName] { get { if (string.IsNullOrWhiteSpace(columnName)) { throw new ArgumentNullException("columnName"); } foreach (ColumnInfo colInfo in this.columns) { if (colInfo.Name == columnName) { return colInfo; } } throw new ArgumentOutOfRangeException("columnName"); } } /// <summary> /// Not supported because the collection is read-only. /// </summary> /// <param name="item">information about the column being added</param> /// <exception cref="InvalidOperationException">the collection is read-only</exception> public void Add(ColumnInfo item) { throw new InvalidOperationException(); } /// <summary> /// Not supported because the collection is read-only. /// </summary> /// <exception cref="InvalidOperationException">the collection is read-only</exception> public void Clear() { throw new InvalidOperationException(); } /// <summary> /// Checks if a column with a given name exists in the collection. /// </summary> /// <param name="columnName">case-sensitive name of the column to look for</param> /// <returns>true if the column exists in the collection, false otherwise</returns> public bool Contains(string columnName) { return this.IndexOf(columnName) >= 0; } /// <summary> /// Checks if a column with a given name exists in the collection. /// </summary> /// <param name="column">column to look for, with case-sensitive name</param> /// <returns>true if the column exists in the collection, false otherwise</returns> bool ICollection<ColumnInfo>.Contains(ColumnInfo column) { return this.Contains(column.Name); } /// <summary> /// Gets the index of a column within the collection. /// </summary> /// <param name="columnName">case-sensitive name of the column to look for</param> /// <returns>0-based index of the column, or -1 if not found</returns> public int IndexOf(string columnName) { if (string.IsNullOrWhiteSpace(columnName)) { throw new ArgumentNullException("columnName"); } for (int index = 0; index < this.columns.Count; index++) { if (this.columns[index].Name == columnName) { return index; } } return -1; } /// <summary> /// Copies the columns from this collection into an array. /// </summary> /// <param name="array">destination array to be filed</param> /// <param name="arrayIndex">offset into the destination array where copying begins</param> public void CopyTo(ColumnInfo[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } this.columns.CopyTo(array, arrayIndex); } /// <summary> /// Not supported because the collection is read-only. /// </summary> /// <param name="column">column to remove</param> /// <returns>true if the column was removed, false if it was not found</returns> /// <exception cref="InvalidOperationException">the collection is read-only</exception> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "column")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] bool ICollection<ColumnInfo>.Remove(ColumnInfo column) { throw new InvalidOperationException(); } /// <summary> /// Gets an enumerator over the columns in the collection. /// </summary> /// <returns>An enumerator of ColumnInfo objects.</returns> public IEnumerator<ColumnInfo> GetEnumerator() { return this.columns.GetEnumerator(); } /// <summary> /// Gets a string suitable for printing all the values of a record containing these columns. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string FormatString { get { if (this.formatString == null) { this.formatString = CreateFormatString(this.columns); } return this.formatString; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static string CreateFormatString(IList<ColumnInfo> columns) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < columns.Count; i++) { if (columns[i].Type == typeof(Stream)) { sb.AppendFormat("{0} = [Binary Data]", columns[i].Name); } else { sb.AppendFormat("{0} = [{1}]", columns[i].Name, i + 1); } if (i < columns.Count - 1) { sb.Append(", "); } } return sb.ToString(); } /// <summary> /// Gets an enumerator over the columns in the collection. /// </summary> /// <returns>An enumerator of ColumnInfo objects.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Creates ColumnInfo objects for the associated view. /// </summary> /// <returns>dynamically-generated list of columns</returns> private static IList<ColumnInfo> GetViewColumns(View view) { IList<string> columnNames = ColumnCollection.GetViewColumns(view, false); IList<string> columnTypes = ColumnCollection.GetViewColumns(view, true); int count = columnNames.Count; if (columnTypes[count - 1] == "O0") { // Weird.. the "_Tables" table returns a second column with type "O0" -- ignore it. count--; } IList<ColumnInfo> columnsList = new List<ColumnInfo>(count); for (int i = 0; i < count; i++) { columnsList.Add(new ColumnInfo(columnNames[i], columnTypes[i])); } return columnsList; } /// <summary> /// Gets a list of column names or column-definition-strings for the /// associated view. /// </summary> /// <param name="view">the view to that defines the columns</param> /// <param name="types">true to return types (column definition strings), /// false to return names</param> /// <returns>list of column names or types</returns> private static IList<string> GetViewColumns(View view, bool types) { int recordHandle; int typesFlag = types ? 1 : 0; uint ret = RemotableNativeMethods.MsiViewGetColumnInfo( (int) view.Handle, (uint) typesFlag, out recordHandle); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } using (Record rec = new Record((IntPtr) recordHandle, true, null)) { int count = rec.FieldCount; IList<string> columnsList = new List<string>(count); // Since we must be getting all strings of limited length, // this code is faster than calling rec.GetString(field). for (int field = 1; field <= count; field++) { uint bufSize = 256; StringBuilder buf = new StringBuilder((int) bufSize); ret = RemotableNativeMethods.MsiRecordGetString((int) rec.Handle, (uint) field, buf, ref bufSize); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } columnsList.Add(buf.ToString()); } return columnsList; } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// A set of permissions associated with a subject /// First published in XenServer 5.6. /// </summary> public partial class Role : XenObject<Role> { public Role() { } public Role(string uuid, string name_label, string name_description, List<XenRef<Role>> subroles) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.subroles = subroles; } /// <summary> /// Creates a new Role from a Proxy_Role. /// </summary> /// <param name="proxy"></param> public Role(Proxy_Role proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Role update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; subroles = update.subroles; } internal void UpdateFromProxy(Proxy_Role proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; subroles = proxy.subroles == null ? null : XenRef<Role>.Create(proxy.subroles); } public Proxy_Role ToProxy() { Proxy_Role result_ = new Proxy_Role(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.subroles = (subroles != null) ? Helper.RefListToStringArray(subroles) : new string[] {}; return result_; } /// <summary> /// Creates a new Role from a Hashtable. /// </summary> /// <param name="table"></param> public Role(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); subroles = Marshalling.ParseSetRef<Role>(table, "subroles"); } public bool DeepEquals(Role other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._subroles, other._subroles); } public override string SaveChanges(Session session, string opaqueRef, Role server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given role. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static Role get_record(Session session, string _role) { return new Role((Proxy_Role)session.proxy.role_get_record(session.uuid, _role ?? "").parse()); } /// <summary> /// Get a reference to the role instance with the specified UUID. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Role> get_by_uuid(Session session, string _uuid) { return XenRef<Role>.Create(session.proxy.role_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get all the role instances with the given label. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Role>> get_by_name_label(Session session, string _label) { return XenRef<Role>.Create(session.proxy.role_get_by_name_label(session.uuid, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given role. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static string get_uuid(Session session, string _role) { return (string)session.proxy.role_get_uuid(session.uuid, _role ?? "").parse(); } /// <summary> /// Get the name/label field of the given role. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static string get_name_label(Session session, string _role) { return (string)session.proxy.role_get_name_label(session.uuid, _role ?? "").parse(); } /// <summary> /// Get the name/description field of the given role. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static string get_name_description(Session session, string _role) { return (string)session.proxy.role_get_name_description(session.uuid, _role ?? "").parse(); } /// <summary> /// Get the subroles field of the given role. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static List<XenRef<Role>> get_subroles(Session session, string _role) { return XenRef<Role>.Create(session.proxy.role_get_subroles(session.uuid, _role ?? "").parse()); } /// <summary> /// This call returns a list of permissions given a role /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static List<XenRef<Role>> get_permissions(Session session, string _role) { return XenRef<Role>.Create(session.proxy.role_get_permissions(session.uuid, _role ?? "").parse()); } /// <summary> /// This call returns a list of permission names given a role /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given role</param> public static string[] get_permissions_name_label(Session session, string _role) { return (string [])session.proxy.role_get_permissions_name_label(session.uuid, _role ?? "").parse(); } /// <summary> /// This call returns a list of roles given a permission /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_role">The opaque_ref of the given permission</param> public static List<XenRef<Role>> get_by_permission(Session session, string _role) { return XenRef<Role>.Create(session.proxy.role_get_by_permission(session.uuid, _role ?? "").parse()); } /// <summary> /// This call returns a list of roles given a permission name /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_label">The short friendly name of the role</param> public static List<XenRef<Role>> get_by_permission_name_label(Session session, string _label) { return XenRef<Role>.Create(session.proxy.role_get_by_permission_name_label(session.uuid, _label ?? "").parse()); } /// <summary> /// Return a list of all the roles known to the system. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Role>> get_all(Session session) { return XenRef<Role>.Create(session.proxy.role_get_all(session.uuid).parse()); } /// <summary> /// Get all the role Records at once, in a single XML RPC call /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Role>, Role> get_all_records(Session session) { return XenRef<Role>.Create<Proxy_Role>(session.proxy.role_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a short user-friendly name for the role /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// what this role is for /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// a list of pointers to other roles or permissions /// </summary> public virtual List<XenRef<Role>> subroles { get { return _subroles; } set { if (!Helper.AreEqual(value, _subroles)) { _subroles = value; Changed = true; NotifyPropertyChanged("subroles"); } } } private List<XenRef<Role>> _subroles; } }
//----------------------------------------------------------------------- // <copyright file="TangoDeltaPoseController.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using UnityEngine; using Tango; /// <summary> /// This is a more advanced movement controller based on the poses returned /// from the Tango service. /// /// This updates the position with deltas, so movement can be done using a /// CharacterController, or physics, or anything else that wants deltas. /// </summary> public class TangoDeltaPoseController : MonoBehaviour, ITangoLifecycle, ITangoPose { /// <summary> /// The change in time since the last pose update. /// </summary> [HideInInspector] public float m_poseDeltaTime; /// <summary> /// Total number of poses ever received by this controller. /// </summary> [HideInInspector] public int m_poseCount; /// <summary> /// The most recent pose status received. /// </summary> [HideInInspector] public TangoEnums.TangoPoseStatusType m_poseStatus; /// <summary> /// If set, the Area Description used for relocalization. /// </summary> [HideInInspector] public AreaDescription m_areaDescription; /// <summary> /// The most recent pose timestamp received. /// </summary> [HideInInspector] public float m_poseTimestamp; /// <summary> /// The most recent Tango rotation. /// /// This is different from the pose's rotation because it takes into /// account teleporting and the clutch. /// </summary> [HideInInspector] public Vector3 m_tangoPosition; /// <summary> /// The most recent Tango position. /// /// This is different from the pose's position because it takes into /// account teleporting and the clutch. /// </summary> [HideInInspector] public Quaternion m_tangoRotation; /// <summary> /// If set, use the character controller to move the object. /// </summary> public bool m_characterMotion; /// <summary> /// If set, display a Clutch UI via OnGUI. /// </summary> public bool m_enableClutchUI; /// <summary> /// If set, this contoller will use the Device with respect Area Description frame pose. /// </summary> public bool m_useAreaDescriptionPose; /// <summary> /// The TangoApplication being listened to. /// </summary> private TangoApplication m_tangoApplication; /// <summary> /// The previous Tango's position. /// /// This is different from the pose's position because it takes into /// account teleporting and the clutch. /// </summary> private Vector3 m_prevTangoPosition; /// <summary> /// The previous Tango's rotation. /// /// This is different from the pose's rotation because it takes into /// account teleporting and the clutch. /// </summary> private Quaternion m_prevTangoRotation; /// <summary> /// If the clutch is active. /// /// When the clutch is active, the Tango device can be moved and rotated /// without the controller actually moving. /// </summary> /// <value><c>true</c> if clutch active; otherwise, <c>false</c>.</value> public bool ClutchActive { get { return m_clutchActive; } set { if (m_clutchActive && !value) { SetPose(transform.position, transform.rotation); } m_clutchActive = value; } } /// <summary> /// Internal data about the clutch. /// </summary> private bool m_clutchActive; /// <summary> /// Internal CharacterController used for motion. /// </summary> private CharacterController m_characterController; // We use couple of matrix transformation to convert the pose from Tango coordinate // frame to Unity coordinate frame. // The full equation is: // Matrix4x4 uwTuc = uwTss * ssTd * dTuc; // // uwTuc: Unity camera with respect to Unity world, this is the desired matrix. // uwTss: Constant matrix converting start of service frame to Unity world frame. // ssTd: Device frame with repect to start of service frame, this matrix denotes the // pose transform we get from pose callback. // dTuc: Constant matrix converting Unity world frame frame to device frame. // // Please see the coordinate system section online for more information: // https://developers.google.com/project-tango/overview/coordinate-systems /// <summary> /// Matrix that transforms from Start of Service to the Unity World. /// </summary> private Matrix4x4 m_uwTss; /// <summary> /// Matrix that transforms from the Unity Camera to Device. /// </summary> private Matrix4x4 m_dTuc; /// <summary> /// Matrix that transforms from the Unity Camera to the Unity World. /// /// Needed to calculate offsets. /// </summary> private Matrix4x4 m_uwTuc; /// <summary> /// Matrix that transforms the Unity World taking into account offsets from calls /// to <c>SetPose</c>. /// </summary> private Matrix4x4 m_uwOffsetTuw; /// <summary> /// Gets the unity world offset which can be then multiplied to any transform to apply this offset. /// </summary> /// <value>The unity world offset.</value> public Matrix4x4 UnityWorldOffset { get { return m_uwOffsetTuw; } } /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> public void Awake() { // Constant matrix converting start of service frame to Unity world frame. m_uwTss = new Matrix4x4(); m_uwTss.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(1, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_uwTss.SetColumn(2, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Constant matrix converting Unity world frame frame to device frame. m_dTuc = new Matrix4x4(); m_dTuc.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_dTuc.SetColumn(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_dTuc.SetColumn(2, new Vector4(0.0f, 0.0f, -1.0f, 0.0f)); m_dTuc.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); m_poseDeltaTime = -1.0f; m_poseTimestamp = -1.0f; m_poseCount = -1; m_poseStatus = TangoEnums.TangoPoseStatusType.NA; m_prevTangoRotation = m_tangoRotation = Quaternion.identity; m_prevTangoPosition = m_tangoPosition = Vector3.zero; m_uwTuc = Matrix4x4.identity; m_uwOffsetTuw = Matrix4x4.identity; } /// <summary> /// Start is called on the frame when a script is enabled. /// </summary> public void Start() { m_tangoApplication = FindObjectOfType<TangoApplication>(); m_characterController = GetComponent<CharacterController>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); if (AndroidHelper.IsTangoCorePresent()) { // Request Tango permissions m_tangoApplication.RequestPermissions(); } else { // If no Tango Core is present let's tell the user to install it! StartCoroutine(_InformUserNoTangoCore()); } } else { Debug.Log("No Tango Manager found in scene."); } SetPose(transform.position, transform.rotation); } /// <summary> /// Update is called every frame. /// </summary> public void Update() { #if UNITY_ANDROID && !UNITY_EDITOR if (Input.GetKeyDown(KeyCode.Escape)) { if (m_tangoApplication != null) { m_tangoApplication.Shutdown(); } // This is a temporary fix for a lifecycle issue where calling // Application.Quit() here, and restarting the application immediately, // results in a hard crash. AndroidHelper.AndroidQuit(); } #else Vector3 tempPosition = transform.position; Quaternion tempRotation = transform.rotation; PoseProvider.GetMouseEmulation(ref tempPosition, ref tempRotation); transform.rotation = tempRotation; transform.position = tempPosition; #endif } /// <summary> /// OnGUI is called for rendering and handling GUI events. /// </summary> public void OnGUI() { if (!m_enableClutchUI) { return; } bool buttonState = GUI.RepeatButton(new Rect(10, 500, 200, 200), "<size=40>CLUTCH</size>"); // OnGUI is called multiple times per frame. Make sure to only care about the last one. if (Event.current.type == EventType.Repaint) { ClutchActive = buttonState; } } /// <summary> /// Unity callback when application is paused. /// </summary> /// <param name="pauseStatus">The pauseStatus as reported by Unity.</param> public void OnApplicationPause(bool pauseStatus) { m_poseDeltaTime = -1.0f; m_poseTimestamp = -1.0f; m_poseCount = -1; m_poseStatus = TangoEnums.TangoPoseStatusType.NA; } /// <summary> /// OnTangoPoseAvailable is called from Tango when a new Pose is available. /// </summary> /// <param name="pose">The new Tango pose.</param> public void OnTangoPoseAvailable(TangoPoseData pose) { // Get out of here if the pose is null if (pose == null) { Debug.Log("TangoPoseDate is null."); return; } // Only interested in pose updates relative to the start of service pose. if (!m_useAreaDescriptionPose) { if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE && pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE) { _UpdateTransformationFromPose(pose); } } else { if (pose.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION && pose.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE) { _UpdateTransformationFromPose(pose); } } } /// <summary> /// Sets the pose on this component. Future Tango pose updates will move relative to this pose. /// </summary> /// <param name="pos">New position.</param> /// <param name="quat">New rotation.</param> public void SetPose(Vector3 pos, Quaternion quat) { Quaternion uwQuc = Quaternion.LookRotation(m_uwTuc.GetColumn(2), m_uwTuc.GetColumn(1)); Vector3 eulerAngles = quat.eulerAngles; eulerAngles.x = uwQuc.eulerAngles.x; eulerAngles.z = uwQuc.eulerAngles.z; quat.eulerAngles = eulerAngles; m_uwOffsetTuw = Matrix4x4.TRS(pos, quat, Vector3.one) * m_uwTuc.inverse; m_prevTangoPosition = m_tangoPosition = pos; m_prevTangoRotation = m_tangoRotation = quat; m_characterController.transform.position = pos; m_characterController.transform.rotation = quat; } /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { if (permissionsGranted) { if (m_tangoApplication.m_enableADFLoading && m_areaDescription != null) { m_tangoApplication.Startup(m_areaDescription); } else { m_tangoApplication.Startup(null); } } else { AndroidHelper.ShowAndroidToastMessage("Motion Tracking Permissions Needed", true); } } /// <summary> /// This is called when succesfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// Set controller's transformation based on received pose. /// </summary> /// <param name="pose">Received Tango pose data.</param> private void _UpdateTransformationFromPose(TangoPoseData pose) { // Remember the previous position, so you can do delta motion m_prevTangoPosition = m_tangoPosition; m_prevTangoRotation = m_tangoRotation; // The callback pose is for device with respect to start of service pose. if (pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { // Construct matrix for the start of service with respect to device from the pose. Vector3 posePosition = new Vector3((float)pose.translation[0], (float)pose.translation[1], (float)pose.translation[2]); Quaternion poseRotation = new Quaternion((float)pose.orientation[0], (float)pose.orientation[1], (float)pose.orientation[2], (float)pose.orientation[3]); Matrix4x4 ssTd = Matrix4x4.TRS(posePosition, poseRotation, Vector3.one); // Calculate matrix for the camera in the Unity world, taking into account offsets. m_uwTuc = m_uwTss * ssTd * m_dTuc; Matrix4x4 uwOffsetTuc = m_uwOffsetTuw * m_uwTuc; // Extract final position, rotation. m_tangoPosition = uwOffsetTuc.GetColumn(3); m_tangoRotation = Quaternion.LookRotation(uwOffsetTuc.GetColumn(2), uwOffsetTuc.GetColumn(1)); // Other pose data -- Pose count gets reset if pose status just became valid. if (pose.status_code != m_poseStatus) { m_poseCount = 0; } m_poseCount++; // Other pose data -- Pose delta time. m_poseDeltaTime = (float)pose.timestamp - m_poseTimestamp; m_poseTimestamp = (float)pose.timestamp; } m_poseStatus = pose.status_code; if (m_clutchActive) { // When clutching, preserve position. m_tangoPosition = m_prevTangoPosition; // When clutching, preserve yaw, keep changes in pitch, roll. Vector3 rotationAngles = m_tangoRotation.eulerAngles; rotationAngles.y = m_prevTangoRotation.eulerAngles.y; m_tangoRotation.eulerAngles = rotationAngles; } // Calculate final position and rotation deltas and apply them. Vector3 deltaPosition = m_tangoPosition - m_prevTangoPosition; Quaternion deltaRotation = m_tangoRotation * Quaternion.Inverse(m_prevTangoRotation); if (m_characterMotion) { m_characterController.Move(deltaPosition); transform.rotation = deltaRotation * transform.rotation; } else { transform.position = transform.position + deltaPosition; transform.rotation = deltaRotation * transform.rotation; } } /// <summary> /// Internal callback when no Tango core is present. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _InformUserNoTangoCore() { AndroidHelper.ShowAndroidToastMessage("Please install Tango Core", false); yield return new WaitForSeconds(2.0f); Application.Quit(); } }
using System; using System.Runtime.CompilerServices; using Etg.SimpleStubs; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubIApplicationLogEntry : IApplicationLogEntry { private readonly StubContainer<StubIApplicationLogEntry> _stubs = new StubContainer<StubIApplicationLogEntry>(); global::System.Guid global::Sannel.House.ServerSDK.IApplicationLogEntry.Id { get { return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke(); } set { _stubs.GetMethodStub<Id_Set_Delegate>("set_Id").Invoke(value); } } int? global::Sannel.House.ServerSDK.IApplicationLogEntry.DeviceId { get { return _stubs.GetMethodStub<DeviceId_Get_Delegate>("get_DeviceId").Invoke(); } set { _stubs.GetMethodStub<DeviceId_Set_Delegate>("set_DeviceId").Invoke(value); } } string global::Sannel.House.ServerSDK.IApplicationLogEntry.ApplicationId { get { return _stubs.GetMethodStub<ApplicationId_Get_Delegate>("get_ApplicationId").Invoke(); } set { _stubs.GetMethodStub<ApplicationId_Set_Delegate>("set_ApplicationId").Invoke(value); } } string global::Sannel.House.ServerSDK.IApplicationLogEntry.Message { get { return _stubs.GetMethodStub<Message_Get_Delegate>("get_Message").Invoke(); } set { _stubs.GetMethodStub<Message_Set_Delegate>("set_Message").Invoke(value); } } string global::Sannel.House.ServerSDK.IApplicationLogEntry.Exception { get { return _stubs.GetMethodStub<Exception_Get_Delegate>("get_Exception").Invoke(); } set { _stubs.GetMethodStub<Exception_Set_Delegate>("set_Exception").Invoke(value); } } global::System.DateTimeOffset global::Sannel.House.ServerSDK.IApplicationLogEntry.CreatedDate { get { return _stubs.GetMethodStub<CreatedDate_Get_Delegate>("get_CreatedDate").Invoke(); } set { _stubs.GetMethodStub<CreatedDate_Set_Delegate>("set_CreatedDate").Invoke(value); } } public delegate global::System.Guid Id_Get_Delegate(); public StubIApplicationLogEntry Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Id_Set_Delegate(global::System.Guid value); public StubIApplicationLogEntry Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate int? DeviceId_Get_Delegate(); public StubIApplicationLogEntry DeviceId_Get(DeviceId_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DeviceId_Set_Delegate(int? value); public StubIApplicationLogEntry DeviceId_Set(DeviceId_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate string ApplicationId_Get_Delegate(); public StubIApplicationLogEntry ApplicationId_Get(ApplicationId_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void ApplicationId_Set_Delegate(string value); public StubIApplicationLogEntry ApplicationId_Set(ApplicationId_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate string Message_Get_Delegate(); public StubIApplicationLogEntry Message_Get(Message_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Message_Set_Delegate(string value); public StubIApplicationLogEntry Message_Set(Message_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate string Exception_Get_Delegate(); public StubIApplicationLogEntry Exception_Get(Exception_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Exception_Set_Delegate(string value); public StubIApplicationLogEntry Exception_Set(Exception_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset CreatedDate_Get_Delegate(); public StubIApplicationLogEntry CreatedDate_Get(CreatedDate_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void CreatedDate_Set_Delegate(global::System.DateTimeOffset value); public StubIApplicationLogEntry CreatedDate_Set(CreatedDate_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubICreateHelper : ICreateHelper { private readonly StubContainer<StubICreateHelper> _stubs = new StubContainer<StubICreateHelper>(); global::Sannel.House.ServerSDK.IDevice global::Sannel.House.ServerSDK.ICreateHelper.CreateDevice() { return _stubs.GetMethodStub<CreateDevice_Delegate>("CreateDevice").Invoke(); } public delegate global::Sannel.House.ServerSDK.IDevice CreateDevice_Delegate(); public StubICreateHelper CreateDevice(CreateDevice_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } global::Sannel.House.ServerSDK.ITemperatureSetting global::Sannel.House.ServerSDK.ICreateHelper.CreateTemperatureSetting() { return _stubs.GetMethodStub<CreateTemperatureSetting_Delegate>("CreateTemperatureSetting").Invoke(); } public delegate global::Sannel.House.ServerSDK.ITemperatureSetting CreateTemperatureSetting_Delegate(); public StubICreateHelper CreateTemperatureSetting(CreateTemperatureSetting_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } global::Sannel.House.ServerSDK.IApplicationLogEntry global::Sannel.House.ServerSDK.ICreateHelper.CreateApplicationLogEntry() { return _stubs.GetMethodStub<CreateApplicationLogEntry_Delegate>("CreateApplicationLogEntry").Invoke(); } public delegate global::Sannel.House.ServerSDK.IApplicationLogEntry CreateApplicationLogEntry_Delegate(); public StubICreateHelper CreateApplicationLogEntry(CreateApplicationLogEntry_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } global::Sannel.House.ServerSDK.ITemperatureEntry global::Sannel.House.ServerSDK.ICreateHelper.CreateTemperatureEntry() { return _stubs.GetMethodStub<CreateTemperatureEntry_Delegate>("CreateTemperatureEntry").Invoke(); } public delegate global::Sannel.House.ServerSDK.ITemperatureEntry CreateTemperatureEntry_Delegate(); public StubICreateHelper CreateTemperatureEntry(CreateTemperatureEntry_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubIDevice : IDevice { private readonly StubContainer<StubIDevice> _stubs = new StubContainer<StubIDevice>(); int global::Sannel.House.ServerSDK.IDevice.Id { get { return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke(); } set { _stubs.GetMethodStub<Id_Set_Delegate>("set_Id").Invoke(value); } } string global::Sannel.House.ServerSDK.IDevice.Name { get { return _stubs.GetMethodStub<Name_Get_Delegate>("get_Name").Invoke(); } set { _stubs.GetMethodStub<Name_Set_Delegate>("set_Name").Invoke(value); } } string global::Sannel.House.ServerSDK.IDevice.Description { get { return _stubs.GetMethodStub<Description_Get_Delegate>("get_Description").Invoke(); } set { _stubs.GetMethodStub<Description_Set_Delegate>("set_Description").Invoke(value); } } int global::Sannel.House.ServerSDK.IDevice.DisplayOrder { get { return _stubs.GetMethodStub<DisplayOrder_Get_Delegate>("get_DisplayOrder").Invoke(); } set { _stubs.GetMethodStub<DisplayOrder_Set_Delegate>("set_DisplayOrder").Invoke(value); } } global::System.DateTimeOffset global::Sannel.House.ServerSDK.IDevice.DateCreated { get { return _stubs.GetMethodStub<DateCreated_Get_Delegate>("get_DateCreated").Invoke(); } set { _stubs.GetMethodStub<DateCreated_Set_Delegate>("set_DateCreated").Invoke(value); } } bool global::Sannel.House.ServerSDK.IDevice.IsReadOnly { get { return _stubs.GetMethodStub<IsReadOnly_Get_Delegate>("get_IsReadOnly").Invoke(); } set { _stubs.GetMethodStub<IsReadOnly_Set_Delegate>("set_IsReadOnly").Invoke(value); } } public delegate int Id_Get_Delegate(); public StubIDevice Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Id_Set_Delegate(int value); public StubIDevice Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate string Name_Get_Delegate(); public StubIDevice Name_Get(Name_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Name_Set_Delegate(string value); public StubIDevice Name_Set(Name_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate string Description_Get_Delegate(); public StubIDevice Description_Get(Description_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Description_Set_Delegate(string value); public StubIDevice Description_Set(Description_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate int DisplayOrder_Get_Delegate(); public StubIDevice DisplayOrder_Get(DisplayOrder_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DisplayOrder_Set_Delegate(int value); public StubIDevice DisplayOrder_Set(DisplayOrder_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset DateCreated_Get_Delegate(); public StubIDevice DateCreated_Get(DateCreated_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DateCreated_Set_Delegate(global::System.DateTimeOffset value); public StubIDevice DateCreated_Set(DateCreated_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate bool IsReadOnly_Get_Delegate(); public StubIDevice IsReadOnly_Get(IsReadOnly_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void IsReadOnly_Set_Delegate(bool value); public StubIDevice IsReadOnly_Set(IsReadOnly_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubITemperatureEntry : ITemperatureEntry { private readonly StubContainer<StubITemperatureEntry> _stubs = new StubContainer<StubITemperatureEntry>(); global::System.Guid global::Sannel.House.ServerSDK.ITemperatureEntry.Id { get { return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke(); } set { _stubs.GetMethodStub<Id_Set_Delegate>("set_Id").Invoke(value); } } int global::Sannel.House.ServerSDK.ITemperatureEntry.DeviceId { get { return _stubs.GetMethodStub<DeviceId_Get_Delegate>("get_DeviceId").Invoke(); } set { _stubs.GetMethodStub<DeviceId_Set_Delegate>("set_DeviceId").Invoke(value); } } double global::Sannel.House.ServerSDK.ITemperatureEntry.TemperatureCelsius { get { return _stubs.GetMethodStub<TemperatureCelsius_Get_Delegate>("get_TemperatureCelsius").Invoke(); } set { _stubs.GetMethodStub<TemperatureCelsius_Set_Delegate>("set_TemperatureCelsius").Invoke(value); } } double global::Sannel.House.ServerSDK.ITemperatureEntry.Humidity { get { return _stubs.GetMethodStub<Humidity_Get_Delegate>("get_Humidity").Invoke(); } set { _stubs.GetMethodStub<Humidity_Set_Delegate>("set_Humidity").Invoke(value); } } double global::Sannel.House.ServerSDK.ITemperatureEntry.Pressure { get { return _stubs.GetMethodStub<Pressure_Get_Delegate>("get_Pressure").Invoke(); } set { _stubs.GetMethodStub<Pressure_Set_Delegate>("set_Pressure").Invoke(value); } } global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureEntry.CreatedDateTime { get { return _stubs.GetMethodStub<CreatedDateTime_Get_Delegate>("get_CreatedDateTime").Invoke(); } set { _stubs.GetMethodStub<CreatedDateTime_Set_Delegate>("set_CreatedDateTime").Invoke(value); } } public delegate global::System.Guid Id_Get_Delegate(); public StubITemperatureEntry Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Id_Set_Delegate(global::System.Guid value); public StubITemperatureEntry Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate int DeviceId_Get_Delegate(); public StubITemperatureEntry DeviceId_Get(DeviceId_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DeviceId_Set_Delegate(int value); public StubITemperatureEntry DeviceId_Set(DeviceId_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate double TemperatureCelsius_Get_Delegate(); public StubITemperatureEntry TemperatureCelsius_Get(TemperatureCelsius_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void TemperatureCelsius_Set_Delegate(double value); public StubITemperatureEntry TemperatureCelsius_Set(TemperatureCelsius_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate double Humidity_Get_Delegate(); public StubITemperatureEntry Humidity_Get(Humidity_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Humidity_Set_Delegate(double value); public StubITemperatureEntry Humidity_Set(Humidity_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate double Pressure_Get_Delegate(); public StubITemperatureEntry Pressure_Get(Pressure_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Pressure_Set_Delegate(double value); public StubITemperatureEntry Pressure_Set(Pressure_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset CreatedDateTime_Get_Delegate(); public StubITemperatureEntry CreatedDateTime_Get(CreatedDateTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void CreatedDateTime_Set_Delegate(global::System.DateTimeOffset value); public StubITemperatureEntry CreatedDateTime_Set(CreatedDateTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubITemperatureSetting : ITemperatureSetting { private readonly StubContainer<StubITemperatureSetting> _stubs = new StubContainer<StubITemperatureSetting>(); long global::Sannel.House.ServerSDK.ITemperatureSetting.Id { get { return _stubs.GetMethodStub<Id_Get_Delegate>("get_Id").Invoke(); } set { _stubs.GetMethodStub<Id_Set_Delegate>("set_Id").Invoke(value); } } int? global::Sannel.House.ServerSDK.ITemperatureSetting.DayOfWeek { get { return _stubs.GetMethodStub<DayOfWeek_Get_Delegate>("get_DayOfWeek").Invoke(); } set { _stubs.GetMethodStub<DayOfWeek_Set_Delegate>("set_DayOfWeek").Invoke(value); } } int? global::Sannel.House.ServerSDK.ITemperatureSetting.Month { get { return _stubs.GetMethodStub<Month_Get_Delegate>("get_Month").Invoke(); } set { _stubs.GetMethodStub<Month_Set_Delegate>("set_Month").Invoke(value); } } bool global::Sannel.House.ServerSDK.ITemperatureSetting.IsTimeOnly { get { return _stubs.GetMethodStub<IsTimeOnly_Get_Delegate>("get_IsTimeOnly").Invoke(); } set { _stubs.GetMethodStub<IsTimeOnly_Set_Delegate>("set_IsTimeOnly").Invoke(value); } } global::System.DateTimeOffset? global::Sannel.House.ServerSDK.ITemperatureSetting.StartTime { get { return _stubs.GetMethodStub<StartTime_Get_Delegate>("get_StartTime").Invoke(); } set { _stubs.GetMethodStub<StartTime_Set_Delegate>("set_StartTime").Invoke(value); } } global::System.DateTimeOffset? global::Sannel.House.ServerSDK.ITemperatureSetting.EndTime { get { return _stubs.GetMethodStub<EndTime_Get_Delegate>("get_EndTime").Invoke(); } set { _stubs.GetMethodStub<EndTime_Set_Delegate>("set_EndTime").Invoke(value); } } double global::Sannel.House.ServerSDK.ITemperatureSetting.HeatTemperatureC { get { return _stubs.GetMethodStub<HeatTemperatureC_Get_Delegate>("get_HeatTemperatureC").Invoke(); } set { _stubs.GetMethodStub<HeatTemperatureC_Set_Delegate>("set_HeatTemperatureC").Invoke(value); } } double global::Sannel.House.ServerSDK.ITemperatureSetting.CoolTemperatureC { get { return _stubs.GetMethodStub<CoolTemperatureC_Get_Delegate>("get_CoolTemperatureC").Invoke(); } set { _stubs.GetMethodStub<CoolTemperatureC_Set_Delegate>("set_CoolTemperatureC").Invoke(value); } } global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureSetting.DateCreated { get { return _stubs.GetMethodStub<DateCreated_Get_Delegate>("get_DateCreated").Invoke(); } set { _stubs.GetMethodStub<DateCreated_Set_Delegate>("set_DateCreated").Invoke(value); } } global::System.DateTimeOffset global::Sannel.House.ServerSDK.ITemperatureSetting.DateModified { get { return _stubs.GetMethodStub<DateModified_Get_Delegate>("get_DateModified").Invoke(); } set { _stubs.GetMethodStub<DateModified_Set_Delegate>("set_DateModified").Invoke(value); } } public delegate long Id_Get_Delegate(); public StubITemperatureSetting Id_Get(Id_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Id_Set_Delegate(long value); public StubITemperatureSetting Id_Set(Id_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate int? DayOfWeek_Get_Delegate(); public StubITemperatureSetting DayOfWeek_Get(DayOfWeek_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DayOfWeek_Set_Delegate(int? value); public StubITemperatureSetting DayOfWeek_Set(DayOfWeek_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate int? Month_Get_Delegate(); public StubITemperatureSetting Month_Get(Month_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void Month_Set_Delegate(int? value); public StubITemperatureSetting Month_Set(Month_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate bool IsTimeOnly_Get_Delegate(); public StubITemperatureSetting IsTimeOnly_Get(IsTimeOnly_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void IsTimeOnly_Set_Delegate(bool value); public StubITemperatureSetting IsTimeOnly_Set(IsTimeOnly_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset? StartTime_Get_Delegate(); public StubITemperatureSetting StartTime_Get(StartTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void StartTime_Set_Delegate(global::System.DateTimeOffset? value); public StubITemperatureSetting StartTime_Set(StartTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset? EndTime_Get_Delegate(); public StubITemperatureSetting EndTime_Get(EndTime_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void EndTime_Set_Delegate(global::System.DateTimeOffset? value); public StubITemperatureSetting EndTime_Set(EndTime_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate double HeatTemperatureC_Get_Delegate(); public StubITemperatureSetting HeatTemperatureC_Get(HeatTemperatureC_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void HeatTemperatureC_Set_Delegate(double value); public StubITemperatureSetting HeatTemperatureC_Set(HeatTemperatureC_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate double CoolTemperatureC_Get_Delegate(); public StubITemperatureSetting CoolTemperatureC_Get(CoolTemperatureC_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void CoolTemperatureC_Set_Delegate(double value); public StubITemperatureSetting CoolTemperatureC_Set(CoolTemperatureC_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset DateCreated_Get_Delegate(); public StubITemperatureSetting DateCreated_Get(DateCreated_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DateCreated_Set_Delegate(global::System.DateTimeOffset value); public StubITemperatureSetting DateCreated_Set(DateCreated_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate global::System.DateTimeOffset DateModified_Get_Delegate(); public StubITemperatureSetting DateModified_Get(DateModified_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void DateModified_Set_Delegate(global::System.DateTimeOffset value); public StubITemperatureSetting DateModified_Set(DateModified_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubIHttpClient : IHttpClient { private readonly StubContainer<StubIHttpClient> _stubs = new StubContainer<StubIHttpClient>(); string global::Sannel.House.ServerSDK.IHttpClient.GetCookieValue(global::System.Uri uri, string cookieName) { return _stubs.GetMethodStub<GetCookieValue_Uri_String_Delegate>("GetCookieValue").Invoke(uri, cookieName); } public delegate string GetCookieValue_Uri_String_Delegate(global::System.Uri uri, string cookieName); public StubIHttpClient GetCookieValue(GetCookieValue_Uri_String_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.HttpClientResult> global::Sannel.House.ServerSDK.IHttpClient.GetAsync(global::System.Uri requestUri) { return _stubs.GetMethodStub<GetAsync_Uri_Delegate>("GetAsync").Invoke(requestUri); } public delegate global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.HttpClientResult> GetAsync_Uri_Delegate(global::System.Uri requestUri); public StubIHttpClient GetAsync(GetAsync_Uri_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.HttpClientResult> global::Sannel.House.ServerSDK.IHttpClient.PostAsync(global::System.Uri requestUri, global::System.Collections.Generic.IDictionary<string, string> data) { return _stubs.GetMethodStub<PostAsync_Uri_IDictionaryOfStringString_Delegate>("PostAsync").Invoke(requestUri, data); } public delegate global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.HttpClientResult> PostAsync_Uri_IDictionaryOfStringString_Delegate(global::System.Uri requestUri, global::System.Collections.Generic.IDictionary<string, string> data); public StubIHttpClient PostAsync(PostAsync_Uri_IDictionaryOfStringString_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } void global::System.IDisposable.Dispose() { _stubs.GetMethodStub<IDisposable_Dispose_Delegate>("Dispose").Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIHttpClient Dispose(IDisposable_Dispose_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubIServerContext : IServerContext { private readonly StubContainer<StubIServerContext> _stubs = new StubContainer<StubIServerContext>(); bool global::Sannel.House.ServerSDK.IServerContext.IsAuthenticated { get { return _stubs.GetMethodStub<IsAuthenticated_Get_Delegate>("get_IsAuthenticated").Invoke(); } } global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.LoginResult> global::Sannel.House.ServerSDK.IServerContext.LoginAsync(string username, string password) { return _stubs.GetMethodStub<LoginAsync_String_String_Delegate>("LoginAsync").Invoke(username, password); } public delegate global::System.Threading.Tasks.Task<global::Sannel.House.ServerSDK.LoginResult> LoginAsync_String_String_Delegate(string username, string password); public StubIServerContext LoginAsync(LoginAsync_String_String_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate bool IsAuthenticated_Get_Delegate(); public StubIServerContext IsAuthenticated_Get(IsAuthenticated_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } void global::System.IDisposable.Dispose() { _stubs.GetMethodStub<IDisposable_Dispose_Delegate>("Dispose").Invoke(); } public delegate void IDisposable_Dispose_Delegate(); public StubIServerContext Dispose(IDisposable_Dispose_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } } namespace Sannel.House.ServerSDK { [CompilerGenerated] public class StubIServerSettings : IServerSettings { private readonly StubContainer<StubIServerSettings> _stubs = new StubContainer<StubIServerSettings>(); global::System.Uri global::Sannel.House.ServerSDK.IServerSettings.ServerUri { get { return _stubs.GetMethodStub<ServerUri_Get_Delegate>("get_ServerUri").Invoke(); } set { _stubs.GetMethodStub<ServerUri_Set_Delegate>("set_ServerUri").Invoke(value); } } public delegate global::System.Uri ServerUri_Get_Delegate(); public StubIServerSettings ServerUri_Get(ServerUri_Get_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } public delegate void ServerUri_Set_Delegate(global::System.Uri value); public StubIServerSettings ServerUri_Set(ServerUri_Set_Delegate del, int count = Times.Forever, bool overwrite = false) { _stubs.SetMethodStub(del, count, overwrite); return this; } } }
//Apache2,GitHub:mongodb-csharp using System; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace MongoDB { /// <summary> /// </summary> [Serializable] public sealed class MongoRegex : IEquatable<MongoRegex>, IXmlSerializable { /// <summary> /// Initializes a new instance of the <see cref = "MongoRegex" /> class. /// </summary> public MongoRegex() { } /// <summary> /// Initializes a new instance of the <see cref = "MongoRegex" /> class. /// </summary> /// <param name = "expression">The expression.</param> public MongoRegex(string expression) : this(expression, string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref = "MongoRegex" /> class. /// </summary> /// <param name = "expression">The expression.</param> /// <param name = "options">The options.</param> public MongoRegex(string expression, MongoRegexOption options) { Expression = expression; Options = options; } /// <summary> /// Initializes a new instance of the <see cref="MongoRegex"/> class. /// </summary> /// <param name="expression">The Regex expression.</param> /// <param name="options">The Regex options.</param> public MongoRegex(string expression, RegexOptions options) : this(new Regex(expression, options)) { } /// <summary> /// Initializes a new instance of the <see cref = "MongoRegex" /> class. /// </summary> /// <param name = "regex">The regex.</param> public MongoRegex(Regex regex) { if(regex == null) throw new ArgumentNullException("regex"); Expression = regex.ToString(); ToggleOption("i", (regex.Options & RegexOptions.IgnoreCase) != 0); ToggleOption("m", (regex.Options & RegexOptions.Multiline) != 0); ToggleOption("g", (regex.Options & RegexOptions.IgnorePatternWhitespace) != 0); } /// <summary> /// Initializes a new instance of the <see cref = "MongoRegex" /> class. /// </summary> /// <param name = "expression">The expression.</param> /// <param name = "options">The options.</param> public MongoRegex(string expression, string options) { Expression = expression; RawOptions = options; } /// <summary> /// A valid regex string including the enclosing / characters. /// </summary> public string Expression { get; set; } /// <summary> /// Gets or sets the options. /// </summary> /// <value>The options.</value> public MongoRegexOption Options { get { var options = MongoRegexOption.None; if(RawOptions != null) { if(RawOptions.Contains("i")) options = options | MongoRegexOption.IgnoreCase; if(RawOptions.Contains("m")) options = options | MongoRegexOption.Multiline; if(RawOptions.Contains("g")) options = options | MongoRegexOption.IgnorePatternWhitespace; } return options; } set { ToggleOption("i", (value & MongoRegexOption.IgnoreCase) != 0); ToggleOption("m", (value & MongoRegexOption.Multiline) != 0); ToggleOption("g", (value & MongoRegexOption.IgnorePatternWhitespace) != 0); } } /// <summary> /// A string that may contain only the characters 'g', 'i', and 'm'. /// Because the JS and TenGen representations support a limited range of options, /// any nonconforming options will be dropped when converting to this representation /// </summary> public string RawOptions { get; set; } /// <summary> /// Builds a .Net Regex. /// </summary> /// <returns></returns> public Regex BuildRegex() { var options = RegexOptions.None; if(RawOptions != null) { if(RawOptions.Contains("i")) options = options | RegexOptions.IgnoreCase; if(RawOptions.Contains("m")) options = options | RegexOptions.Multiline; if(RawOptions.Contains("g")) options = options | RegexOptions.IgnorePatternWhitespace; } return new Regex(Expression,options); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name = "other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false. /// </returns> public bool Equals(MongoRegex other) { if(ReferenceEquals(null, other)) return false; if(ReferenceEquals(this, other)) return true; return Equals(other.Expression, Expression) && Equals(other.RawOptions, RawOptions); } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref = "T:System.Xml.Serialization.XmlSchemaProviderAttribute" /> to the class. /// </summary> /// <returns> /// An <see cref = "T:System.Xml.Schema.XmlSchema" /> that describes the XML representation of the object that is produced by the <see cref = "M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)" /> method and consumed by the <see cref = "M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)" /> method. /// </returns> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name = "reader">The <see cref = "T:System.Xml.XmlReader" /> stream from which the object is deserialized.</param> void IXmlSerializable.ReadXml(XmlReader reader) { if(reader.MoveToAttribute("options")) RawOptions = reader.Value; if(reader.IsEmptyElement) return; Expression = reader.ReadString(); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name = "writer">The <see cref = "T:System.Xml.XmlWriter" /> stream to which the object is serialized.</param> void IXmlSerializable.WriteXml(XmlWriter writer) { if(RawOptions != null) writer.WriteAttributeString("options", RawOptions); if(Expression == null) return; writer.WriteString(Expression); } /// <summary> /// Toggles the option. /// </summary> /// <param name = "option">The option.</param> /// <param name = "enabled">if set to <c>true</c> [enabled].</param> private void ToggleOption(string option, bool enabled) { if(RawOptions == null) RawOptions = string.Empty; if(enabled) { if(RawOptions.Contains(option)) return; RawOptions += option; } else { if(!RawOptions.Contains(option)) return; RawOptions = RawOptions.Replace(option, string.Empty); } } /// <summary> /// Determines whether the specified <see cref = "System.Object" /> is equal to this instance. /// </summary> /// <param name = "obj">The <see cref = "System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref = "System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref = "T:System.NullReferenceException"> /// The <paramref name = "obj" /> parameter is null. /// </exception> public override bool Equals(object obj) { if(ReferenceEquals(null, obj)) return false; if(ReferenceEquals(this, obj)) return true; return obj.GetType() == typeof(MongoRegex) && Equals((MongoRegex)obj); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name = "left">The left.</param> /// <param name = "right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(MongoRegex left, MongoRegex right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name = "left">The left.</param> /// <param name = "right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(MongoRegex left, MongoRegex right) { return !Equals(left, right); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { unchecked { return ((Expression != null ? Expression.GetHashCode() : 0)*397) ^ (RawOptions != null ? RawOptions.GetHashCode() : 0); } } /// <summary> /// Returns a <see cref = "System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref = "System.String" /> that represents this instance. /// </returns> public override string ToString() { return string.Format("{0}{1}", Expression, RawOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using Xunit; using Microsoft.Extensions.DependencyModel; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class StartupHooks : IClassFixture<StartupHooks.SharedTestState> { private SharedTestState sharedTestState; private string startupHookVarName = "DOTNET_STARTUP_HOOKS"; public StartupHooks(StartupHooks.SharedTestState fixture) { sharedTestState = fixture; } // Run the app with a startup hook [Fact] public void Muxer_activation_of_StartupHook_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookWithNonPublicMethodFixture = sharedTestState.StartupHookWithNonPublicMethodFixture.Copy(); var startupHookWithNonPublicMethodDll = startupHookWithNonPublicMethodFixture.TestProject.AppDll; // Simple startup hook dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Non-public Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithNonPublicMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with non-public method"); // Ensure startup hook tracing works dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining("Property STARTUP_HOOKS = " + startupHookDll) .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Startup hook in type that has an additional overload of Initialize with a different signature startupHookFixture = sharedTestState.StartupHookWithOverloadFixture.Copy(); startupHookDll = startupHookFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with overload! Input: 123") .And.HaveStdOutContaining("Hello World"); } // Run the app with multiple startup hooks [Fact] public void Muxer_activation_of_Multiple_StartupHooks_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Multiple startup hooks var startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } // Empty startup hook variable [Fact] public void Muxer_activation_of_Empty_StartupHook_Variable_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookVar = ""; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World"); } // Run the app with a startup hook assembly that depends on assemblies not on the TPA list [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Dependencies_Fails() { var fixture = sharedTestState.PortableAppWithExceptionFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // Startup hook has a dependency not on the TPA list dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json"); } // Different variants of the startup hook variable format [Fact] public void Muxer_activation_of_StartupHook_VariableVariants() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Missing entries in the hook var startupHookVar = startupHookDll + Path.PathSeparator + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); // Whitespace is invalid startupHookVar = startupHookDll + Path.PathSeparator + " " + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.ArgumentException: The startup hook simple assembly name ' ' is invalid."); // Leading separator startupHookVar = Path.PathSeparator + startupHookDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Trailing separator startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll + Path.PathSeparator; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_StartupHook_With_Invalid_Simple_Name_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var relativeAssemblyPath = $".{Path.DirectorySeparatorChar}Assembly"; var expectedError = "System.ArgumentException: The startup hook simple assembly name '{0}' is invalid."; // With directory separator var startupHookVar = relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With alternative directory separator startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With comma startupHookVar = $"Assembly,version=1.0.0.0"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With space startupHookVar = $"Assembly version"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With .dll suffix startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly.DLl"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With invalid name startupHookVar = $"Assembly=Name"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining("---> System.IO.FileLoadException: The given assembly name or codebase was invalid."); // Relative path error is caught before any hooks run startupHookVar = startupHookDll + Path.PathSeparator + relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, relativeAssemblyPath)) .And.NotHaveStdOutContaining("Hello from startup hook!"); } [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: Startup hook assembly '{0}' failed to load."; // With file path which doesn't exist var startupHookVar = startupHookDll + ".missing.dll"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}'. The system cannot find the file specified."); // With simple name which won't resolve startupHookVar = "MissingAssembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}"); } [Fact] public void Muxer_activation_of_StartupHook_WithSimpleAssemblyName_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookAssemblyName = Path.GetFileNameWithoutExtension(startupHookDll); File.Copy(startupHookDll, Path.Combine(fixture.TestProject.BuiltApp.Location, Path.GetFileName(startupHookDll))); SharedFramework.AddReferenceToDepsJson( fixture.TestProject.DepsJson, $"{fixture.TestProject.AssemblyName}/1.0.0", startupHookAssemblyName, "1.0.0"); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll) .EnvironmentVariable(startupHookVarName, startupHookAssemblyName) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } // Run the app with missing startup hook assembly [Fact] public void Muxer_activation_of_Missing_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingDll = Path.Combine(Path.GetDirectoryName(startupHookDll), "StartupHookMissing.dll"); var expectedError = "System.IO.FileNotFoundException: Could not load file or assembly '{0}'."; // Missing dll is detected with appropriate error var startupHookVar = startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, Path.GetFullPath(startupHookMissingDll))); // Missing dll is detected after previous hooks run startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(String.Format(expectedError, Path.GetFullPath((startupHookMissingDll)))); } // Run the app with an invalid startup hook assembly [Fact] public void Muxer_activation_of_Invalid_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookInvalidAssembly = sharedTestState.StartupHookStartupHookInvalidAssemblyFixture.Copy(); var startupHookInvalidAssemblyDll = Path.Combine(Path.GetDirectoryName(startupHookInvalidAssembly.TestProject.AppDll), "StartupHookInvalidAssembly.dll"); var expectedError = "System.BadImageFormatException"; // Dll load gives meaningful error message dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookInvalidAssemblyDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Dll load error happens after previous hooks run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookInvalidAssemblyDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); } // Run the app with the startup hook type missing [Fact] public void Muxer_activation_of_Missing_StartupHook_Type_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingTypeFixture = sharedTestState.StartupHookWithoutStartupHookTypeFixture.Copy(); var startupHookMissingTypeDll = startupHookMissingTypeFixture.TestProject.AppDll; // Missing type is detected dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHook"); // Missing type is detected after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingTypeDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHookWithoutStartupHookType"); } // Run the app with a startup hook that doesn't have any Initialize method [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Method_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingMethodFixture = sharedTestState.StartupHookWithoutInitializeMethodFixture.Copy(); var startupHookMissingMethodDll = startupHookMissingMethodFixture.TestProject.AppDll; var expectedError = "System.MissingMethodException: Method 'StartupHook.Initialize' not found."; // No Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Missing Initialize method is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingMethodDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(expectedError); } // Run the app with startup hook that has no static void Initialize() method [Fact] public void Muxer_activation_of_StartupHook_With_Incorrect_Method_Signature_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: The signature of the startup hook 'StartupHook.Initialize' in assembly '{0}' was invalid. It must be 'public static void Initialize()'."; // Initialize is an instance method var startupHookWithInstanceMethodFixture = sharedTestState.StartupHookWithInstanceMethodFixture.Copy(); var startupHookWithInstanceMethodDll = startupHookWithInstanceMethodFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithInstanceMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithInstanceMethodDll)); // Initialize method takes parameters var startupHookWithParameterFixture = sharedTestState.StartupHookWithParameterFixture.Copy(); var startupHookWithParameterDll = startupHookWithParameterFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithParameterDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithParameterDll)); // Initialize method has non-void return type var startupHookWithReturnTypeFixture = sharedTestState.StartupHookWithReturnTypeFixture.Copy(); var startupHookWithReturnTypeDll = startupHookWithReturnTypeFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithReturnTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithReturnTypeDll)); // Initialize method that has multiple methods with an incorrect signature var startupHookWithMultipleIncorrectSignaturesFixture = sharedTestState.StartupHookWithMultipleIncorrectSignaturesFixture.Copy(); var startupHookWithMultipleIncorrectSignaturesDll = startupHookWithMultipleIncorrectSignaturesFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithMultipleIncorrectSignaturesDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); // Signature problem is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookWithMultipleIncorrectSignaturesDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); } private static void RemoveLibraryFromDepsJson(string depsJsonPath, string libraryName) { DependencyContext context; using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Open)) { using (DependencyContextJsonReader reader = new DependencyContextJsonReader()) { context = reader.Read(fileStream); } } context = new DependencyContext(context.Target, context.CompilationOptions, context.CompileLibraries, context.RuntimeLibraries.Select(lib => new RuntimeLibrary( lib.Type, lib.Name, lib.Version, lib.Hash, lib.RuntimeAssemblyGroups.Select(assemblyGroup => new RuntimeAssetGroup( assemblyGroup.Runtime, assemblyGroup.RuntimeFiles.Where(f => !f.Path.EndsWith("SharedLibrary.dll")))).ToList().AsReadOnly(), lib.NativeLibraryGroups, lib.ResourceAssemblies, lib.Dependencies, lib.Serviceable, lib.Path, lib.HashPath, lib.RuntimeStoreManifestName)), context.RuntimeGraph); using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Truncate, FileAccess.Write)) { DependencyContextWriter writer = new DependencyContextWriter(); writer.Write(context, fileStream); } } // Run startup hook that adds an assembly resolver [Fact] public void Muxer_activation_of_StartupHook_With_Assembly_Resolver() { var fixture = sharedTestState.PortableAppWithMissingRefFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var appDepsJson = Path.Combine(Path.GetDirectoryName(appDll), Path.GetFileNameWithoutExtension(appDll) + ".deps.json"); RemoveLibraryFromDepsJson(appDepsJson, "SharedLibrary.dll"); var startupHookFixture = sharedTestState.StartupHookWithAssemblyResolver.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // No startup hook results in failure due to missing app dependency dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("FileNotFoundException: Could not load file or assembly 'SharedLibrary"); // Startup hook with assembly resolver results in use of injected dependency (which has value 2) dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.ExitWith(2); } public class SharedTestState : IDisposable { // Entry point projects public TestProjectFixture PortableAppFixture { get; } public TestProjectFixture PortableAppWithExceptionFixture { get; } // Entry point with missing reference assembly public TestProjectFixture PortableAppWithMissingRefFixture { get; } // Correct startup hooks public TestProjectFixture StartupHookFixture { get; } public TestProjectFixture StartupHookWithOverloadFixture { get; } // Missing startup hook type (no StartupHook type defined) public TestProjectFixture StartupHookWithoutStartupHookTypeFixture { get; } // Missing startup hook method (no Initialize method defined) public TestProjectFixture StartupHookWithoutInitializeMethodFixture { get; } // Invalid startup hook assembly public TestProjectFixture StartupHookStartupHookInvalidAssemblyFixture { get; } // Invalid startup hooks (incorrect signatures) public TestProjectFixture StartupHookWithNonPublicMethodFixture { get; } public TestProjectFixture StartupHookWithInstanceMethodFixture { get; } public TestProjectFixture StartupHookWithParameterFixture { get; } public TestProjectFixture StartupHookWithReturnTypeFixture { get; } public TestProjectFixture StartupHookWithMultipleIncorrectSignaturesFixture { get; } // Valid startup hooks with incorrect behavior public TestProjectFixture StartupHookWithDependencyFixture { get; } // Startup hook with an assembly resolver public TestProjectFixture StartupHookWithAssemblyResolver { get; } public RepoDirectoriesProvider RepoDirectories { get; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); // Entry point projects PortableAppFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); PortableAppWithExceptionFixture = new TestProjectFixture("PortableAppWithException", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture = new TestProjectFixture("PortableAppWithMissingRef", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Correct startup hooks StartupHookFixture = new TestProjectFixture("StartupHook", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); StartupHookWithOverloadFixture = new TestProjectFixture("StartupHookWithOverload", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture = new TestProjectFixture("StartupHookWithoutStartupHookType", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture = new TestProjectFixture("StartupHookWithoutInitializeMethod", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture = new TestProjectFixture("StartupHookFake", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture = new TestProjectFixture("StartupHookWithNonPublicMethod", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); StartupHookWithInstanceMethodFixture = new TestProjectFixture("StartupHookWithInstanceMethod", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); StartupHookWithParameterFixture = new TestProjectFixture("StartupHookWithParameter", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); StartupHookWithReturnTypeFixture = new TestProjectFixture("StartupHookWithReturnType", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); StartupHookWithMultipleIncorrectSignaturesFixture = new TestProjectFixture("StartupHookWithMultipleIncorrectSignatures", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture = new TestProjectFixture("StartupHookWithDependency", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver = new TestProjectFixture("StartupHookWithAssemblyResolver", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); } public void Dispose() { // Entry point projects PortableAppFixture.Dispose(); PortableAppWithExceptionFixture.Dispose(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture.Dispose(); // Correct startup hooks StartupHookFixture.Dispose(); StartupHookWithOverloadFixture.Dispose(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture.Dispose(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture.Dispose(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture.Dispose(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture.Dispose(); StartupHookWithInstanceMethodFixture.Dispose(); StartupHookWithParameterFixture.Dispose(); StartupHookWithReturnTypeFixture.Dispose(); StartupHookWithMultipleIncorrectSignaturesFixture.Dispose(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture.Dispose(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver.Dispose(); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/uptime_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Monitoring.V3 { /// <summary>Holder for reflection information generated from google/monitoring/v3/uptime_service.proto</summary> public static partial class UptimeServiceReflection { #region Descriptor /// <summary>File descriptor for google/monitoring/v3/uptime_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UptimeServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cilnb29nbGUvbW9uaXRvcmluZy92My91cHRpbWVfc2VydmljZS5wcm90bxIU", "Z29vZ2xlLm1vbml0b3JpbmcudjMaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMu", "cHJvdG8aIWdvb2dsZS9tb25pdG9yaW5nL3YzL3VwdGltZS5wcm90bxobZ29v", "Z2xlL3Byb3RvYnVmL2VtcHR5LnByb3RvGiBnb29nbGUvcHJvdG9idWYvZmll", "bGRfbWFzay5wcm90byJWCh1MaXN0VXB0aW1lQ2hlY2tDb25maWdzUmVxdWVz", "dBIOCgZwYXJlbnQYASABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2Vf", "dG9rZW4YBCABKAkigAEKHkxpc3RVcHRpbWVDaGVja0NvbmZpZ3NSZXNwb25z", "ZRJFChR1cHRpbWVfY2hlY2tfY29uZmlncxgBIAMoCzInLmdvb2dsZS5tb25p", "dG9yaW5nLnYzLlVwdGltZUNoZWNrQ29uZmlnEhcKD25leHRfcGFnZV90b2tl", "bhgCIAEoCSIrChtHZXRVcHRpbWVDaGVja0NvbmZpZ1JlcXVlc3QSDAoEbmFt", "ZRgBIAEoCSJ2Ch5DcmVhdGVVcHRpbWVDaGVja0NvbmZpZ1JlcXVlc3QSDgoG", "cGFyZW50GAEgASgJEkQKE3VwdGltZV9jaGVja19jb25maWcYAiABKAsyJy5n", "b29nbGUubW9uaXRvcmluZy52My5VcHRpbWVDaGVja0NvbmZpZyKXAQoeVXBk", "YXRlVXB0aW1lQ2hlY2tDb25maWdSZXF1ZXN0Ei8KC3VwZGF0ZV9tYXNrGAIg", "ASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxJEChN1cHRpbWVfY2hl", "Y2tfY29uZmlnGAMgASgLMicuZ29vZ2xlLm1vbml0b3JpbmcudjMuVXB0aW1l", "Q2hlY2tDb25maWciLgoeRGVsZXRlVXB0aW1lQ2hlY2tDb25maWdSZXF1ZXN0", "EgwKBG5hbWUYASABKAkiQgoZTGlzdFVwdGltZUNoZWNrSXBzUmVxdWVzdBIR", "CglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCSJ0ChpMaXN0", "VXB0aW1lQ2hlY2tJcHNSZXNwb25zZRI9ChB1cHRpbWVfY2hlY2tfaXBzGAEg", "AygLMiMuZ29vZ2xlLm1vbml0b3JpbmcudjMuVXB0aW1lQ2hlY2tJcBIXCg9u", "ZXh0X3BhZ2VfdG9rZW4YAiABKAkyxwgKElVwdGltZUNoZWNrU2VydmljZRK3", "AQoWTGlzdFVwdGltZUNoZWNrQ29uZmlncxIzLmdvb2dsZS5tb25pdG9yaW5n", "LnYzLkxpc3RVcHRpbWVDaGVja0NvbmZpZ3NSZXF1ZXN0GjQuZ29vZ2xlLm1v", "bml0b3JpbmcudjMuTGlzdFVwdGltZUNoZWNrQ29uZmlnc1Jlc3BvbnNlIjKC", "0+STAiwSKi92My97cGFyZW50PXByb2plY3RzLyp9L3VwdGltZUNoZWNrQ29u", "ZmlncxKmAQoUR2V0VXB0aW1lQ2hlY2tDb25maWcSMS5nb29nbGUubW9uaXRv", "cmluZy52My5HZXRVcHRpbWVDaGVja0NvbmZpZ1JlcXVlc3QaJy5nb29nbGUu", "bW9uaXRvcmluZy52My5VcHRpbWVDaGVja0NvbmZpZyIygtPkkwIsEiovdjMv", "e25hbWU9cHJvamVjdHMvKi91cHRpbWVDaGVja0NvbmZpZ3MvKn0SwQEKF0Ny", "ZWF0ZVVwdGltZUNoZWNrQ29uZmlnEjQuZ29vZ2xlLm1vbml0b3JpbmcudjMu", "Q3JlYXRlVXB0aW1lQ2hlY2tDb25maWdSZXF1ZXN0GicuZ29vZ2xlLm1vbml0", "b3JpbmcudjMuVXB0aW1lQ2hlY2tDb25maWciR4LT5JMCQSIqL3YzL3twYXJl", "bnQ9cHJvamVjdHMvKn0vdXB0aW1lQ2hlY2tDb25maWdzOhN1cHRpbWVfY2hl", "Y2tfY29uZmlnEtUBChdVcGRhdGVVcHRpbWVDaGVja0NvbmZpZxI0Lmdvb2ds", "ZS5tb25pdG9yaW5nLnYzLlVwZGF0ZVVwdGltZUNoZWNrQ29uZmlnUmVxdWVz", "dBonLmdvb2dsZS5tb25pdG9yaW5nLnYzLlVwdGltZUNoZWNrQ29uZmlnIluC", "0+STAlUyPi92My97dXB0aW1lX2NoZWNrX2NvbmZpZy5uYW1lPXByb2plY3Rz", "LyovdXB0aW1lQ2hlY2tDb25maWdzLyp9OhN1cHRpbWVfY2hlY2tfY29uZmln", "EpsBChdEZWxldGVVcHRpbWVDaGVja0NvbmZpZxI0Lmdvb2dsZS5tb25pdG9y", "aW5nLnYzLkRlbGV0ZVVwdGltZUNoZWNrQ29uZmlnUmVxdWVzdBoWLmdvb2ds", "ZS5wcm90b2J1Zi5FbXB0eSIygtPkkwIsKiovdjMve25hbWU9cHJvamVjdHMv", "Ki91cHRpbWVDaGVja0NvbmZpZ3MvKn0SkwEKEkxpc3RVcHRpbWVDaGVja0lw", "cxIvLmdvb2dsZS5tb25pdG9yaW5nLnYzLkxpc3RVcHRpbWVDaGVja0lwc1Jl", "cXVlc3QaMC5nb29nbGUubW9uaXRvcmluZy52My5MaXN0VXB0aW1lQ2hlY2tJ", "cHNSZXNwb25zZSIagtPkkwIUEhIvdjMvdXB0aW1lQ2hlY2tJcHNCqgEKGGNv", "bS5nb29nbGUubW9uaXRvcmluZy52M0ISVXB0aW1lU2VydmljZVByb3RvUAFa", "Pmdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvbW9uaXRv", "cmluZy92Mzttb25pdG9yaW5nqgIaR29vZ2xlLkNsb3VkLk1vbml0b3Jpbmcu", "VjPKAhpHb29nbGVcQ2xvdWRcTW9uaXRvcmluZ1xWM2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.Monitoring.V3.UptimeReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest), global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsRequest.Parser, new[]{ "Parent", "PageSize", "PageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse), global::Google.Cloud.Monitoring.V3.ListUptimeCheckConfigsResponse.Parser, new[]{ "UptimeCheckConfigs", "NextPageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest), global::Google.Cloud.Monitoring.V3.GetUptimeCheckConfigRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest), global::Google.Cloud.Monitoring.V3.CreateUptimeCheckConfigRequest.Parser, new[]{ "Parent", "UptimeCheckConfig" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest), global::Google.Cloud.Monitoring.V3.UpdateUptimeCheckConfigRequest.Parser, new[]{ "UpdateMask", "UptimeCheckConfig" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest), global::Google.Cloud.Monitoring.V3.DeleteUptimeCheckConfigRequest.Parser, new[]{ "Name" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest), global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsRequest.Parser, new[]{ "PageSize", "PageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse), global::Google.Cloud.Monitoring.V3.ListUptimeCheckIpsResponse.Parser, new[]{ "UptimeCheckIps", "NextPageToken" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// The protocol for the `ListUptimeCheckConfigs` request. /// </summary> public sealed partial class ListUptimeCheckConfigsRequest : pb::IMessage<ListUptimeCheckConfigsRequest> { private static readonly pb::MessageParser<ListUptimeCheckConfigsRequest> _parser = new pb::MessageParser<ListUptimeCheckConfigsRequest>(() => new ListUptimeCheckConfigsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListUptimeCheckConfigsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsRequest(ListUptimeCheckConfigsRequest other) : this() { parent_ = other.parent_; pageSize_ = other.pageSize_; pageToken_ = other.pageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsRequest Clone() { return new ListUptimeCheckConfigsRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// The project whose uptime check configurations are listed. The format is /// /// `projects/[PROJECT_ID]`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 3; private int pageSize_; /// <summary> /// The maximum number of results to return in a single response. The server /// may further constrain the maximum number of results returned in a single /// page. If the page_size is &lt;=0, the server will decide the number of results /// to be returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 4; private string pageToken_ = ""; /// <summary> /// If this field is not empty then it must contain the `nextPageToken` value /// returned by a previous call to this method. Using this field causes the /// method to return more results from the previous method call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListUptimeCheckConfigsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListUptimeCheckConfigsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (PageSize != other.PageSize) return false; if (PageToken != other.PageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (PageSize != 0) { output.WriteRawTag(24); output.WriteInt32(PageSize); } if (PageToken.Length != 0) { output.WriteRawTag(34); output.WriteString(PageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListUptimeCheckConfigsRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.PageSize != 0) { PageSize = other.PageSize; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 24: { PageSize = input.ReadInt32(); break; } case 34: { PageToken = input.ReadString(); break; } } } } } /// <summary> /// The protocol for the `ListUptimeCheckConfigs` response. /// </summary> public sealed partial class ListUptimeCheckConfigsResponse : pb::IMessage<ListUptimeCheckConfigsResponse> { private static readonly pb::MessageParser<ListUptimeCheckConfigsResponse> _parser = new pb::MessageParser<ListUptimeCheckConfigsResponse>(() => new ListUptimeCheckConfigsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListUptimeCheckConfigsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsResponse(ListUptimeCheckConfigsResponse other) : this() { uptimeCheckConfigs_ = other.uptimeCheckConfigs_.Clone(); nextPageToken_ = other.nextPageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckConfigsResponse Clone() { return new ListUptimeCheckConfigsResponse(this); } /// <summary>Field number for the "uptime_check_configs" field.</summary> public const int UptimeCheckConfigsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> _repeated_uptimeCheckConfigs_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> uptimeCheckConfigs_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig>(); /// <summary> /// The returned uptime check configurations. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig> UptimeCheckConfigs { get { return uptimeCheckConfigs_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// This field represents the pagination token to retrieve the next page of /// results. If the value is empty, it means no further results for the /// request. To retrieve the next page of results, the value of the /// next_page_token is passed to the subsequent List method call (in the /// request message's page_token field). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListUptimeCheckConfigsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListUptimeCheckConfigsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!uptimeCheckConfigs_.Equals(other.uptimeCheckConfigs_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= uptimeCheckConfigs_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { uptimeCheckConfigs_.WriteTo(output, _repeated_uptimeCheckConfigs_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += uptimeCheckConfigs_.CalculateSize(_repeated_uptimeCheckConfigs_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListUptimeCheckConfigsResponse other) { if (other == null) { return; } uptimeCheckConfigs_.Add(other.uptimeCheckConfigs_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { uptimeCheckConfigs_.AddEntriesFrom(input, _repeated_uptimeCheckConfigs_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } /// <summary> /// The protocol for the `GetUptimeCheckConfig` request. /// </summary> public sealed partial class GetUptimeCheckConfigRequest : pb::IMessage<GetUptimeCheckConfigRequest> { private static readonly pb::MessageParser<GetUptimeCheckConfigRequest> _parser = new pb::MessageParser<GetUptimeCheckConfigRequest>(() => new GetUptimeCheckConfigRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetUptimeCheckConfigRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUptimeCheckConfigRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUptimeCheckConfigRequest(GetUptimeCheckConfigRequest other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUptimeCheckConfigRequest Clone() { return new GetUptimeCheckConfigRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The uptime check configuration to retrieve. The format is /// /// `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetUptimeCheckConfigRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetUptimeCheckConfigRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetUptimeCheckConfigRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } /// <summary> /// The protocol for the `CreateUptimeCheckConfig` request. /// </summary> public sealed partial class CreateUptimeCheckConfigRequest : pb::IMessage<CreateUptimeCheckConfigRequest> { private static readonly pb::MessageParser<CreateUptimeCheckConfigRequest> _parser = new pb::MessageParser<CreateUptimeCheckConfigRequest>(() => new CreateUptimeCheckConfigRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateUptimeCheckConfigRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUptimeCheckConfigRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUptimeCheckConfigRequest(CreateUptimeCheckConfigRequest other) : this() { parent_ = other.parent_; UptimeCheckConfig = other.uptimeCheckConfig_ != null ? other.UptimeCheckConfig.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUptimeCheckConfigRequest Clone() { return new CreateUptimeCheckConfigRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// The project in which to create the uptime check. The format is: /// /// `projects/[PROJECT_ID]`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "uptime_check_config" field.</summary> public const int UptimeCheckConfigFieldNumber = 2; private global::Google.Cloud.Monitoring.V3.UptimeCheckConfig uptimeCheckConfig_; /// <summary> /// The new uptime check configuration. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig UptimeCheckConfig { get { return uptimeCheckConfig_; } set { uptimeCheckConfig_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateUptimeCheckConfigRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateUptimeCheckConfigRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (!object.Equals(UptimeCheckConfig, other.UptimeCheckConfig)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (uptimeCheckConfig_ != null) hash ^= UptimeCheckConfig.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (uptimeCheckConfig_ != null) { output.WriteRawTag(18); output.WriteMessage(UptimeCheckConfig); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (uptimeCheckConfig_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UptimeCheckConfig); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateUptimeCheckConfigRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.uptimeCheckConfig_ != null) { if (uptimeCheckConfig_ == null) { uptimeCheckConfig_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig(); } UptimeCheckConfig.MergeFrom(other.UptimeCheckConfig); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 18: { if (uptimeCheckConfig_ == null) { uptimeCheckConfig_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig(); } input.ReadMessage(uptimeCheckConfig_); break; } } } } } /// <summary> /// The protocol for the `UpdateUptimeCheckConfig` request. /// </summary> public sealed partial class UpdateUptimeCheckConfigRequest : pb::IMessage<UpdateUptimeCheckConfigRequest> { private static readonly pb::MessageParser<UpdateUptimeCheckConfigRequest> _parser = new pb::MessageParser<UpdateUptimeCheckConfigRequest>(() => new UpdateUptimeCheckConfigRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UpdateUptimeCheckConfigRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateUptimeCheckConfigRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateUptimeCheckConfigRequest(UpdateUptimeCheckConfigRequest other) : this() { UpdateMask = other.updateMask_ != null ? other.UpdateMask.Clone() : null; UptimeCheckConfig = other.uptimeCheckConfig_ != null ? other.UptimeCheckConfig.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateUptimeCheckConfigRequest Clone() { return new UpdateUptimeCheckConfigRequest(this); } /// <summary>Field number for the "update_mask" field.</summary> public const int UpdateMaskFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.FieldMask updateMask_; /// <summary> /// Optional. If present, only the listed fields in the current uptime check /// configuration are updated with values from the new configuration. If this /// field is empty, then the current configuration is completely replaced with /// the new configuration. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.FieldMask UpdateMask { get { return updateMask_; } set { updateMask_ = value; } } /// <summary>Field number for the "uptime_check_config" field.</summary> public const int UptimeCheckConfigFieldNumber = 3; private global::Google.Cloud.Monitoring.V3.UptimeCheckConfig uptimeCheckConfig_; /// <summary> /// Required. If an `"updateMask"` has been specified, this field gives /// the values for the set of fields mentioned in the `"updateMask"`. If an /// `"updateMask"` has not been given, this uptime check configuration replaces /// the current configuration. If a field is mentioned in `"updateMask`" but /// the corresonding field is omitted in this partial uptime check /// configuration, it has the effect of deleting/clearing the field from the /// configuration on the server. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig UptimeCheckConfig { get { return uptimeCheckConfig_; } set { uptimeCheckConfig_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UpdateUptimeCheckConfigRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UpdateUptimeCheckConfigRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(UpdateMask, other.UpdateMask)) return false; if (!object.Equals(UptimeCheckConfig, other.UptimeCheckConfig)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (updateMask_ != null) hash ^= UpdateMask.GetHashCode(); if (uptimeCheckConfig_ != null) hash ^= UptimeCheckConfig.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (updateMask_ != null) { output.WriteRawTag(18); output.WriteMessage(UpdateMask); } if (uptimeCheckConfig_ != null) { output.WriteRawTag(26); output.WriteMessage(UptimeCheckConfig); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (updateMask_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateMask); } if (uptimeCheckConfig_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UptimeCheckConfig); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UpdateUptimeCheckConfigRequest other) { if (other == null) { return; } if (other.updateMask_ != null) { if (updateMask_ == null) { updateMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask(); } UpdateMask.MergeFrom(other.UpdateMask); } if (other.uptimeCheckConfig_ != null) { if (uptimeCheckConfig_ == null) { uptimeCheckConfig_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig(); } UptimeCheckConfig.MergeFrom(other.UptimeCheckConfig); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (updateMask_ == null) { updateMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask(); } input.ReadMessage(updateMask_); break; } case 26: { if (uptimeCheckConfig_ == null) { uptimeCheckConfig_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig(); } input.ReadMessage(uptimeCheckConfig_); break; } } } } } /// <summary> /// The protocol for the `DeleteUptimeCheckConfig` request. /// </summary> public sealed partial class DeleteUptimeCheckConfigRequest : pb::IMessage<DeleteUptimeCheckConfigRequest> { private static readonly pb::MessageParser<DeleteUptimeCheckConfigRequest> _parser = new pb::MessageParser<DeleteUptimeCheckConfigRequest>(() => new DeleteUptimeCheckConfigRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DeleteUptimeCheckConfigRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteUptimeCheckConfigRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteUptimeCheckConfigRequest(DeleteUptimeCheckConfigRequest other) : this() { name_ = other.name_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteUptimeCheckConfigRequest Clone() { return new DeleteUptimeCheckConfigRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The uptime check configuration to delete. The format is /// /// `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DeleteUptimeCheckConfigRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DeleteUptimeCheckConfigRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DeleteUptimeCheckConfigRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } /// <summary> /// The protocol for the `ListUptimeCheckIps` request. /// </summary> public sealed partial class ListUptimeCheckIpsRequest : pb::IMessage<ListUptimeCheckIpsRequest> { private static readonly pb::MessageParser<ListUptimeCheckIpsRequest> _parser = new pb::MessageParser<ListUptimeCheckIpsRequest>(() => new ListUptimeCheckIpsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListUptimeCheckIpsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsRequest(ListUptimeCheckIpsRequest other) : this() { pageSize_ = other.pageSize_; pageToken_ = other.pageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsRequest Clone() { return new ListUptimeCheckIpsRequest(this); } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 2; private int pageSize_; /// <summary> /// The maximum number of results to return in a single response. The server /// may further constrain the maximum number of results returned in a single /// page. If the page_size is &lt;=0, the server will decide the number of results /// to be returned. /// NOTE: this field is not yet implemented /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 3; private string pageToken_ = ""; /// <summary> /// If this field is not empty then it must contain the `nextPageToken` value /// returned by a previous call to this method. Using this field causes the /// method to return more results from the previous method call. /// NOTE: this field is not yet implemented /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListUptimeCheckIpsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListUptimeCheckIpsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (PageSize != other.PageSize) return false; if (PageToken != other.PageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (PageSize != 0) hash ^= PageSize.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (PageSize != 0) { output.WriteRawTag(16); output.WriteInt32(PageSize); } if (PageToken.Length != 0) { output.WriteRawTag(26); output.WriteString(PageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListUptimeCheckIpsRequest other) { if (other == null) { return; } if (other.PageSize != 0) { PageSize = other.PageSize; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 16: { PageSize = input.ReadInt32(); break; } case 26: { PageToken = input.ReadString(); break; } } } } } /// <summary> /// The protocol for the `ListUptimeCheckIps` response. /// </summary> public sealed partial class ListUptimeCheckIpsResponse : pb::IMessage<ListUptimeCheckIpsResponse> { private static readonly pb::MessageParser<ListUptimeCheckIpsResponse> _parser = new pb::MessageParser<ListUptimeCheckIpsResponse>(() => new ListUptimeCheckIpsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListUptimeCheckIpsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.UptimeServiceReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsResponse(ListUptimeCheckIpsResponse other) : this() { uptimeCheckIps_ = other.uptimeCheckIps_.Clone(); nextPageToken_ = other.nextPageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListUptimeCheckIpsResponse Clone() { return new ListUptimeCheckIpsResponse(this); } /// <summary>Field number for the "uptime_check_ips" field.</summary> public const int UptimeCheckIpsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.UptimeCheckIp> _repeated_uptimeCheckIps_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Monitoring.V3.UptimeCheckIp.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckIp> uptimeCheckIps_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckIp>(); /// <summary> /// The returned list of IP addresses (including region and location) that the /// checkers run from. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckIp> UptimeCheckIps { get { return uptimeCheckIps_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// This field represents the pagination token to retrieve the next page of /// results. If the value is empty, it means no further results for the /// request. To retrieve the next page of results, the value of the /// next_page_token is passed to the subsequent List method call (in the /// request message's page_token field). /// NOTE: this field is not yet implemented /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListUptimeCheckIpsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListUptimeCheckIpsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!uptimeCheckIps_.Equals(other.uptimeCheckIps_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= uptimeCheckIps_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { uptimeCheckIps_.WriteTo(output, _repeated_uptimeCheckIps_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += uptimeCheckIps_.CalculateSize(_repeated_uptimeCheckIps_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListUptimeCheckIpsResponse other) { if (other == null) { return; } uptimeCheckIps_.Add(other.uptimeCheckIps_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { uptimeCheckIps_.AddEntriesFrom(input, _repeated_uptimeCheckIps_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using ClosedXML.Excel; using ClosedXML.Excel.Drawings; using ClosedXML.Tests.Utils; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ClosedXML.Tests.Excel { // Tests in this fixture test only the successful loading of existing Excel files, // i.e. we test that ClosedXML doesn't choke on a given input file // These tests DO NOT test that ClosedXML successfully recognises all the Excel parts or that it can successfully save those parts again. [TestFixture] public class LoadingTests { private static IEnumerable<string> TryToLoad => TestHelper.ListResourceFiles(s => s.Contains(".TryToLoad.") && !s.Contains(".LO.")); [TestCaseSource(nameof(TryToLoad))] public void CanSuccessfullyLoadFiles(string file) { TestHelper.LoadFile(file); } [TestCaseSource(nameof(LOFiles))] public void CanSuccessfullyLoadLOFiles(string file) { TestHelper.LoadFile(file); } private static IEnumerable<string> LOFiles { get { // TODO: unpark all files var parkedForLater = new[] { "TryToLoad.LO.xlsx.formats.xlsx", "TryToLoad.LO.xlsx.pivot_table.shared-group-field.xlsx", "TryToLoad.LO.xlsx.pivot_table.shared-nested-dategroup.xlsx", "TryToLoad.LO.xlsx.pivottable_bool_field_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_date_field_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_double_field_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_duplicated_member_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_rowcolpage_field_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_string_field_filter.xlsx", "TryToLoad.LO.xlsx.pivottable_tabular_mode.xlsx", "TryToLoad.LO.xlsx.pivot_table_first_header_row.xlsx", "TryToLoad.LO.xlsx.tdf100709.xlsx", "TryToLoad.LO.xlsx.tdf89139_pivot_table.xlsx", "TryToLoad.LO.xlsx.universal-content-strict.xlsx", "TryToLoad.LO.xlsx.universal-content.xlsx", "TryToLoad.LO.xlsx.xf_default_values.xlsx", "TryToLoad.LO.xlsm.pass.CVE-2016-0122-1.xlsm", "TryToLoad.LO.xlsm.tdf111974.xlsm", "TryToLoad.LO.xlsm.vba-user-function.xlsm", }; return TestHelper.ListResourceFiles(s => s.Contains(".LO.") && !parkedForLater.Any(i => s.Contains(i))); } } [Test] public void CanLoadAndManipulateFileWithEmptyTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\EmptyTable.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); var table = ws.Tables.First(); table.DataRange.InsertRowsBelow(5); } } [Test] public void CanLoadDate1904SystemCorrectly() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\Date1904System.xlsx"))) using (var ms = new MemoryStream()) { using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); var c = ws.Cell("A2"); Assert.AreEqual(XLDataType.DateTime, c.DataType); Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime()); wb.SaveAs(ms); } ms.Seek(0, SeekOrigin.Begin); using (var wb = new XLWorkbook(ms)) { var ws = wb.Worksheets.First(); var c = ws.Cell("A2"); Assert.AreEqual(XLDataType.DateTime, c.DataType); Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime()); wb.SaveAs(ms); } } } [Test] public void CanLoadAndSaveFileWithMismatchingSheetIdAndRelId() { // This file's workbook.xml contains: // <x:sheet name="Data" sheetId="13" r:id="rId1" /> // and the mismatch between the sheetId and r:id can create problems. using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\FileWithMismatchSheetIdAndRelId.xlsx"))) using (var wb = new XLWorkbook(stream)) { using (var ms = new MemoryStream()) { wb.SaveAs(ms, true); } } } [Test] public void CanLoadBasicPivotTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("PivotTable1"); var pt = ws.PivotTable("PivotTable1"); Assert.AreEqual("PivotTable1", pt.Name); Assert.AreEqual(1, pt.RowLabels.Count()); Assert.AreEqual("Name", pt.RowLabels.Single().SourceName); Assert.AreEqual(1, pt.ColumnLabels.Count()); Assert.AreEqual("Month", pt.ColumnLabels.Single().SourceName); var pv = pt.Values.Single(); Assert.AreEqual("Sum of NumberOfOrders", pv.CustomName); Assert.AreEqual("NumberOfOrders", pv.SourceName); } } [Test] public void CanLoadOrderedPivotTable() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("OrderedPivotTable"); var pt = ws.PivotTable("OrderedPivotTable"); Assert.AreEqual(XLPivotSortType.Ascending, pt.RowLabels.Single().SortType); Assert.AreEqual(XLPivotSortType.Descending, pt.ColumnLabels.Single().SortType); } } [Test] public void CanLoadPivotTableSubtotals() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\LoadPivotTables.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet("PivotTableSubtotals"); var pt = ws.PivotTable("PivotTableSubtotals"); var subtotals = pt.RowLabels.Get("Group").Subtotals.ToArray(); Assert.AreEqual(3, subtotals.Length); Assert.AreEqual(XLSubtotalFunction.Average, subtotals[0]); Assert.AreEqual(XLSubtotalFunction.Count, subtotals[1]); Assert.AreEqual(XLSubtotalFunction.Sum, subtotals[2]); } } /// <summary> /// For non-English locales, the default style ("Normal" in English) can be /// another piece of text (e.g. ??????? in Russian). /// This test ensures that the default style is correctly detected and /// no style conflicts occur on save. /// </summary> [Test] public void CanSaveFileWithDefaultStyleNameNotInEnglish() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\FileWithDefaultStyleNameNotInEnglish.xlsx"))) using (var wb = new XLWorkbook(stream)) { using (var ms = new MemoryStream()) { wb.SaveAs(ms, true); } } } /// <summary> /// As per https://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.cellvalues(v=office.15).aspx /// the 'Date' DataType is available only in files saved with Microsoft Office /// In other files, the data type will be saved as numeric /// ClosedXML then deduces the data type by inspecting the number format string /// </summary> [Test] public void CanLoadLibreOfficeFileWithDates() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\LibreOfficeFileWithDates.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); foreach (var cell in ws.CellsUsed()) { Assert.AreEqual(XLDataType.DateTime, cell.DataType); } } } [Test] public void CanLoadFileWithImagesWithCorrectAnchorTypes() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(2, ws.Pictures.Count); Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Pictures.First().Placement); Assert.AreEqual(XLPicturePlacement.Move, ws.Pictures.Skip(1).First().Placement); var ws2 = wb.Worksheets.Skip(1).First(); Assert.AreEqual(1, ws2.Pictures.Count); Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws2.Pictures.First().Placement); } } [Test] public void CanLoadFileWithImagesWithCorrectImageType() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageFormats.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(1, ws.Pictures.Count); Assert.AreEqual(XLPictureFormat.Jpeg, ws.Pictures.First().Format); var ws2 = wb.Worksheets.Skip(1).First(); Assert.AreEqual(1, ws2.Pictures.Count); Assert.AreEqual(XLPictureFormat.Png, ws2.Pictures.First().Format); } } [Test] public void CanLoadAndDeduceAnchorsFromExcelGeneratedFile() { // This file was produced by Excel. It contains 3 images, but the latter 2 were copied from the first. // There is actually only 1 embedded image if you inspect the file's internals. // Additionally, Excel saves all image anchors as TwoCellAnchor, but uses the EditAs attribute to distinguish the types using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\ExcelProducedWorkbookWithImages.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); Assert.AreEqual(3, ws.Pictures.Count); Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws.Picture("Picture 1").Placement); Assert.AreEqual(XLPicturePlacement.Move, ws.Picture("Picture 2").Placement); Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Picture("Picture 3").Placement); using (var ms = new MemoryStream()) wb.SaveAs(ms, true); } } [Test] public void CanLoadFromTemplate() { using (var tf1 = new TemporaryFile()) using (var tf2 = new TemporaryFile()) { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\AllShapes.xlsx"))) using (var wb = new XLWorkbook(stream)) { // Save as temporary file wb.SaveAs(tf1.Path); } var workbook = XLWorkbook.OpenFromTemplate(tf1.Path); Assert.True(workbook.Worksheets.Any()); Assert.Throws<InvalidOperationException>(() => workbook.Save()); workbook.SaveAs(tf2.Path); } } /// <summary> /// Excel escapes symbol ' in worksheet title so we have to process this correctly. /// </summary> [Test] public void CanOpenWorksheetWithEscapedApostrophe() { string title = ""; TestDelegate openWorkbook = () => { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\EscapedApostrophe.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheets.First(); title = ws.Name; } }; Assert.DoesNotThrow(openWorkbook); Assert.AreEqual("L'E", title); } [Test] public void CanRoundTripSheetProtectionForObjects() { using (var book = new XLWorkbook()) { var sheet = book.AddWorksheet("TestSheet"); sheet.Protect() .AllowElement(XLSheetProtectionElements.EditObjects | XLSheetProtectionElements.EditScenarios); Assert.AreEqual(XLSheetProtectionElements.SelectEverything | XLSheetProtectionElements.EditObjects | XLSheetProtectionElements.EditScenarios, sheet.Protection.AllowedElements); using (var xlStream = new MemoryStream()) { book.SaveAs(xlStream); using (var persistedBook = new XLWorkbook(xlStream)) { var persistedSheet = persistedBook.Worksheets.Worksheet(1); Assert.AreEqual(sheet.Protection.AllowedElements, persistedSheet.Protection.AllowedElements); } } } } [Test] [TestCase("A1*10", 1230)] [TestCase("A1/10", 12.3)] [TestCase("A1&\" cells\"", "123 cells")] [TestCase("A1&\"000\"", "123000")] [TestCase("ISNUMBER(A1)", true)] [TestCase("ISBLANK(A1)", false)] [TestCase("DATE(2018,1,28)", 43128)] public void LoadFormulaCachedValue(string formula, object expectedCachedValue) { using (var ms = new MemoryStream()) { using (XLWorkbook book1 = new XLWorkbook()) { var sheet = book1.AddWorksheet("sheet1"); sheet.Cell("A1").Value = 123; sheet.Cell("A2").FormulaA1 = formula; var options = new SaveOptions { EvaluateFormulasBeforeSaving = true }; book1.SaveAs(ms, options); } ms.Position = 0; using (XLWorkbook book2 = new XLWorkbook(ms)) { var ws = book2.Worksheet(1); Assert.IsFalse(ws.Cell("A2").NeedsRecalculation); Assert.AreEqual(expectedCachedValue, ws.Cell("A2").CachedValue); } } } [Test] public void LoadingOptions() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\ExternalLinks\WorkbookWithExternalLink.xlsx"))) { Assert.DoesNotThrow(() => new XLWorkbook(stream, new LoadOptions { RecalculateAllFormulas = false })); Assert.Throws<ArgumentOutOfRangeException>(() => new XLWorkbook(stream, new LoadOptions { RecalculateAllFormulas = true })); Assert.AreEqual(XLEventTracking.Disabled, new XLWorkbook(stream, new LoadOptions { EventTracking = XLEventTracking.Disabled }).EventTracking); Assert.AreEqual(XLEventTracking.Enabled, new XLWorkbook(stream, new LoadOptions { EventTracking = XLEventTracking.Enabled }).EventTracking); } } [Test] public void CanLoadWorksheetStyle() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\BaseColumnWidth.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); Assert.AreEqual(8, ws.Style.Font.FontSize); Assert.AreEqual("Arial", ws.Style.Font.FontName); Assert.AreEqual(8, ws.Cell("A1").Style.Font.FontSize); Assert.AreEqual("Arial", ws.Cell("A1").Style.Font.FontName); } } [Test] public void CanCorrectLoadWorkbookCellWithStringDataType() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\CellWithStringDataType.xlsx"))) using (var wb = new XLWorkbook(stream)) { var cellToCheck = wb.Worksheet(1).Cell("B2"); Assert.AreEqual(XLDataType.Text, cellToCheck.DataType); Assert.AreEqual("String with String Data type", cellToCheck.Value); } } [Test] public void CanLoadFileWithInvalidSelectedRanges() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\SelectedRanges\InvalidSelectedRange.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); Assert.AreEqual(2, ws.SelectedRanges.Count); Assert.AreEqual("B2:B2", ws.SelectedRanges.First().RangeAddress.ToString()); Assert.AreEqual("B2:C2", ws.SelectedRanges.Last().RangeAddress.ToString()); } } [Test] public void CanLoadCellsWithoutReferencesCorrectly() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\LO\xlsx\row-index-1-based.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); Assert.AreEqual("Page 1", ws.Name); var expected = new Dictionary<string, string>() { ["A1"] = "Action Plan.Name", ["B1"] = "Action Plan.Description", ["A2"] = "Jerry", ["B2"] = "This is a longer Text.\nSecond line.\nThird line.", ["A3"] = "", ["B3"] = "" }; foreach (var pair in expected) Assert.AreEqual(pair.Value, ws.Cell(pair.Key).GetString(), pair.Key); } } [Test] public void CorrectlyLoadMergedCellsBorder() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\StyleReferenceFiles\MergedCellsBorder\inputfile.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); var c = ws.Cell("B2"); Assert.AreEqual(XLColorType.Theme, c.Style.Border.TopBorderColor.ColorType); Assert.AreEqual(XLThemeColor.Accent1, c.Style.Border.TopBorderColor.ThemeColor); Assert.AreEqual(0.39994506668294322d, c.Style.Border.TopBorderColor.ThemeTint, XLHelper.Epsilon); } } [Test] public void CorrectlyLoadDefaultRowAndColumnStyles() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\StyleReferenceFiles\RowAndColumnStyles\inputfile.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); Assert.AreEqual(8, ws.Row(1).Style.Font.FontSize); Assert.AreEqual(8, ws.Row(2).Style.Font.FontSize); Assert.AreEqual(8, ws.Column("A").Style.Font.FontSize); } } [Test] public void EmptyNumberFormatIdTreatedAsGeneral() { using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"TryToLoad\EmptyNumberFormatId.xlsx"))) using (var wb = new XLWorkbook(stream)) { var ws = wb.Worksheet(1); Assert.AreEqual(XLPredefinedFormat.General, ws.Cell("A2").Style.NumberFormat.NumberFormatId); } } [Test] public void CanLoadProperties() { const string author = "TestAuthor"; const string title = "TestTitle"; const string subject = "TestSubject"; const string category = "TestCategory"; const string keywords = "TestKeywords"; const string comments = "TestComments"; const string status = "TestStatus"; var created = new DateTime(2019, 10, 19, 20, 42, 30); var modified = new DateTime(2020, 11, 20, 09, 51, 20); const string lastModifiedBy = "TestLastModifiedBy"; const string company = "TestCompany"; const string manager = "TestManager"; using (var stream = new MemoryStream()) { using (var wb = new XLWorkbook()) { var sheet = wb.AddWorksheet("sheet1"); wb.Properties.Author = author; wb.Properties.Title = title; wb.Properties.Subject = subject; wb.Properties.Category = category; wb.Properties.Keywords = keywords; wb.Properties.Comments = comments; wb.Properties.Status = status; wb.Properties.Created = created; wb.Properties.Modified = modified; wb.Properties.LastModifiedBy = lastModifiedBy; wb.Properties.Company = company; wb.Properties.Manager = manager; wb.SaveAs(stream, true); } stream.Position = 0; using (var wb = new XLWorkbook(stream)) { Assert.AreEqual(author, wb.Properties.Author); Assert.AreEqual(title, wb.Properties.Title); Assert.AreEqual(subject, wb.Properties.Subject); Assert.AreEqual(category, wb.Properties.Category); Assert.AreEqual(keywords, wb.Properties.Keywords); Assert.AreEqual(comments, wb.Properties.Comments); Assert.AreEqual(status, wb.Properties.Status); Assert.AreEqual(created, wb.Properties.Created); Assert.AreEqual(modified, wb.Properties.Modified); Assert.AreEqual(lastModifiedBy, wb.Properties.LastModifiedBy); Assert.AreEqual(company, wb.Properties.Company); Assert.AreEqual(manager, wb.Properties.Manager); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Tests { public static class BufferTests { [Fact] public static void BlockCopy() { byte[] src = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d }; byte[] dst = new byte[] { 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f }; Buffer.BlockCopy(src, 0, dst, 1, 4); Assert.Equal(new byte[] { 0x6f, 0x1a, 0x2b, 0x3c, 0x4d, 0x6f }, dst); } [Fact] public static void BlockCopy_SameDestinationAndSourceArray() { byte[] dst = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e }; Buffer.BlockCopy(dst, 1, dst, 2, 2); Assert.Equal(new byte[] { 0x1a, 0x2b, 0x2b, 0x3c, 0x5e }, dst); } [Fact] public static void BlockCopy_Invalid() { Assert.Throws<ArgumentNullException>("src", () => Buffer.BlockCopy(null, 0, new int[3], 0, 0)); // Src is null Assert.Throws<ArgumentNullException>("dst", () => Buffer.BlockCopy(new string[3], 0, null, 0, 0)); // Dst is null Assert.Throws<ArgumentOutOfRangeException>("srcOffset", () => Buffer.BlockCopy(new byte[3], -1, new byte[3], 0, 0)); // SrcOffset < 0 Assert.Throws<ArgumentOutOfRangeException>("dstOffset", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], -1, 0)); // DstOffset < 0 Assert.Throws<ArgumentOutOfRangeException>("count", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 0, -1)); // Count < 0 Assert.Throws<ArgumentException>("src", () => Buffer.BlockCopy(new string[3], 0, new byte[3], 0, 0)); // Src is not a byte array Assert.Throws<ArgumentException>("dest", () => Buffer.BlockCopy(new byte[3], 0, new string[3], 0, 0)); // Dst is not a byte array Assert.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 3, new byte[3], 0, 1)); // SrcOffset + count >= src.length Assert.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 4, new byte[3], 0, 0)); // SrcOffset >= src.Length Assert.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 3, 1)); // DstOffset + count >= dst.Length Assert.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 4, 0)); // DstOffset >= dst.Length } public static unsafe IEnumerable<object[]> ByteLength_TestData() { return new object[][] { new object[] { typeof(byte), sizeof(byte) }, new object[] { typeof(sbyte), sizeof(sbyte) }, new object[] { typeof(short), sizeof(short) }, new object[] { typeof(ushort), sizeof(ushort) }, new object[] { typeof(int), sizeof(int) }, new object[] { typeof(uint), sizeof(uint) }, new object[] { typeof(long), sizeof(long) }, new object[] { typeof(ulong), sizeof(ulong) }, new object[] { typeof(IntPtr), sizeof(IntPtr) }, new object[] { typeof(UIntPtr), sizeof(UIntPtr) }, new object[] { typeof(double), sizeof(double) }, new object[] { typeof(float), sizeof(float) }, new object[] { typeof(bool), sizeof(bool) }, new object[] { typeof(char), sizeof(char) } }; } [Theory] [MemberData(nameof(ByteLength_TestData))] public static void ByteLength(Type type, int size) { const int Length = 25; Array array = Array.CreateInstance(type, Length); Assert.Equal(Length * size, Buffer.ByteLength(array)); } [Fact] public static void ByteLength_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Buffer.ByteLength(null)); // Array is null Assert.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(DateTime), 25))); // Array is not a primitive Assert.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(decimal), 25))); // Array is not a primitive Assert.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(string), 25))); // Array is not a primitive } [Theory] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x67)] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 7, 0x89)] public static void GetByte(Array array, int index, int expected) { Assert.Equal(expected, Buffer.GetByte(array, index)); } [Fact] public static void GetByte_Invalid() { var array = new uint[] { 0x01234567, 0x89abcdef }; Assert.Throws<ArgumentNullException>("array", () => Buffer.GetByte(null, 0)); // Array is null Assert.Throws<ArgumentException>("array", () => Buffer.GetByte(new object[10], 0)); // Array is not a primitive array Assert.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, 8)); // Index >= array.Length } [Theory] [InlineData(25000, 0, 30000, 0, 25000)] [InlineData(25000, 0, 30000, 5000, 25000)] [InlineData(25000, 5000, 30000, 6000, 20000)] [InlineData(25000, 5000, 30000, 6000, 4000)] [InlineData(100, 0, 100, 0, 0)] [InlineData(100, 0, 100, 0, 1)] [InlineData(100, 0, 100, 0, 2)] [InlineData(100, 0, 100, 0, 3)] [InlineData(100, 0, 100, 0, 4)] [InlineData(100, 0, 100, 0, 5)] [InlineData(100, 0, 100, 0, 6)] [InlineData(100, 0, 100, 0, 7)] [InlineData(100, 0, 100, 0, 8)] [InlineData(100, 0, 100, 0, 9)] [InlineData(100, 0, 100, 0, 10)] [InlineData(100, 0, 100, 0, 11)] [InlineData(100, 0, 100, 0, 12)] [InlineData(100, 0, 100, 0, 13)] [InlineData(100, 0, 100, 0, 14)] [InlineData(100, 0, 100, 0, 15)] [InlineData(100, 0, 100, 0, 16)] [InlineData(100, 0, 100, 0, 17)] public static unsafe void MemoryCopy(int sourceLength, int sourceIndexOffset, int destinationLength, int destinationIndexOffset, long sourceBytesToCopy) { var sourceArray = new byte[sourceLength]; for (int i = 0; i < sourceArray.Length; i++) { sourceArray[i] = unchecked((byte)i); } var destinationArray = new byte[destinationLength]; for (int i = 0; i < destinationArray.Length; i++) { destinationArray[i] = unchecked((byte)(i * 2)); } fixed (byte* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase + sourceIndexOffset, destinationBase + destinationIndexOffset, destinationLength, sourceBytesToCopy); } for (int i = 0; i < destinationIndexOffset; i++) { Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]); } for (int i = 0; i < sourceBytesToCopy; i++) { Assert.Equal(sourceArray[i + sourceIndexOffset], destinationArray[i + destinationIndexOffset]); } for (long i = destinationIndexOffset + sourceBytesToCopy; i < destinationArray.Length; i++) { Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]); } } [Theory] [InlineData(200, 50, 100)] [InlineData(200, 5, 15)] public static unsafe void MemoryCopy_OverlappingBuffers(int sourceLength, int destinationIndexOffset, int sourceBytesToCopy) { var array = new int[sourceLength]; for (int i = 0; i < array.Length; i++) { array[i] = i; } fixed (int* arrayBase = array) { Buffer.MemoryCopy(arrayBase, arrayBase + destinationIndexOffset, sourceLength * 4, sourceBytesToCopy * 4); } for (int i = 0; i < sourceBytesToCopy; i++) { Assert.Equal(i, array[i + destinationIndexOffset]); } } [Fact] public static unsafe void MemoryCopy_Invalid() { var sourceArray = new int[5000]; var destinationArray = new int[1000]; Assert.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () => { fixed (int* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase, destinationBase, 5000 * 4, 20000 * 4); // Source bytes to copy > destination size in bytes } }); Assert.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () => { fixed (int* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase, destinationBase, (ulong)5000 * 4, (ulong)20000 * 4); // Source bytes to copy > destination size in bytes } }); } [Theory] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x42, new uint[] { 0x01234542, 0x89abcdef })] [InlineData(new uint[] { 0x01234542, 0x89abcdef }, 7, 0xa2, new uint[] { 0x01234542, 0xa2abcdef })] public static void SetByte(Array array, int index, byte value, Array expected) { Buffer.SetByte(array, index, value); Assert.Equal(expected, array); } [Fact] public static void SetByte_Invalid() { var array = new uint[] { 0x01234567, 0x89abcdef }; Assert.Throws<ArgumentNullException>("array", () => Buffer.SetByte(null, 0, 0xff)); // Array is null Assert.Throws<ArgumentException>("array", () => Buffer.SetByte(new object[10], 0, 0xff)); // Array is not a primitive array Assert.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, -1, 0xff)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, 8, 0xff)); // Index > array.Length } } }
// // WebHeaderCollectionTest.cs - NUnit Test Cases for System.Net.WebHeaderCollection // // Authors: // Lawrence Pit ([email protected]) // Martin Willemoes Hansen ([email protected]) // // (C) 2003 Martin Willemoes Hansen // using NUnit.Framework; using System; using System.Net; using System.Collections; namespace MonoTests.System.Net { [TestFixture] public class WebHeaderCollectionTest { WebHeaderCollection col; [SetUp] public void GetReady () { col = new WebHeaderCollection (); col.Add ("Name1: Value1"); col.Add ("Name2: Value2"); } [Test] public void Add () { try { col.Add (null); Assertion.Fail ("#1"); } catch (ArgumentNullException) {} try { col.Add (""); Assertion.Fail ("#2"); } catch (ArgumentException) {} try { col.Add (" "); Assertion.Fail ("#3"); } catch (ArgumentException) {} try { col.Add (":"); Assertion.Fail ("#4"); } catch (ArgumentException) {} try { col.Add (" : "); Assertion.Fail ("#5"); } catch (ArgumentException) {} try { col.Add ("XHost: foo"); } catch (ArgumentException) { Assertion.Fail ("#7"); } // invalid values try { col.Add ("XHost" + ((char) 0xa9) + ": foo"); Assertion.Fail ("#8"); } catch (ArgumentException) {} try { col.Add ("XHost: foo" + (char) 0xa9); } catch (ArgumentException) { Assertion.Fail ("#9"); } try { col.Add ("XHost: foo" + (char) 0x7f); Assertion.Fail ("#10"); } catch (ArgumentException) { } try { col.Add ("XHost", null); } catch (ArgumentException) { Assertion.Fail ("#11"); } try { col.Add ("XHost:"); } catch (ArgumentException) { Assertion.Fail ("#12"); } // restricted /* // this can only be tested in namespace System.Net try { WebHeaderCollection col2 = new WebHeaderCollection (true); col2.Add ("Host: foo"); Assertion.Fail ("#13: should fail according to spec"); } catch (ArgumentException) {} */ } [Test] public void GetValues () { WebHeaderCollection w = new WebHeaderCollection (); w.Add ("Hello", "H1"); w.Add ("Hello", "H2"); w.Add ("Hello", "H3,H4"); string [] sa = w.GetValues ("Hello"); Assertion.AssertEquals ("#1", 3, sa.Length); Assertion.AssertEquals ("#2", "H1,H2,H3,H4", w.Get ("Hello")); w = new WebHeaderCollection (); w.Add ("Accept", "H1"); w.Add ("Accept", "H2"); w.Add ("Accept", "H3,H4"); Assertion.AssertEquals ("#3a", 3, w.GetValues (0).Length); Assertion.AssertEquals ("#3b", 4, w.GetValues ("Accept").Length); Assertion.AssertEquals ("#4", "H1,H2,H3,H4", w.Get ("Accept")); w = new WebHeaderCollection (); w.Add ("Allow", "H1"); w.Add ("Allow", "H2"); w.Add ("Allow", "H3,H4"); sa = w.GetValues ("Allow"); Assertion.AssertEquals ("#5", 4, sa.Length); Assertion.AssertEquals ("#6", "H1,H2,H3,H4", w.Get ("Allow")); w = new WebHeaderCollection (); w.Add ("AUTHorization", "H1, H2, H3"); sa = w.GetValues ("authorization"); Assertion.AssertEquals ("#9", 3, sa.Length); w = new WebHeaderCollection (); w.Add ("proxy-authenticate", "H1, H2, H3"); sa = w.GetValues ("Proxy-Authenticate"); Assertion.AssertEquals ("#9", 3, sa.Length); w = new WebHeaderCollection (); w.Add ("expect", "H1,\tH2, H3 "); sa = w.GetValues ("EXPECT"); Assertion.AssertEquals ("#10", 3, sa.Length); Assertion.AssertEquals ("#11", "H2", sa [1]); Assertion.AssertEquals ("#12", "H3", sa [2]); try { w.GetValues (null); Assertion.Fail ("#13"); } catch (ArgumentNullException) {} Assertion.AssertEquals ("#14", null, w.GetValues ("")); Assertion.AssertEquals ("#15", null, w.GetValues ("NotExistent")); } [Test] public void Indexers () { Assertion.AssertEquals ("#1", "Value1", col [0]); Assertion.AssertEquals ("#2", "Value1", col ["Name1"]); Assertion.AssertEquals ("#3", "Value1", col ["NAME1"]); } [Test] public void Remove () { col.Remove ("Name1"); col.Remove ("NameNotExist"); Assertion.AssertEquals ("#1", 1, col.Count); /* // this can only be tested in namespace System.Net try { WebHeaderCollection col2 = new WebHeaderCollection (true); col2.Add ("Host", "foo"); col2.Remove ("Host"); Assertion.Fail ("#2: should fail according to spec"); } catch (ArgumentException) {} */ } [Test] public void Set () { col.Add ("Name1", "Value1b"); col.Set ("Name1", "\t X \t"); Assertion.AssertEquals ("#1", "X", col.Get ("Name1")); } [Test] public void IsRestricted () { Assertion.Assert ("#1", !WebHeaderCollection.IsRestricted ("Xhost")); Assertion.Assert ("#2", WebHeaderCollection.IsRestricted ("Host")); Assertion.Assert ("#3", WebHeaderCollection.IsRestricted ("HOST")); Assertion.Assert ("#4", WebHeaderCollection.IsRestricted ("Transfer-Encoding")); Assertion.Assert ("#5", WebHeaderCollection.IsRestricted ("user-agent")); Assertion.Assert ("#6", WebHeaderCollection.IsRestricted ("accept")); Assertion.Assert ("#7", !WebHeaderCollection.IsRestricted ("accept-charset")); } [Test] public void ToStringTest () { col.Add ("Name1", "Value1b"); col.Add ("Name3", "Value3a\r\n Value3b"); col.Add ("Name4", " Value4 "); Assertion.AssertEquals ("#1", "Name1: Value1,Value1b\r\nName2: Value2\r\nName3: Value3a\r\n Value3b\r\nName4: Value4\r\n\r\n", col.ToString ()); } } }
/// Credit BinaryX, SimonDarksideJ /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602 /// Updated by SimonDarksideJ - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect. /// Updated by SimonDarksideJ - major refactoring on updating current position and scroll management using UnityEngine.EventSystems; namespace UnityEngine.UI.Extensions { [RequireComponent(typeof(ScrollRect))] [AddComponentMenu("Layout/Extensions/Vertical Scroll Snap")] public class VerticalScrollSnap : ScrollSnapBase, IEndDragHandler { void Start() { _isVertical = true; _childAnchorPoint = new Vector2(0.5f,0); _currentPage = StartingScreen; panelDimensions = gameObject.GetComponent<RectTransform>().rect; UpdateLayout(); } void Update() { if (!_lerp && _scroll_rect.velocity == Vector2.zero) { if (!_settled && !_pointerDown) { if (!IsRectSettledOnaPage(_screensContainer.localPosition)) { ScrollToClosestElement(); } } return; } else if (_lerp) { _screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime); if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.1f) { _screensContainer.localPosition = _lerp_target; _lerp = false; EndScreenChange(); } } CurrentPage = GetPageforPosition(_screensContainer.localPosition); //If the container is moving check if it needs to settle on a page if (!_pointerDown) { if (_scroll_rect.velocity.y > 0.01 || _scroll_rect.velocity.y < -0.01) { // if the pointer is released and is moving slower than the threshold, then just land on a page if (IsRectMovingSlowerThanThreshold(0)) { ScrollToClosestElement(); } } } } private bool IsRectMovingSlowerThanThreshold(float startingSpeed) { return (_scroll_rect.velocity.y > startingSpeed && _scroll_rect.velocity.y < SwipeVelocityThreshold) || (_scroll_rect.velocity.y < startingSpeed && _scroll_rect.velocity.y > -SwipeVelocityThreshold); } public void DistributePages() { _screens = _screensContainer.childCount; _scroll_rect.verticalNormalizedPosition = 0; float _offset = 0; float _dimension = 0; Rect panelDimensions = gameObject.GetComponent<RectTransform>().rect; float currentYPosition = 0; var pageStepValue = _childSize = (int)panelDimensions.height * ((PageStep == 0) ? 3 : PageStep); for (int i = 0; i < _screensContainer.transform.childCount; i++) { RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>(); currentYPosition = _offset + i * pageStepValue; child.sizeDelta = new Vector2(panelDimensions.width, panelDimensions.height); child.anchoredPosition = new Vector2(0f, currentYPosition); child.anchorMin = child.anchorMax = child.pivot = _childAnchorPoint; } _dimension = currentYPosition + _offset * -1; _screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(0f, _dimension); } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> public void AddChild(GameObject GO) { AddChild(GO, false); } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> /// <param name="WorldPositionStays">Should the world position be updated to it's parent transform?</param> public void AddChild(GameObject GO, bool WorldPositionStays) { _scroll_rect.verticalNormalizedPosition = 0; GO.transform.SetParent(_screensContainer, WorldPositionStays); InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); SetScrollContainerPosition(); } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index">Index element of child to remove</param> /// <param name="ChildRemoved">Resulting removed GO</param> public void RemoveChild(int index, out GameObject ChildRemoved) { RemoveChild(index, false, out ChildRemoved); } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index">Index element of child to remove</param> /// <param name="WorldPositionStays">If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before</param> /// <param name="ChildRemoved">Resulting removed GO</param> public void RemoveChild(int index, bool WorldPositionStays, out GameObject ChildRemoved) { ChildRemoved = null; if (index < 0 || index > _screensContainer.childCount) { return; } _scroll_rect.verticalNormalizedPosition = 0; Transform child = _screensContainer.transform.GetChild(index); child.SetParent(null, WorldPositionStays); ChildRemoved = child.gameObject; InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); if (_currentPage > _screens - 1) { CurrentPage = _screens - 1; } SetScrollContainerPosition(); } /// <summary> /// Remove all children from this ScrollSnap /// </summary> /// <param name="ChildrenRemoved">Array of child GO's removed</param> public void RemoveAllChildren(out GameObject[] ChildrenRemoved) { RemoveAllChildren(false, out ChildrenRemoved); } /// <summary> /// Remove all children from this ScrollSnap /// </summary> /// <param name="WorldPositionStays">If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before</param> /// <param name="ChildrenRemoved">Array of child GO's removed</param> public void RemoveAllChildren(bool WorldPositionStays, out GameObject[] ChildrenRemoved) { var _screenCount = _screensContainer.childCount; ChildrenRemoved = new GameObject[_screenCount]; for (int i = _screenCount - 1; i >= 0; i--) { ChildrenRemoved[i] = _screensContainer.GetChild(i).gameObject; ChildrenRemoved[i].transform.SetParent(null, WorldPositionStays); } _scroll_rect.verticalNormalizedPosition = 0; CurrentPage = 0; InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); } private void SetScrollContainerPosition() { _scrollStartPosition = _screensContainer.localPosition.y; _scroll_rect.verticalNormalizedPosition = (float)(_currentPage) / (_screens - 1); OnCurrentScreenChange(_currentPage); } /// <summary> /// used for changing / updating between screen resolutions /// </summary> public void UpdateLayout() { _lerp = false; DistributePages(); if (MaskArea) UpdateVisible(); SetScrollContainerPosition(); OnCurrentScreenChange(_currentPage); } private void OnRectTransformDimensionsChange() { if (_childAnchorPoint != Vector2.zero) { UpdateLayout(); } } private void OnEnable() { InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); if (JumpOnEnable || !RestartOnEnable) SetScrollContainerPosition(); if(RestartOnEnable) GoToScreen(StartingScreen); } #region Interfaces /// <summary> /// Release screen to swipe /// </summary> /// <param name="eventData"></param> public void OnEndDrag(PointerEventData eventData) { _pointerDown = false; if (_scroll_rect.vertical) { var distance = Vector3.Distance(_startPosition, _screensContainer.localPosition); if (UseFastSwipe && distance < panelDimensions.height + FastSwipeThreshold && distance >=1f) { _scroll_rect.velocity = Vector3.zero; if (_startPosition.y - _screensContainer.localPosition.y > 0) { NextScreen(); } else { PreviousScreen(); } } } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NStorage.Utility { using System.IO; /** * This class provides common functionality for the * various LZW implementations in the different file * formats. * It's currently used by HDGF and HMEF. * * Two good resources on LZW are: * http://en.wikipedia.org/wiki/LZW * http://marknelson.us/1989/10/01/lzw-data-compression/ */ public abstract class LZWDecompresser { /** * Does the mask bit mean it's compressed or uncompressed? */ private bool maskMeansCompressed; /** * How much to append to the code length in the stream * to Get the real code length? Normally 2 or 3 */ private int codeLengthIncrease; /** * Does the 12 bits of the position Get stored in * Little Endian or Big Endian form? * This controls whether a pos+length of 0x12 0x34 * becomes a position of 0x123 or 0x312 */ private bool positionIsBigEndian; protected LZWDecompresser(bool maskMeansCompressed, int codeLengthIncrease, bool positionIsBigEndian) { this.maskMeansCompressed = maskMeansCompressed; this.codeLengthIncrease = codeLengthIncrease; this.positionIsBigEndian = positionIsBigEndian; } /** * Populates the dictionary, and returns where in it * to begin writing new codes. * Generally, if the dictionary is pre-populated, then new * codes should be placed at the end of that block. * Equally, if the dictionary is left with all zeros, then * usually the new codes can go in at the start. */ protected abstract int populateDictionary(byte[] dict); /** * Adjusts the position offset if needed when looking * something up in the dictionary. */ protected abstract int adjustDictionaryOffset(int offset); /** * Decompresses the given input stream, returning the array of bytes * of the decompressed input. */ public byte[] decompress(Stream src) { using (MemoryStream res = new MemoryStream()) { decompress(src, res); return res.ToArray(); } } /** * Perform a streaming decompression of the input. * Works by: * 1) Reading a flag byte, the 8 bits of which tell you if the * following 8 codes are compressed our un-compressed * 2) Consider the 8 bits in turn * 3) If the bit is Set, the next code is un-compressed, so * add it to the dictionary and output it * 4) If the bit isn't Set, then read in the length and start * position in the dictionary, and output the bytes there * 5) Loop until we've done all 8 bits, then read in the next * flag byte */ public void decompress(Stream src, Stream res) { // How far through the output we've got // (This is normally used &4095, so it nicely wraps) // The Initial value is Set when populating the dictionary int pos; // The flag byte is treated as its 8 individual // bits, which tell us if the following 8 codes // are compressed or un-compressed int flag; // The mask, between 1 and 255, which is used when // Processing each bit of the flag byte in turn int mask; // We use 12 bit codes: // * 0-255 are real bytes // * 256-4095 are the substring codes // Java handily Initialises our buffer / dictionary // to all zeros byte[] buffer = new byte[4096]; pos = populateDictionary(buffer); // These are bytes as looked up in the dictionary // It needs to be signed, as it'll Get passed on to // the output stream byte[] dataB = new byte[16 + codeLengthIncrease]; // This is an unsigned byte read from the stream // It needs to be unsigned, so that bit stuff works int dataI; // The compressed code sequence is held over 2 bytes int dataIPt1, dataIPt2; // How long a code sequence is, and where in the // dictionary to start at int len, pntr; while ((flag = src.ReadByte()) != -1) { // Compare each bit in our flag byte in turn: for (mask = 1; mask < 256; mask <<= 1) { // Is this a new code (un-compressed), or // the use of existing codes (compressed)? bool IsMaskSet = (flag & mask) > 0; if (IsMaskSet ^ maskMeansCompressed) { // Retrieve the un-compressed code if ((dataI = src.ReadByte()) != -1) { // Save the byte into the dictionary buffer[(pos & 4095)] = fromInt(dataI); pos++; // And output the byte res.WriteByte(fromInt(dataI)); //res.Write(new byte[] { fromInt(dataI) }, 0, 1); } } else { // We have a compressed sequence // Grab the next 16 bits of data dataIPt1 = src.ReadByte(); dataIPt2 = src.ReadByte(); if (dataIPt1 == -1 || dataIPt2 == -1) break; // Build up how long the code sequence is, and // what position of the code to start at // (The position is the usually the first 12 bits, // and the length is usually the last 4 bits) len = (dataIPt2 & 15) + codeLengthIncrease; if (positionIsBigEndian) { pntr = (dataIPt1 << 4) + (dataIPt2 >> 4); } else { pntr = dataIPt1 + ((dataIPt2 & 0xF0) << 4); } // Adjust the pointer as needed pntr = adjustDictionaryOffset(pntr); // Loop over the codes, outputting what they correspond to for (int i = 0; i < len; i++) { dataB[i] = buffer[(pntr + i) & 4095]; buffer[(pos + i) & 4095] = dataB[i]; } res.Write(dataB, 0, len); // Record how far along the stream we have Moved pos = pos + len; } } } } /** * Given an integer, turn it into a java byte, handling * the wrapping. * This is a convenience method */ public static byte fromInt(int b) { if (b < 128) return (byte)b; return (byte)(b - 256); } /** * Given a java byte, turn it into an integer between 0 * and 255 (i.e. handle the unwrapping). * This is a convenience method */ public static int fromByte(byte b) { if (b >= 0) { return b; } return b + 256; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static partial class PropertyTests { [Fact] public static void TestProperties_GetterSetter() { Type t = typeof(DerivedFromPropertyHolder1<>).Project(); Type bt = t.BaseType; { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.ReadOnlyProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.ReadOnlyProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.False(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.ReadOnlyProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); Assert.Null(p.SetMethod); Assert.Null(p.GetSetMethod(nonPublic: true)); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.ReadWriteProp)); Type theT = t.GetGenericTypeParameters()[0]; Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.ReadWriteProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.ReadWriteProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.ReadWriteProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); MethodInfo[] accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(theT, p.PropertyType); } { PropertyInfo p = bt.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp)); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.True(p.CanRead); Assert.True(p.CanWrite); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(bt, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicPrivateProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(bt, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicPrivateProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(bt, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(GenericClass1<>).Project().MakeGenericType(theT), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp)); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.True(p.CanRead); Assert.False(p.CanWrite); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicPrivateProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); Assert.Null(p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(GenericClass1<>).Project().MakeGenericType(theT), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicInternalProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicInternalProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.True(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicInternalProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicInternalProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicProtectedProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicProtectedProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.True(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicProtectedProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicProtectedProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty("Item"); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.Equal("Item", p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_Item", getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); ParameterInfo[] pis = p.GetIndexParameters(); Assert.Equal(2, pis.Length); for (int i = 0; i < pis.Length; i++) { ParameterInfo pi = pis[i]; Assert.Equal(i, pi.Position); Assert.Equal(p, pi.Member); } Assert.Equal("i", pis[0].Name); Assert.Equal(typeof(int).Project(), pis[0].ParameterType); Assert.Equal("t", pis[1].Name); Assert.Equal(theT, pis[1].ParameterType); } } [Fact] public unsafe static void TestCustomModifiers1() { using (TypeLoader tl = new TypeLoader("mscorlib")) { tl.Resolving += delegate (TypeLoader sender, AssemblyName name) { if (name.Name == "mscorlib") return tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly()); return null; }; Assembly a = tl.LoadFromByteArray(TestData.s_CustomModifiersImage); Type t = a.GetType("N", throwOnError: true); Type reqA = a.GetType("ReqA", throwOnError: true); Type reqB = a.GetType("ReqB", throwOnError: true); Type reqC = a.GetType("ReqC", throwOnError: true); Type optA = a.GetType("OptA", throwOnError: true); Type optB = a.GetType("OptB", throwOnError: true); Type optC = a.GetType("OptC", throwOnError: true); PropertyInfo p = t.GetProperty("MyProperty"); Type[] req = p.GetRequiredCustomModifiers(); Type[] opt = p.GetOptionalCustomModifiers(); Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req); Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetRequiredCustomModifiers()); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetOptionalCustomModifiers()); } } } }
// 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.ObjectModel; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { public partial class Expression { internal class BinaryExpressionProxy { private readonly BinaryExpression _node; public BinaryExpressionProxy(BinaryExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public LambdaExpression Conversion => _node.Conversion; public string DebugView => _node.DebugView; public bool IsLifted => _node.IsLifted; public bool IsLiftedToNull => _node.IsLiftedToNull; public Expression Left => _node.Left; public MethodInfo Method => _node.Method; public ExpressionType NodeType => _node.NodeType; public Expression Right => _node.Right; public Type Type => _node.Type; } internal class BlockExpressionProxy { private readonly BlockExpression _node; public BlockExpressionProxy(BlockExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ReadOnlyCollection<Expression> Expressions => _node.Expressions; public ExpressionType NodeType => _node.NodeType; public Expression Result => _node.Result; public Type Type => _node.Type; public ReadOnlyCollection<ParameterExpression> Variables => _node.Variables; } internal class CatchBlockProxy { private readonly CatchBlock _node; public CatchBlockProxy(CatchBlock node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public Expression Body => _node.Body; public Expression Filter => _node.Filter; public Type Test => _node.Test; public ParameterExpression Variable => _node.Variable; } internal class ConditionalExpressionProxy { private readonly ConditionalExpression _node; public ConditionalExpressionProxy(ConditionalExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression IfFalse => _node.IfFalse; public Expression IfTrue => _node.IfTrue; public ExpressionType NodeType => _node.NodeType; public Expression Test => _node.Test; public Type Type => _node.Type; } internal class ConstantExpressionProxy { private readonly ConstantExpression _node; public ConstantExpressionProxy(ConstantExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; public object Value => _node.Value; } internal class DebugInfoExpressionProxy { private readonly DebugInfoExpression _node; public DebugInfoExpressionProxy(DebugInfoExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public SymbolDocumentInfo Document => _node.Document; public int EndColumn => _node.EndColumn; public int EndLine => _node.EndLine; public bool IsClear => _node.IsClear; public ExpressionType NodeType => _node.NodeType; public int StartColumn => _node.StartColumn; public int StartLine => _node.StartLine; public Type Type => _node.Type; } internal class DefaultExpressionProxy { private readonly DefaultExpression _node; public DefaultExpressionProxy(DefaultExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class GotoExpressionProxy { private readonly GotoExpression _node; public GotoExpressionProxy(GotoExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public GotoExpressionKind Kind => _node.Kind; public ExpressionType NodeType => _node.NodeType; public LabelTarget Target => _node.Target; public Type Type => _node.Type; public Expression Value => _node.Value; } internal class IndexExpressionProxy { private readonly IndexExpression _node; public IndexExpressionProxy(IndexExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public ReadOnlyCollection<Expression> Arguments => _node.Arguments; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public PropertyInfo Indexer => _node.Indexer; public ExpressionType NodeType => _node.NodeType; public Expression Object => _node.Object; public Type Type => _node.Type; } internal class InvocationExpressionProxy { private readonly InvocationExpression _node; public InvocationExpressionProxy(InvocationExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public ReadOnlyCollection<Expression> Arguments => _node.Arguments; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression Expression => _node.Expression; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class LabelExpressionProxy { private readonly LabelExpression _node; public LabelExpressionProxy(LabelExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression DefaultValue => _node.DefaultValue; public ExpressionType NodeType => _node.NodeType; public LabelTarget Target => _node.Target; public Type Type => _node.Type; } internal class LambdaExpressionProxy { private readonly LambdaExpression _node; public LambdaExpressionProxy(LambdaExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public Expression Body => _node.Body; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public string Name => _node.Name; public ExpressionType NodeType => _node.NodeType; public ReadOnlyCollection<ParameterExpression> Parameters => _node.Parameters; public Type ReturnType => _node.ReturnType; public bool TailCall => _node.TailCall; public Type Type => _node.Type; } internal class ListInitExpressionProxy { private readonly ListInitExpression _node; public ListInitExpressionProxy(ListInitExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ReadOnlyCollection<ElementInit> Initializers => _node.Initializers; public NewExpression NewExpression => _node.NewExpression; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class LoopExpressionProxy { private readonly LoopExpression _node; public LoopExpressionProxy(LoopExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public Expression Body => _node.Body; public LabelTarget BreakLabel => _node.BreakLabel; public bool CanReduce => _node.CanReduce; public LabelTarget ContinueLabel => _node.ContinueLabel; public string DebugView => _node.DebugView; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class MemberExpressionProxy { private readonly MemberExpression _node; public MemberExpressionProxy(MemberExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression Expression => _node.Expression; public MemberInfo Member => _node.Member; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class MemberInitExpressionProxy { private readonly MemberInitExpression _node; public MemberInitExpressionProxy(MemberInitExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public ReadOnlyCollection<MemberBinding> Bindings => _node.Bindings; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public NewExpression NewExpression => _node.NewExpression; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class MethodCallExpressionProxy { private readonly MethodCallExpression _node; public MethodCallExpressionProxy(MethodCallExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public ReadOnlyCollection<Expression> Arguments => _node.Arguments; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public MethodInfo Method => _node.Method; public ExpressionType NodeType => _node.NodeType; public Expression Object => _node.Object; public Type Type => _node.Type; } internal class NewArrayExpressionProxy { private readonly NewArrayExpression _node; public NewArrayExpressionProxy(NewArrayExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ReadOnlyCollection<Expression> Expressions => _node.Expressions; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class NewExpressionProxy { private readonly NewExpression _node; public NewExpressionProxy(NewExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public ReadOnlyCollection<Expression> Arguments => _node.Arguments; public bool CanReduce => _node.CanReduce; public ConstructorInfo Constructor => _node.Constructor; public string DebugView => _node.DebugView; public ReadOnlyCollection<MemberInfo> Members => _node.Members; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class ParameterExpressionProxy { private readonly ParameterExpression _node; public ParameterExpressionProxy(ParameterExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public bool IsByRef => _node.IsByRef; public string Name => _node.Name; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class RuntimeVariablesExpressionProxy { private readonly RuntimeVariablesExpression _node; public RuntimeVariablesExpressionProxy(RuntimeVariablesExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; public ReadOnlyCollection<ParameterExpression> Variables => _node.Variables; } internal class SwitchCaseProxy { private readonly SwitchCase _node; public SwitchCaseProxy(SwitchCase node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public Expression Body => _node.Body; public ReadOnlyCollection<Expression> TestValues => _node.TestValues; } internal class SwitchExpressionProxy { private readonly SwitchExpression _node; public SwitchExpressionProxy(SwitchExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public ReadOnlyCollection<SwitchCase> Cases => _node.Cases; public MethodInfo Comparison => _node.Comparison; public string DebugView => _node.DebugView; public Expression DefaultBody => _node.DefaultBody; public ExpressionType NodeType => _node.NodeType; public Expression SwitchValue => _node.SwitchValue; public Type Type => _node.Type; } internal class TryExpressionProxy { private readonly TryExpression _node; public TryExpressionProxy(TryExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public Expression Body => _node.Body; public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression Fault => _node.Fault; public Expression Finally => _node.Finally; public ReadOnlyCollection<CatchBlock> Handlers => _node.Handlers; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; } internal class TypeBinaryExpressionProxy { private readonly TypeBinaryExpression _node; public TypeBinaryExpressionProxy(TypeBinaryExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public Expression Expression => _node.Expression; public ExpressionType NodeType => _node.NodeType; public Type Type => _node.Type; public Type TypeOperand => _node.TypeOperand; } internal class UnaryExpressionProxy { private readonly UnaryExpression _node; public UnaryExpressionProxy(UnaryExpression node) { ContractUtils.RequiresNotNull(node, nameof(node)); _node = node; } public bool CanReduce => _node.CanReduce; public string DebugView => _node.DebugView; public bool IsLifted => _node.IsLifted; public bool IsLiftedToNull => _node.IsLiftedToNull; public MethodInfo Method => _node.Method; public ExpressionType NodeType => _node.NodeType; public Expression Operand => _node.Operand; public Type Type => _node.Type; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsyncDolls { /// <summary> /// Provides a TaskScheduler that provides control over priorities, fairness, and the underlying threads utilized. /// </summary> [DebuggerTypeProxy(typeof(QueuedTaskSchedulerDebugView)), DebuggerDisplay("Id={Id}, Queues={DebugQueueCount}, ScheduledTasks = {DebugTaskCount}")] sealed class QueuedTaskScheduler : TaskScheduler, IDisposable { /// <summary>Whether we're processing tasks on the current thread.</summary> static readonly ThreadLocal<bool> _taskProcessingThread = new ThreadLocal<bool>(); /// <summary>The collection of tasks to be executed on our custom threads.</summary> readonly BlockingCollection<Task> _blockingTaskQueue; /// <summary> /// The maximum allowed concurrency level of this scheduler. If custom threads are /// used, this represents the number of created threads. /// </summary> readonly int _concurrencyLevel; /// <summary>Cancellation token used for disposal.</summary> readonly CancellationTokenSource _disposeCancellation = new CancellationTokenSource(); // *** // *** For when using a target scheduler // *** /// <summary>The queue of tasks to process when using an underlying target scheduler.</summary> readonly Queue<Task> _nonthreadsafeTaskQueue; /// <summary> /// A sorted list of round-robin queue lists. Tasks with the smallest priority value /// are preferred. Priority groups are round-robin'd through in order of priority. /// </summary> readonly SortedList<int, QueueGroup> _queueGroups = new SortedList<int, QueueGroup>(); /// <summary>The scheduler onto which actual work is scheduled.</summary> readonly TaskScheduler _targetScheduler; // *** // *** For when using our own threads // *** /// <summary>The threads used by the scheduler to process work.</summary> readonly Thread[] _threads; /// <summary>The number of Tasks that have been queued or that are running whiel using an underlying scheduler.</summary> int _delegatesQueuedOrRunning; // *** /// <summary>Initializes the scheduler.</summary> public QueuedTaskScheduler() : this(Default, 0) { } /// <summary>Initializes the scheduler.</summary> /// <param name="targetScheduler">The target underlying scheduler onto which this sceduler's work is queued.</param> public QueuedTaskScheduler(TaskScheduler targetScheduler) : this(targetScheduler, 0) { } /// <summary>Initializes the scheduler.</summary> /// <param name="targetScheduler">The target underlying scheduler onto which this sceduler's work is queued.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency allowed for this scheduler's work.</param> public QueuedTaskScheduler(TaskScheduler targetScheduler, int maxConcurrencyLevel) { if (targetScheduler == null) throw new ArgumentNullException("targetScheduler"); if (maxConcurrencyLevel < 0) throw new ArgumentOutOfRangeException("maxConcurrencyLevel"); // Initialize only those fields relevant to use an underlying scheduler. We don't // initialize the fields relevant to using our own custom threads. _targetScheduler = targetScheduler; _nonthreadsafeTaskQueue = new Queue<Task>(); // If 0, use the number of logical processors. But make sure whatever value we pick // is not greater than the degree of parallelism allowed by the underlying scheduler. _concurrencyLevel = maxConcurrencyLevel != 0 ? maxConcurrencyLevel : Environment.ProcessorCount; if (targetScheduler.MaximumConcurrencyLevel > 0 && targetScheduler.MaximumConcurrencyLevel < _concurrencyLevel) _concurrencyLevel = targetScheduler.MaximumConcurrencyLevel; } /// <summary>Initializes the scheduler.</summary> /// <param name="threadCount">The number of threads to create and use for processing work items.</param> public QueuedTaskScheduler(int threadCount) : this(threadCount, String.Empty, false, ThreadPriority.Normal, ApartmentState.MTA, 0, null, null) { } /// <summary>Initializes the scheduler.</summary> /// <param name="threadCount">The number of threads to create and use for processing work items.</param> /// <param name="threadName">The name to use for each of the created threads.</param> /// <param name="useForegroundThreads">A Boolean value that indicates whether to use foreground threads instead of background.</param> /// <param name="threadPriority">The priority to assign to each thread.</param> /// <param name="threadApartmentState">The apartment state to use for each thread.</param> /// <param name="threadMaxStackSize">The stack size to use for each thread.</param> /// <param name="threadInit">An initialization routine to run on each thread.</param> /// <param name="threadFinally">A finalization routine to run on each thread.</param> public QueuedTaskScheduler( int threadCount, string threadName = "", bool useForegroundThreads = false, ThreadPriority threadPriority = ThreadPriority.Normal, ApartmentState threadApartmentState = ApartmentState.MTA, int threadMaxStackSize = 0, Action threadInit = null, Action threadFinally = null) { // Validates arguments (some validation is left up to the Thread type itself). // If the thread count is 0, default to the number of logical processors. if (threadCount < 0) throw new ArgumentOutOfRangeException("threadCount"); _concurrencyLevel = threadCount == 0 ? Environment.ProcessorCount : threadCount; // Initialize the queue used for storing tasks _blockingTaskQueue = new BlockingCollection<Task>(); // Create all of the threads _threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { _threads[i] = new Thread(() => ThreadBasedDispatchLoop(threadInit, threadFinally), threadMaxStackSize) { Priority = threadPriority, IsBackground = !useForegroundThreads, }; if (threadName != null) _threads[i].Name = threadName + " (" + i + ")"; _threads[i].SetApartmentState(threadApartmentState); } // Start all of the threads foreach (Thread thread in _threads) thread.Start(); } /// <summary>Gets the number of queues currently activated.</summary> int DebugQueueCount { get { int count = 0; foreach (var group in _queueGroups) count += @group.Value.Count; return count; } } /// <summary>Gets the number of tasks currently scheduled.</summary> int DebugTaskCount { get { return (_targetScheduler != null ? _nonthreadsafeTaskQueue : (IEnumerable<Task>)_blockingTaskQueue) .Where(t => t != null).Count(); } } /// <summary>Gets the maximum concurrency level to use when processing tasks.</summary> public override int MaximumConcurrencyLevel { get { return _concurrencyLevel; } } /// <summary>Initiates shutdown of the scheduler.</summary> public void Dispose() { _disposeCancellation.Cancel(); } /// <summary>The dispatch loop run by all threads in this scheduler.</summary> /// <param name="threadInit">An initialization routine to run when the thread begins.</param> /// <param name="threadFinally">A finalization routine to run before the thread ends.</param> void ThreadBasedDispatchLoop(Action threadInit, Action threadFinally) { _taskProcessingThread.Value = true; if (threadInit != null) threadInit(); try { // If the scheduler is disposed, the cancellation token will be set and // we'll receive an OperationCanceledException. That OCE should not crash the process. try { // If a thread abort occurs, we'll try to reset it and continue running. while (true) { try { // For each task queued to the scheduler, try to execute it. foreach (Task task in _blockingTaskQueue.GetConsumingEnumerable(_disposeCancellation.Token)) { // If the task is not null, that means it was queued to this scheduler directly. // Run it. if (task != null) TryExecuteTask(task); // If the task is null, that means it's just a placeholder for a task // queued to one of the subschedulers. Find the next task based on // priority and fairness and run it. else { // Find the next task based on our ordering rules... Task targetTask; QueuedTaskSchedulerQueue queueForTargetTask; lock (_queueGroups) FindNextTaskNeedsLock(out targetTask, out queueForTargetTask); // ... and if we found one, run it if (targetTask != null) queueForTargetTask.ExecuteTask(targetTask); } } } catch (ThreadAbortException) { // If we received a thread abort, and that thread abort was due to shutting down // or unloading, let it pass through. Otherwise, reset the abort so we can // continue processing work items. if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) Thread.ResetAbort(); } } } catch (OperationCanceledException) { } } finally { // Run a cleanup routine if there was one if (threadFinally != null) threadFinally(); _taskProcessingThread.Value = false; } } /// <summary>Find the next task that should be executed, based on priorities and fairness and the like.</summary> /// <param name="targetTask">The found task, or null if none was found.</param> /// <param name="queueForTargetTask"> /// The scheduler associated with the found task. Due to security checks inside of TPL, /// this scheduler needs to be used to execute that task. /// </param> void FindNextTaskNeedsLock(out Task targetTask, out QueuedTaskSchedulerQueue queueForTargetTask) { targetTask = null; queueForTargetTask = null; // Look through each of our queue groups in sorted order. // This ordering is based on the priority of the queues. foreach (var queueGroup in _queueGroups) { QueueGroup queues = queueGroup.Value; // Within each group, iterate through the queues in a round-robin // fashion. Every time we iterate again and successfully find a task, // we'll start in the next location in the group. foreach (int i in queues.CreateSearchOrder()) { queueForTargetTask = queues[i]; Queue<Task> items = queueForTargetTask._workItems; if (items.Count > 0) { targetTask = items.Dequeue(); if (queueForTargetTask._disposed && items.Count == 0) RemoveQueueNeedsLock(queueForTargetTask); queues.NextQueueIndex = (queues.NextQueueIndex + 1) % queueGroup.Value.Count; return; } } } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected override void QueueTask(Task task) { // If we've been disposed, no one should be queueing if (_disposeCancellation.IsCancellationRequested) throw new ObjectDisposedException(GetType().Name); // If the target scheduler is null (meaning we're using our own threads), // add the task to the blocking queue if (_targetScheduler == null) _blockingTaskQueue.Add(task); // Otherwise, add the task to the non-blocking queue, // and if there isn't already an executing processing task, // start one up else { // Queue the task and check whether we should launch a processing // task (noting it if we do, so that other threads don't result // in queueing up too many). bool launchTask = false; lock (_nonthreadsafeTaskQueue) { _nonthreadsafeTaskQueue.Enqueue(task); if (_delegatesQueuedOrRunning < _concurrencyLevel) { ++_delegatesQueuedOrRunning; launchTask = true; } } // If necessary, start processing asynchronously if (launchTask) { Task.Factory.StartNew(ProcessPrioritizedAndBatchedTasks, CancellationToken.None, TaskCreationOptions.None, _targetScheduler); } } } /// <summary> /// Process tasks one at a time in the best order. /// This should be run in a Task generated by QueueTask. /// It's been separated out into its own method to show up better in Parallel Tasks. /// </summary> void ProcessPrioritizedAndBatchedTasks() { bool continueProcessing = true; while (!_disposeCancellation.IsCancellationRequested && continueProcessing) { try { // Note that we're processing tasks on this thread _taskProcessingThread.Value = true; // Until there are no more tasks to process while (!_disposeCancellation.IsCancellationRequested) { // Try to get the next task. If there aren't any more, we're done. Task targetTask; lock (_nonthreadsafeTaskQueue) { if (_nonthreadsafeTaskQueue.Count == 0) break; targetTask = _nonthreadsafeTaskQueue.Dequeue(); } // If the task is null, it's a placeholder for a task in the round-robin queues. // Find the next one that should be processed. QueuedTaskSchedulerQueue queueForTargetTask = null; if (targetTask == null) { lock (_queueGroups) FindNextTaskNeedsLock(out targetTask, out queueForTargetTask); } // Now if we finally have a task, run it. If the task // was associated with one of the round-robin schedulers, we need to use it // as a thunk to execute its task. if (targetTask != null) { if (queueForTargetTask != null) queueForTargetTask.ExecuteTask(targetTask); else TryExecuteTask(targetTask); } } } finally { // Now that we think we're done, verify that there really is // no more work to do. If there's not, highlight // that we're now less parallel than we were a moment ago. lock (_nonthreadsafeTaskQueue) { if (_nonthreadsafeTaskQueue.Count == 0) { _delegatesQueuedOrRunning--; continueProcessing = false; _taskProcessingThread.Value = false; } } } } } /// <summary>Notifies the pool that there's a new item to be executed in one of the round-robin queues.</summary> void NotifyNewWorkItem() { QueueTask(null); } /// <summary>Tries to execute a task synchronously on the current thread.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued.</param> /// <returns>true if the task was executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If we're already running tasks on this threads, enable inlining return _taskProcessingThread.Value && TryExecuteTask(task); } /// <summary>Gets the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of all tasks queued to this scheduler.</returns> /// <remarks>This does not include the tasks on sub-schedulers. Those will be retrieved by the debugger separately.</remarks> protected override IEnumerable<Task> GetScheduledTasks() { // If we're running on our own threads, get the tasks from the blocking queue... if (_targetScheduler == null) { // Get all of the tasks, filtering out nulls, which are just placeholders // for tasks in other sub-schedulers return _blockingTaskQueue.Where(t => t != null).ToList(); } // otherwise get them from the non-blocking queue... return _nonthreadsafeTaskQueue.Where(t => t != null).ToList(); } /// <summary>Creates and activates a new scheduling queue for this scheduler.</summary> /// <returns>The newly created and activated queue at priority 0.</returns> public TaskScheduler ActivateNewQueue() { return ActivateNewQueue(0); } /// <summary>Creates and activates a new scheduling queue for this scheduler.</summary> /// <param name="priority">The priority level for the new queue.</param> /// <returns>The newly created and activated queue at the specified priority.</returns> public TaskScheduler ActivateNewQueue(int priority) { // Create the queue var createdQueue = new QueuedTaskSchedulerQueue(priority, this); // Add the queue to the appropriate queue group based on priority lock (_queueGroups) { QueueGroup list; if (!_queueGroups.TryGetValue(priority, out list)) { list = new QueueGroup(); _queueGroups.Add(priority, list); } list.Add(createdQueue); } // Hand the new queue back return createdQueue; } /// <summary>Removes a scheduler from the group.</summary> /// <param name="queue">The scheduler to be removed.</param> void RemoveQueueNeedsLock(QueuedTaskSchedulerQueue queue) { // Find the group that contains the queue and the queue's index within the group QueueGroup queueGroup = _queueGroups[queue._priority]; int index = queueGroup.IndexOf(queue); // We're about to remove the queue, so adjust the index of the next // round-robin starting location if it'll be affected by the removal if (queueGroup.NextQueueIndex >= index) queueGroup.NextQueueIndex--; // Remove it queueGroup.RemoveAt(index); } /// <summary>A group of queues a the same priority level.</summary> class QueueGroup : List<QueuedTaskSchedulerQueue> { /// <summary>The starting index for the next round-robin traversal.</summary> public int NextQueueIndex; /// <summary>Creates a search order through this group.</summary> /// <returns>An enumerable of indices for this group.</returns> public IEnumerable<int> CreateSearchOrder() { for (int i = NextQueueIndex; i < Count; i++) yield return i; for (int i = 0; i < NextQueueIndex; i++) yield return i; } } /// <summary>Debug view for the QueuedTaskScheduler.</summary> class QueuedTaskSchedulerDebugView { /// <summary>The scheduler.</summary> readonly QueuedTaskScheduler _scheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler.</param> public QueuedTaskSchedulerDebugView(QueuedTaskScheduler scheduler) { if (scheduler == null) throw new ArgumentNullException("scheduler"); _scheduler = scheduler; } /// <summary>Gets all of the Tasks queued to the scheduler directly.</summary> public IEnumerable<Task> ScheduledTasks { get { IEnumerable<Task> tasks = (_scheduler._targetScheduler != null) ? _scheduler._nonthreadsafeTaskQueue : (IEnumerable<Task>)_scheduler._blockingTaskQueue; return tasks.Where(t => t != null).ToList(); } } /// <summary>Gets the prioritized and fair queues.</summary> public IEnumerable<TaskScheduler> Queues { get { var queues = new List<TaskScheduler>(); foreach (var group in _scheduler._queueGroups) queues.AddRange(@group.Value); return queues; } } } /// <summary>Provides a scheduling queue associatd with a QueuedTaskScheduler.</summary> [DebuggerDisplay("QueuePriority = {_priority}, WaitingTasks = {WaitingTasks}"), DebuggerTypeProxy(typeof(QueuedTaskSchedulerQueueDebugView))] sealed class QueuedTaskSchedulerQueue : TaskScheduler, IDisposable { /// <summary>The scheduler with which this pool is associated.</summary> readonly QueuedTaskScheduler _pool; /// <summary>Gets the priority for this queue.</summary> internal readonly int _priority; /// <summary>The work items stored in this queue.</summary> internal readonly Queue<Task> _workItems; /// <summary>Whether this queue has been disposed.</summary> internal bool _disposed; /// <summary>Initializes the queue.</summary> /// <param name="priority">The priority associated with this queue.</param> /// <param name="pool">The scheduler with which this queue is associated.</param> internal QueuedTaskSchedulerQueue(int priority, QueuedTaskScheduler pool) { _priority = priority; _pool = pool; _workItems = new Queue<Task>(); } /// <summary>Gets the number of tasks waiting in this scheduler.</summary> internal int WaitingTasks { get { return _workItems.Count; } } /// <summary>Gets the maximum concurrency level to use when processing tasks.</summary> public override int MaximumConcurrencyLevel { get { return _pool.MaximumConcurrencyLevel; } } /// <summary>Signals that the queue should be removed from the scheduler as soon as the queue is empty.</summary> public void Dispose() { if (!_disposed) { lock (_pool._queueGroups) { // We only remove the queue if it's empty. If it's not empty, // we still mark it as disposed, and the associated QueuedTaskScheduler // will remove the queue when its count hits 0 and its _disposed is true. if (_workItems.Count == 0) _pool.RemoveQueueNeedsLock(this); } _disposed = true; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of all tasks queued to this scheduler.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return _workItems.ToList(); } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected override void QueueTask(Task task) { if (_disposed) throw new ObjectDisposedException(GetType().Name); // Queue up the task locally to this queue, and then notify // the parent scheduler that there's work available lock (_pool._queueGroups) _workItems.Enqueue(task); _pool.NotifyNewWorkItem(); } /// <summary>Tries to execute a task synchronously on the current thread.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued.</param> /// <returns>true if the task was executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If we're using our own threads and if this is being called from one of them, // or if we're currently processing another task on this thread, try running it inline. return _taskProcessingThread.Value && TryExecuteTask(task); } /// <summary>Runs the specified ask.</summary> /// <param name="task">The task to execute.</param> internal void ExecuteTask(Task task) { TryExecuteTask(task); } /// <summary>A debug view for the queue.</summary> sealed class QueuedTaskSchedulerQueueDebugView { /// <summary>The queue.</summary> readonly QueuedTaskSchedulerQueue _queue; /// <summary>Initializes the debug view.</summary> /// <param name="queue">The queue to be debugged.</param> public QueuedTaskSchedulerQueueDebugView(QueuedTaskSchedulerQueue queue) { if (queue == null) throw new ArgumentNullException("queue"); _queue = queue; } /// <summary>Gets the priority of this queue in its associated scheduler.</summary> public int Priority { get { return _queue._priority; } } /// <summary>Gets the ID of this scheduler.</summary> public int Id { get { return _queue.Id; } } /// <summary>Gets all of the tasks scheduled to this queue.</summary> public IEnumerable<Task> ScheduledTasks { get { return _queue.GetScheduledTasks(); } } /// <summary>Gets the QueuedTaskScheduler with which this queue is associated.</summary> public QueuedTaskScheduler AssociatedScheduler { get { return _queue._pool; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Emgu.CV; using Emgu.CV.Structure; using Xamarin.Media; namespace com.bytewild.imaging { public class SelectImageActivityBase : Activity { private Button _clickButton; private TextView _messageText; private ImageView _imageView; private String _buttonText; private ProgressDialog _progress; //private Image<Bgr, Byte> _defaultImage; private MediaPicker _mediaPicker; public SelectImageActivityBase(String buttonText) : base() { _buttonText = buttonText; //dummy code to load the opencv libraries CvInvoke.CV_FOURCC('m', 'j', 'p', 'g'); } public Image<Bgr, Byte> PickImage(String defaultImageName) { if (_mediaPicker == null) { _mediaPicker = new MediaPicker(this); } String negative = _mediaPicker.IsCameraAvailable ? "Camera" : "Cancel"; int result = GetUserResponse(this, "Use Image from", "Default", "Photo Library", negative); if (result > 0) return new Image<Bgr, byte>(Assets, defaultImageName); else if (result == 0) { return GetImageFromTask(_mediaPicker.PickPhotoAsync(), 800, 800); } else if (_mediaPicker.IsCameraAvailable) { return GetImageFromTask(_mediaPicker.TakePhotoAsync(new StoreCameraMediaOptions()), 800, 800); } return null; } private static int GetUserResponse(Activity activity, String title, String positive, string neutral, string negative) { AutoResetEvent e = new AutoResetEvent(false); int value = 0; activity.RunOnUiThread(delegate { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.SetTitle(title); builder.SetPositiveButton(positive, (s, er) => { value = 1; e.Set(); }); builder.SetNeutralButton(neutral, (s, er) => { value = 0; e.Set(); }); builder.SetNegativeButton(negative, (s, er) => { value = -1; e.Set(); }); builder.Show(); }); e.WaitOne(); return value; } private static Image<Bgr, Byte> GetImageFromTask(Task<MediaFile> task, int maxWidth, int maxHeight) { MediaFile file = GetResultFromTask(task); if (file == null) return null; int rotation = 0; Android.Media.ExifInterface exif = new Android.Media.ExifInterface(file.Path); int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue); switch (orientation) { case (int)Android.Media.Orientation.Rotate270: rotation = 270; break; case (int)Android.Media.Orientation.Rotate180: rotation = 180; break; case (int)Android.Media.Orientation.Rotate90: rotation = 90; break; } using (Bitmap bmp = BitmapFactory.DecodeFile(file.Path)) { if (bmp.Width <= maxWidth && bmp.Height <= maxHeight && rotation == 0) { return new Image<Bgr, byte>(bmp); } else { using (Matrix matrix = new Matrix()) { if (bmp.Width > maxWidth || bmp.Height > maxHeight) { double scale = Math.Min((double)maxWidth / bmp.Width, (double)maxHeight / bmp.Height); matrix.PostScale((float)scale, (float)scale); } if (rotation != 0) matrix.PostRotate(rotation); using (Bitmap scaled = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true)) { return new Image<Bgr, byte>(scaled); } } } } } private static TResult GetResultFromTask<TResult>(Task<TResult> task) where TResult : class { if (task == null) return null; task.Wait(); if (task.Status != TaskStatus.Canceled && task.Status != TaskStatus.Faulted) return task.Result; return null; } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _clickButton = new Button(this); _clickButton.Text = _buttonText; _clickButton.LayoutParameters = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent); _messageText = new TextView(this); _messageText.SetTextAppearance(this, Android.Resource.Attribute.TextAppearanceSmall); _imageView = new ImageView(this); _imageView.LayoutParameters = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.MatchParent); LinearLayout layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent); layout.AddView(_clickButton); layout.AddView(_messageText); layout.AddView(_imageView); ScrollView scrollView = new ScrollView(this); scrollView.AddView(layout); SetContentView(scrollView); _progress = new ProgressDialog(this) { Indeterminate = true }; _progress.SetTitle("Processing"); _progress.SetMessage("Please wait..."); _clickButton.Click += delegate(Object sender, EventArgs e) { if (OnButtonClick != null) { _progress.Show(); ThreadPool.QueueUserWorkItem(delegate { try { OnButtonClick(sender, e); } #if !DEBUG catch (Exception excpt) { while (excpt.InnerException != null) { excpt = excpt.InnerException; } RunOnUiThread(() => { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Error"); alert.SetMessage(excpt.Message); alert.SetPositiveButton("OK", (s, er) => { }); alert.Show(); }); } #endif finally { RunOnUiThread( _progress.Hide); } } ); } }; } public EventHandler<EventArgs> OnButtonClick; public void SetMessage(String message) { RunOnUiThread(() => { _messageText.Text = message; }); } public void SetImageBitmap(Bitmap image) { RunOnUiThread(() => { _imageView.SetImageBitmap(image); }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using IxMilia.Dxf.Entities; using IxMilia.Dxf.Objects; using IxMilia.Dxf.Sections; using Xunit; namespace IxMilia.Dxf.Test { public class ObjectTests : AbstractDxfTests { private DxfObject GenObject(string typeString, params (int code, object value)[] codePairs) { var prePairs = new[] { (0, (object)typeString) }; return Section("OBJECTS", prePairs.Concat(codePairs)).Objects.Last(); } private static void EnsureFileContainsObject(DxfObject obj, DxfAcadVersion version, params (int code, object value)[] codePairs) { var file = new DxfFile(); file.Clear(); file.Header.Version = version; file.Objects.Add(obj); VerifyFileContains(file, codePairs); } [Fact] public void ReadSimpleObjectTest() { var proxyObject = GenObject("ACAD_PROXY_OBJECT"); Assert.IsType<DxfAcadProxyObject>(proxyObject); } [Fact] public void WriteSimpleObjectTest() { var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2000; file.Objects.Add(new DxfAcadProxyObject()); VerifyFileContains(file, DxfSectionType.Objects, (0, "ACAD_PROXY_OBJECT"), (5, "#"), (100, "AcDbProxyObject"), (90, 499) ); } [Fact] public void ReadAllObjectsWithTrailingXDataTest() { foreach (var objectType in GetAllObjectTypes()) { var o = Activator.CreateInstance(objectType, nonPublic: true); if (o is DxfObject obj) { var file = Section("OBJECTS", (0, obj.ObjectTypeString), (5, "424241"), (1001, "ACAD"), (1000, "sample-xdata"), (0, "ACAD_PROXY_OBJECT"), // sentinel to ensure we didn't read too far (5, "424242") ); Assert.Equal(2, file.Objects.Count); var readObject = file.Objects.First(); Assert.IsType(objectType, readObject); Assert.Equal((ulong)0x424241, ((IDxfItemInternal)readObject).Handle.Value); var xdata = readObject.XData; var kvp = xdata.Single(); Assert.Equal("ACAD", kvp.Key); Assert.Equal("sample-xdata", ((DxfXDataString)kvp.Value.Single()).Value); var sentinel = file.Objects.Last(); Assert.IsType<DxfAcadProxyObject>(sentinel); Assert.Equal((ulong)0x424242, ((IDxfItemInternal)sentinel).Handle.Value); } } } [Fact] public void ReadDataTableTest() { var table = (DxfDataTable)GenObject("DATATABLE", (330, "0"), (100, "AcDbDataTable"), (70, 2), (90, 3), // 3 columns (91, 2), // 2 rows per column (1, "table-name"), (92, 10), // column 1 (2, "column-of-points"), (10, 1.0), (20, 2.0), (30, 3.0), (10, 4.0), (20, 5.0), (30, 6.0), (92, 3), // column 2 (2, "column-of-strings"), (3, "string 1"), (3, "string 2"), (92, 331), // column 3 (2, "column-of-handles"), (331, "ABCD"), (331, "1234") ); Assert.Equal(3, table.ColumnCount); Assert.Equal(2, table.RowCount); Assert.Equal("table-name", table.Name); Assert.Equal("column-of-points", table.ColumnNames[0]); Assert.Equal(new DxfPoint(1, 2, 3), (DxfPoint)table[0, 0]); Assert.Equal(new DxfPoint(4, 5, 6), (DxfPoint)table[1, 0]); Assert.Equal("column-of-strings", table.ColumnNames[1]); Assert.Equal("string 1", (string)table[0, 1]); Assert.Equal("string 2", (string)table[1, 1]); Assert.Equal("column-of-handles", table.ColumnNames[2]); Assert.Equal(new DxfHandle(0xABCD), (DxfHandle)table[0, 2]); Assert.Equal(new DxfHandle(0x1234), (DxfHandle)table[1, 2]); } [Fact] public void WriteDataTableTest() { var table = new DxfDataTable(); table.Name = "table-name"; table.SetSize(2, 2); table.ColumnNames.Add("column-of-points"); table.ColumnNames.Add("column-of-strings"); table[0, 0] = new DxfPoint(1, 2, 3); table[1, 0] = new DxfPoint(4, 5, 6); table[0, 1] = "string 1"; table[1, 1] = "string 2"; var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2007; file.Objects.Add(table); VerifyFileContains(file, (100, "AcDbDataTable"), (70, 0), (90, 2), (91, 2), (1, "table-name"), (92, 10), (2, "column-of-points"), (10, 1.0), (20, 2.0), (30, 3.0), (10, 4.0), (20, 5.0), (30, 6.0), (92, 3), (2, "column-of-strings"), (3, "string 1"), (3, "string 2") ); } [Fact] public void ReadDictionaryTest1() { // dictionary with simple DICTIONARYVAR values var file = Section("OBJECTS", (0, "DICTIONARY"), (3, "key-1"), (360, "111"), // pointer to value-1 below (3, "key-2"), (360, "222"), // pointer to value-2 below (0, "DICTIONARYVAR"), (5, "111"), (280, 0), (1, "value-1"), (0, "DICTIONARYVAR"), (5, "222"), (280, 0), (1, "value-2") ); var dict = file.Objects.OfType<DxfDictionary>().Single(); Assert.Equal(dict, dict["key-1"].Owner); Assert.Equal(dict, dict["key-2"].Owner); Assert.Equal("value-1", ((DxfDictionaryVariable)dict["key-1"]).Value); Assert.Equal("value-2", ((DxfDictionaryVariable)dict["key-2"]).Value); } [Fact] public void ReadDictionaryTest2() { // dictionary with sub-dictionary with DICTIONARYVAR value var file = Section("OBJECTS", (0, "DICTIONARY"), (3, "key-1"), (360, "1000"), // pointer to dictionary below (0, "DICTIONARY"), (5, "1000"), (3, "key-2"), (360, "2000"), // pointer to value-2 below (0, "DICTIONARYVAR"), (5, "2000"), (280, 0), (1, "value-2") ); var dict1 = file.Objects.OfType<DxfDictionary>().First(); var dict2 = (DxfDictionary)dict1["key-1"]; Assert.Equal(dict1, dict2.Owner); Assert.Equal(dict2, dict2["key-2"].Owner); Assert.Equal("value-2", ((DxfDictionaryVariable)dict2["key-2"]).Value); } [Fact] public void ReadDictionaryTest3() { // dictionary with default with simple DICTIONARYVAR values var file = Section("OBJECTS", (0, "DICTIONARYVAR"), (5, "1"), (280, 0), (1, "default-value"), (0, "ACDBDICTIONARYWDFLT"), (5, "2"), (340, "1"), (3, "key-1"), (350, "111"), (3, "key-2"), (360, "222"), (0, "DICTIONARYVAR"), (5, "111"), (280, 0), (1, "value-1"), (0, "DICTIONARYVAR"), (5, "222"), (280, 0), (1, "value-2") ); var dict = file.Objects.OfType<DxfDictionaryWithDefault>().Single(); Assert.Equal(dict, dict["key-1"].Owner); Assert.Equal(dict, dict["key-2"].Owner); Assert.Equal("value-1", ((DxfDictionaryVariable)dict["key-1"]).Value); Assert.Equal("value-2", ((DxfDictionaryVariable)dict["key-2"]).Value); Assert.Equal("default-value", ((DxfDictionaryVariable)dict["key-that-isn't-present"]).Value); } [Fact] public void ReadDictionaryTest4() { // dictionary with default with sub-dictionary with DICTIONARYVAR value var file = Section("OBJECTS", (0, "DICTIONARYVAR"), (5, "1"), (280, 0), (1, "default-value"), (0, "ACDBDICTIONARYWDFLT"), (340, "1"), (3, "key-1"), (350, "111"), (0, "DICTIONARY"), (5, "111"), (3, "key-2"), (360, "1000"), (0, "DICTIONARYVAR"), (5, "1000"), (280, 0), (1, "value-2") ); var dict1 = file.Objects.OfType<DxfDictionaryWithDefault>().Single(); var dict2 = (DxfDictionary)dict1["key-1"]; Assert.Equal(dict1, dict2.Owner); Assert.Equal(dict2, dict2["key-2"].Owner); Assert.Equal("value-2", ((DxfDictionaryVariable)dict2["key-2"]).Value); } [Fact] public void ReadDictionaryTest5() { // dictionary with MLINESTYLE value var file = Section("OBJECTS", (0, "DICTIONARY"), (5, "42"), (3, "Standard"), (350, "43"), (0, "MLINESTYLE"), (5, "43"), (330, "42"), (2, "Standard") ); var dict = (DxfDictionary)file.Objects.First(); var mlineStyle = (DxfMLineStyle)dict["Standard"]; Assert.Equal("Standard", mlineStyle.StyleName); // now round-trip it using (var ms = new MemoryStream()) { file.Save(ms); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); var file2 = DxfFile.Load(ms); var dict2 = (DxfDictionary)file.Objects.First(); var mlineStyle2 = (DxfMLineStyle)dict["Standard"]; Assert.Equal("Standard", mlineStyle2.StyleName); } } [Fact] public void DictionaryWithUnsupportedObjectTest() { var file = Section("OBJECTS", (0, "DICTIONARY"), (5, "42"), (3, "key"), (350, "43"), (0, "UNSUPPORTED_OBJECT"), (5, "43"), (330, "42") ); var dict = (DxfDictionary)file.Objects.Single(); Assert.Equal(1, dict.Keys.Count); Assert.Null(dict["key"]); } [Fact] public void WriteDictionaryTest1() { // dictionary with simple DICTIONARYVAR values var dict = new DxfDictionary(); dict["key-1"] = new DxfDictionaryVariable() { Value = "value-1" }; dict["key-2"] = new DxfDictionaryVariable() { Value = "value-2" }; EnsureFileContainsObject(dict, DxfAcadVersion.R2000, (0, "DICTIONARY"), (5, "#"), (100, "AcDbDictionary"), (281, 0), (3, "key-1"), (350, "#"), (3, "key-2"), (350, "#"), (0, "DICTIONARYVAR"), (5, "#"), (330, "#"), (100, "DictionaryVariables"), (280, 0), (1, "value-1"), (0, "DICTIONARYVAR"), (5, "#"), (330, "#"), (100, "DictionaryVariables"), (280, 0), (1, "value-2") ); } [Fact] public void WriteDictionaryTest2() { // dictionary with sub-dictionary with DICTIONARYVAR value var dict1 = new DxfDictionary(); var dict2 = new DxfDictionary(); dict1["key-1"] = dict2; dict2["key-2"] = new DxfDictionaryVariable() { Value = "value-2" }; EnsureFileContainsObject(dict1, DxfAcadVersion.R2000, (0, "DICTIONARY"), (5, "#"), (100, "AcDbDictionary"), (281, 0), (3, "key-1"), (350, "#"), (0, "DICTIONARY"), (5, "#"), (330, "#"), (100, "AcDbDictionary"), (281, 0), (3, "key-2"), (350, "#"), (0, "DICTIONARYVAR"), (5, "#"), (330, "#"), (100, "DictionaryVariables"), (280, 0), (1, "value-2") ); } [Fact] public void WriteDictionaryTest3() { // dictionary with default with DICTIONARYVAR value var dict = new DxfDictionaryWithDefault(); dict.DefaultObject = new DxfDictionaryVariable() { Value = "default-value" }; dict["key-1"] = new DxfDictionaryVariable() { Value = "value-1" }; EnsureFileContainsObject(dict, DxfAcadVersion.R2000, (0, "ACDBDICTIONARYWDFLT"), (5, "#"), (100, "AcDbDictionary"), (281, 0), (3, "key-1"), (350, "#"), (100, "AcDbDictionaryWithDefault"), (340, "#"), (0, "DICTIONARYVAR"), (5, "#"), (330, "#"), (100, "DictionaryVariables"), (280, 0), (1, "default-value"), (0, "DICTIONARYVAR"), (5, "#"), (330, "#"), (100, "DictionaryVariables"), (280, 0), (1, "value-1") ); } [Fact] public void WriteDictionaryWithNullValueTest() { var dict = new DxfDictionary(); dict["key"] = null; var objectsSection = new DxfObjectsSection(); objectsSection.Objects.Add(dict); var _pairs = objectsSection.GetValuePairs(DxfAcadVersion.R2000, outputHandles: true, writtenItems: new HashSet<IDxfItem>()); } [Fact] public void DictionaryRoundTripTest1() { // dictionary with DICTIONARYVAR values var dict = new DxfDictionary(); dict["key-1"] = new DxfDictionaryVariable() { Value = "value-1" }; dict["key-2"] = new DxfDictionaryVariable() { Value = "value-2" }; var file = new DxfFile(); file.Clear(); file.Header.Version = DxfAcadVersion.R2000; file.Objects.Add(dict); var roundTrippedFile = RoundTrip(file); var roundTrippedDict = roundTrippedFile.Objects.OfType<DxfDictionary>().Single(d => d.Keys.Count == 2); Assert.Equal("value-1", ((DxfDictionaryVariable)roundTrippedDict["key-1"]).Value); Assert.Equal("value-2", ((DxfDictionaryVariable)roundTrippedDict["key-2"]).Value); } [Fact] public void DictionaryRoundTripTest2() { // dictionary with sub-dictionary wit DICTIONARYVAR value var dict1 = new DxfDictionary(); var dict2 = new DxfDictionary(); dict1["key-1"] = dict2; dict2["key-2"] = new DxfDictionaryVariable() { Value = "value-2" }; var file = new DxfFile(); file.Clear(); file.Header.Version = DxfAcadVersion.R2000; file.Objects.Add(dict1); var roundTrippedFile = RoundTrip(file); var roundTrippedDict1 = roundTrippedFile.Objects.OfType<DxfDictionary>().First(d => d.ContainsKey("key-1")); var roundTrippedDict2 = (DxfDictionary)roundTrippedDict1["key-1"]; Assert.Equal("value-2", ((DxfDictionaryVariable)roundTrippedDict2["key-2"]).Value); } [Fact] public void DictionaryRoundTripTest3() { // dictionary with default with DICTIONARYVAR values var dict = new DxfDictionaryWithDefault(); dict.DefaultObject = new DxfDictionaryVariable() { Value = "default-value" }; dict["key-1"] = new DxfDictionaryVariable() { Value = "value-1" }; var file = new DxfFile(); file.Clear(); file.Header.Version = DxfAcadVersion.R2000; file.Objects.Add(dict); var roundTrippedFile = RoundTrip(file); var roundTrippedDict = roundTrippedFile.Objects.OfType<DxfDictionaryWithDefault>().Single(); Assert.Equal("value-1", ((DxfDictionaryVariable)roundTrippedDict["key-1"]).Value); Assert.Equal("default-value", ((DxfDictionaryVariable)roundTrippedDict.DefaultObject).Value); } [Fact] public void ReadDimensionAssociativityTest() { var file = Parse( (0, "SECTION"), (2, "ENTITIES"), (0, "DIMENSION"), (5, "1"), (1, "dimension-text"), (70, 1), (0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS"), (0, "DIMASSOC"), (330, "1"), (1, "class-name"), (0, "ENDSEC"), (0, "EOF") ); var dimassoc = (Objects.DxfDimensionAssociativity)file.Objects.Last(); Assert.Equal("class-name", dimassoc.ClassName); var dim = (DxfAlignedDimension)dimassoc.Dimension; Assert.Equal(dimassoc, dim.Owner); Assert.Equal("dimension-text", dim.Text); } [Fact] public void ReadLayoutTest() { var layout = (DxfLayout)GenObject("LAYOUT", (1, "page-setup-name"), (100, "AcDbLayout"), (1, "layout-name") ); Assert.Equal("page-setup-name", layout.PageSetupName); Assert.Equal("layout-name", layout.LayoutName); } [Fact] public void ReadLayoutWithEmptyNameTest() { var layout = (DxfLayout)GenObject("LAYOUT", (1, "page-setup-name"), (100, "AcDbLayout"), (1, ""), (999, "comment line to ensure the value for the `1` code is an empty string") ); Assert.Equal("page-setup-name", layout.PageSetupName); Assert.Equal("", layout.LayoutName); } [Fact] public void WriteLayoutTest() { var layout = new DxfLayout(); layout.PageSetupName = "page-setup-name"; layout.LayoutName = "layout-name"; var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2000; file.Objects.Add(layout); var pairs = file.GetCodePairs(); // verify the plot settings were written var plotSettingsOffset = IndexOf(pairs, (100, "AcDbPlotSettings"), (1, "page-setup-name") ); Assert.True(plotSettingsOffset > 0); // verify the layout settings were written var layoutOffset = IndexOf(pairs, (100, "AcDbLayout"), (1, "layout-name") ); Assert.True(layoutOffset > 0); // verify that the layout settings were written after the plot settings Assert.True(layoutOffset > plotSettingsOffset); } [Fact] public void PlotSettingsPlotViewName() { // ensure invalid values aren't allowed Assert.Throws<InvalidOperationException>(() => new DxfPlotSettings(null)); Assert.Throws<InvalidOperationException>(() => new DxfPlotSettings("")); // ensure valid values are allowed _ = new DxfPlotSettings("some value"); } [Fact] public void LayoutName() { // ensure invalid values aren't allowed Assert.Throws<InvalidOperationException>(() => new DxfLayout(null, "layout name")); Assert.Throws<InvalidOperationException>(() => new DxfLayout("", "layout name")); Assert.Throws<InvalidOperationException>(() => new DxfLayout("plot view name", null)); Assert.Throws<InvalidOperationException>(() => new DxfLayout("plot view name", "")); // ensure valid values are allowed _ = new DxfLayout("plot view name", "layout name"); } [Fact] public void LayoutNameOverridesPlotViewName() { // artificially create a layout with a null PlotViewName, but valid LayoutName var layout = new DxfLayout(); layout.LayoutName = "layout name"; Assert.Equal("layout name", layout.PlotViewName); // ensure the base plot view name is honored layout = new DxfLayout("plot view name", "layout name"); Assert.Equal("layout name", layout.LayoutName); Assert.Equal("plot view name", layout.PlotViewName); } [Fact] public void ReadLightListTest() { var file = Parse( (0, "SECTION"), (2, "ENTITIES"), (0, "LIGHT"), (5, "42"), (1, "light-name"), (0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS"), (0, "LIGHTLIST"), (5, "DEADBEEF"), (90, 43), (90, 1), (5, "42"), (1, "can-be-anything"), (0, "ENDSEC"), (0, "EOF") ); var lightList = (DxfLightList)file.Objects.Last(); Assert.Equal(new DxfHandle(0xDEADBEEF), ((IDxfItemInternal)lightList).Handle); Assert.Equal(43, lightList.Version); Assert.Equal("light-name", lightList.Lights.Single().Name); } [Fact] public void WriteLightListTest() { var file = new DxfFile(); file.Clear(); file.Header.Version = DxfAcadVersion.R2007; file.Entities.Add(new DxfLight() { Name = "light-name" }); var lightList = new DxfLightList(); lightList.Version = 42; lightList.Lights.Add((DxfLight)file.Entities.Single()); file.Objects.Add(lightList); VerifyFileContains(file, (0, "LIGHTLIST"), (5, "#"), (100, "AcDbLightList"), (90, 42), (90, 1), (5, "#"), (1, "light-name") ); } [Fact] public void ReadMaterialTest() { var material = (DxfMaterial)GenObject("MATERIAL", (75, 1), (43, 1.0), (43, 2.0), (43, 3.0), (43, 4.0), (43, 5.0), (43, 6.0), (43, 7.0), (43, 8.0), (43, 9.0), (43, 10.0), (43, 11.0), (43, 12.0), (43, 13.0), (43, 14.0), (43, 15.0), (43, 16.0), (75, 2), (43, 10.0), (43, 20.0), (43, 30.0), (43, 40.0), (43, 50.0), (43, 60.0), (43, 70.0), (43, 80.0), (43, 90.0), (43, 100.0), (43, 110.0), (43, 120.0), (43, 130.0), (43, 140.0), (43, 150.0), (43, 160.0) ); Assert.Equal(DxfMapAutoTransformMethod.NoAutoTransform, material.DiffuseMapAutoTransformMethod); Assert.Equal(1.0, material.DiffuseMapTransformMatrix.M11); Assert.Equal(2.0, material.DiffuseMapTransformMatrix.M12); Assert.Equal(3.0, material.DiffuseMapTransformMatrix.M13); Assert.Equal(4.0, material.DiffuseMapTransformMatrix.M14); Assert.Equal(5.0, material.DiffuseMapTransformMatrix.M21); Assert.Equal(6.0, material.DiffuseMapTransformMatrix.M22); Assert.Equal(7.0, material.DiffuseMapTransformMatrix.M23); Assert.Equal(8.0, material.DiffuseMapTransformMatrix.M24); Assert.Equal(9.0, material.DiffuseMapTransformMatrix.M31); Assert.Equal(10.0, material.DiffuseMapTransformMatrix.M32); Assert.Equal(11.0, material.DiffuseMapTransformMatrix.M33); Assert.Equal(12.0, material.DiffuseMapTransformMatrix.M34); Assert.Equal(13.0, material.DiffuseMapTransformMatrix.M41); Assert.Equal(14.0, material.DiffuseMapTransformMatrix.M42); Assert.Equal(15.0, material.DiffuseMapTransformMatrix.M43); Assert.Equal(16.0, material.DiffuseMapTransformMatrix.M44); Assert.Equal(DxfMapAutoTransformMethod.ScaleToCurrentEntity, material.NormalMapAutoTransformMethod); Assert.Equal(10.0, material.NormalMapTransformMatrix.M11); Assert.Equal(20.0, material.NormalMapTransformMatrix.M12); Assert.Equal(30.0, material.NormalMapTransformMatrix.M13); Assert.Equal(40.0, material.NormalMapTransformMatrix.M14); Assert.Equal(50.0, material.NormalMapTransformMatrix.M21); Assert.Equal(60.0, material.NormalMapTransformMatrix.M22); Assert.Equal(70.0, material.NormalMapTransformMatrix.M23); Assert.Equal(80.0, material.NormalMapTransformMatrix.M24); Assert.Equal(90.0, material.NormalMapTransformMatrix.M31); Assert.Equal(100.0, material.NormalMapTransformMatrix.M32); Assert.Equal(110.0, material.NormalMapTransformMatrix.M33); Assert.Equal(120.0, material.NormalMapTransformMatrix.M34); Assert.Equal(130.0, material.NormalMapTransformMatrix.M41); Assert.Equal(140.0, material.NormalMapTransformMatrix.M42); Assert.Equal(150.0, material.NormalMapTransformMatrix.M43); Assert.Equal(160.0, material.NormalMapTransformMatrix.M44); } [Fact] public void ReadMLineStyleTest() { var mlineStyle = (DxfMLineStyle)GenObject("MLINESTYLE", (2, "<name>"), (3, "<description>"), (62, 1), (51, 99.0), (52, 100.0), (71, 2), (49, 3.0), (62, 3), (49, 4.0), (62, 4), (6, "quatro") ); Assert.Equal("<name>", mlineStyle.StyleName); Assert.Equal("<description>", mlineStyle.Description); Assert.Equal(1, mlineStyle.FillColor.RawValue); Assert.Equal(99.0, mlineStyle.StartAngle); Assert.Equal(100.0, mlineStyle.EndAngle); Assert.Equal(2, mlineStyle.Elements.Count); Assert.Equal(3.0, mlineStyle.Elements[0].Offset); Assert.Equal(3, mlineStyle.Elements[0].Color.RawValue); Assert.Null(mlineStyle.Elements[0].LineType); Assert.Equal(4.0, mlineStyle.Elements[1].Offset); Assert.Equal(4, mlineStyle.Elements[1].Color.RawValue); Assert.Equal("quatro", mlineStyle.Elements[1].LineType); } [Fact] public void WriteMLineStyleTest() { var mlineStyle = new DxfMLineStyle(); mlineStyle.StyleName = "<name>"; mlineStyle.Description = "<description>"; mlineStyle.FillColor = DxfColor.FromRawValue(1); mlineStyle.StartAngle = 99.9; mlineStyle.EndAngle = 100.0; mlineStyle.Elements.Add(new DxfMLineStyle.DxfMLineStyleElement() { Offset = 3.0, Color = DxfColor.FromRawValue(3), LineType = "tres" }); mlineStyle.Elements.Add(new DxfMLineStyle.DxfMLineStyleElement() { Offset = 4.0, Color = DxfColor.FromRawValue(4), LineType = "quatro" }); var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R14; file.Objects.Add(mlineStyle); VerifyFileContains(file, (2, "<name>"), (70, 0), (3, "<description>"), (62, 1), (51, 99.9), (52, 100.0), (71, 2), (49, 3.0), (62, 3), (6, "tres"), (49, 4.0), (62, 4), (6, "quatro") ); } [Fact] public void ReadSectionSettingsTest() { var settings = (DxfSectionSettings)GenObject("SECTIONSETTINGS", (5, "ABC"), (100, "AcDbSectionSettings"), (90, 42), (91, 1), (1, "SectionTypeSettings"), (90, 43), (91, 1), (92, 2), (330, "100"), (330, "101"), (331, "FF"), (1, "file-name"), (93, 2), (2, "SectionGeometrySettings"), (90, 1001), (91, 0), (92, 0), (63, 0), (8, ""), (6, ""), (40, 1.0), (1, ""), (370, 0), (70, 0), (71, 0), (72, 0), (2, ""), (41, 0.0), (42, 1.0), (43, 0.0), (3, "SectionGeometrySettingsEnd"), (90, 1002), (91, 0), (92, 0), (63, 0), (8, ""), (6, ""), (40, 1.0), (1, ""), (370, 0), (70, 0), (71, 0), (72, 0), (2, ""), (41, 0.0), (42, 1.0), (43, 0.0), (3, "SectionGeometrySettingsEnd"), (3, "SectionTypeSettingsEnd") ); Assert.Equal(42, settings.SectionType); var typeSettings = settings.SectionTypeSettings.Single(); Assert.Equal(43, typeSettings.SectionType); Assert.True(typeSettings.IsGenerationOption); Assert.Equal(new DxfHandle(0xFF), typeSettings.DestinationObjectHandle); Assert.Equal("file-name", typeSettings.DestinationFileName); Assert.Equal(2, typeSettings.SourceObjectHandles.Count); Assert.Equal(new DxfHandle(0x100), typeSettings.SourceObjectHandles[0]); Assert.Equal(new DxfHandle(0x101), typeSettings.SourceObjectHandles[1]); Assert.Equal(2, typeSettings.GeometrySettings.Count); Assert.Equal(1001, typeSettings.GeometrySettings[0].SectionType); Assert.Equal(1002, typeSettings.GeometrySettings[1].SectionType); } [Fact] public void WriteSectionSettingsTest() { var settings = new DxfSectionSettings(); settings.SectionType = 42; var typeSettings = new DxfSectionTypeSettings() { SectionType = 43, IsGenerationOption = true, DestinationObjectHandle = new DxfHandle(0xFF), DestinationFileName = "file-name", }; typeSettings.SourceObjectHandles.Add(new DxfHandle(0x100)); typeSettings.SourceObjectHandles.Add(new DxfHandle(0x101)); typeSettings.GeometrySettings.Add(new DxfSectionGeometrySettings() { SectionType = 1001 }); typeSettings.GeometrySettings.Add(new DxfSectionGeometrySettings() { SectionType = 1002 }); settings.SectionTypeSettings.Add(typeSettings); var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2007; file.Objects.Add(settings); VerifyFileContains(file, (100, "AcDbSectionSettings"), (90, 42), (91, 1), (1, "SectionTypeSettings"), (90, 43), (91, 1), (92, 2), (330, "100"), (330, "101"), (331, "FF"), (1, "file-name"), (93, 2), (2, "SectionGeometrySettings"), (90, 1001), (91, 0), (92, 0), (63, 0), (8, ""), (6, ""), (40, 1.0), (1, ""), (370, 0), (70, 0), (71, 0), (72, 0), (2, ""), (41, 0.0), (42, 1.0), (43, 0.0), (3, "SectionGeometrySettingsEnd"), (90, 1002), (91, 0), (92, 0), (63, 0), (8, ""), (6, ""), (40, 1.0), (1, ""), (370, 0), (70, 0), (71, 0), (72, 0), (2, ""), (41, 0.0), (42, 1.0), (43, 0.0), (3, "SectionGeometrySettingsEnd"), (3, "SectionTypeSettingsEnd") ); } [Fact] public void ReadSortentsTableTest() { var file = Parse( (0, "SECTION"), (2, "ENTITIES"), (0, "POINT"), (5, "42"), (10, 1.0), (20, 2.0), (30, 3.0), (0, "POINT"), (5, "43"), (10, 4.0), (20, 5.0), (30, 6.0), (0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS"), (0, "SORTENTSTABLE"), (331, "42"), (5, "43"), (0, "ENDSEC"), (0, "EOF") ); var sortents = (DxfSortentsTable)file.Objects.Last(); Assert.Equal(new DxfPoint(1, 2, 3), ((DxfModelPoint)sortents.Entities.Single()).Location); Assert.Equal(new DxfPoint(4, 5, 6), ((DxfModelPoint)sortents.SortItems.Single()).Location); } [Fact] public void WriteSortentsTableTest() { var file = new DxfFile(); file.Clear(); file.Header.Version = DxfAcadVersion.R14; file.Entities.Add(new DxfModelPoint(new DxfPoint(1, 2, 3))); file.Entities.Add(new DxfModelPoint(new DxfPoint(4, 5, 6))); var sortents = new DxfSortentsTable(); sortents.Entities.Add(file.Entities.First()); sortents.SortItems.Add(file.Entities.Skip(1).First()); file.Objects.Add(sortents); VerifyFileContains(file, (0, "POINT"), (5, "#") ); VerifyFileContains(file, (0, "SORTENTSTABLE"), (5, "#"), (100, "AcDbSortentsTable"), (331, "#"), (5, "#") ); } [Fact] public void ReadSpatialIndexTest() { var si = (DxfSpatialIndex)GenObject("SPATIAL_INDEX", (100, "AcDbIndex"), (40, 2451544.91568287), // from Autodesk spec: 2451544.91568287 = December 31, 1999, 9:58:35 pm. (100, "AcDbSpatialIndex"), (40, 1.0), (40, 2.0), (40, 3.0) ); Assert.Equal(new DateTime(1999, 12, 31, 21, 58, 35), si.Timestamp); AssertArrayEqual(new[] { 1.0, 2.0, 3.0 }, si.Values.ToArray()); } [Fact] public void WriteSpatialIndexTest() { var si = new DxfSpatialIndex(); si.Timestamp = new DateTime(1999, 12, 31, 21, 58, 35); si.Values.Add(1.0); si.Values.Add(2.0); si.Values.Add(3.0); EnsureFileContainsObject(si, DxfAcadVersion.R2000, (100, "AcDbIndex"), (40, 2451544.9156828704), // from Autodesk spec: 2451544.91568287(04) = December 31, 1999, 9:58:35 pm. (100, "AcDbSpatialIndex"), (40, 1.0), (40, 2.0), (40, 3.0) ); } [Fact] public void ReadSunStudyTest() { // with subset var sun = (DxfSunStudy)GenObject("SUNSTUDY", (290, 1), (73, 3), (290, 42), (290, 43), (290, 44) ); Assert.True(sun.UseSubset); Assert.Equal(3, sun.Hours.Count); Assert.Equal(42, sun.Hours[0]); Assert.Equal(43, sun.Hours[1]); Assert.Equal(44, sun.Hours[2]); // without subset sun = (DxfSunStudy)GenObject("SUNSTUDY", (73, 3), (290, 42), (290, 43), (290, 44) ); Assert.False(sun.UseSubset); Assert.Equal(3, sun.Hours.Count); Assert.Equal(42, sun.Hours[0]); Assert.Equal(43, sun.Hours[1]); Assert.Equal(44, sun.Hours[2]); } [Fact] public void WriteSunStudyTest() { var sun = new DxfSunStudy(); sun.Hours.Add(42); sun.Hours.Add(43); sun.Hours.Add(44); var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2013; file.Objects.Add(sun); VerifyFileContains(file, (0, "SUNSTUDY"), (5, "#"), (100, "AcDbSunStudy"), (90, 0), (1, ""), (2, ""), (70, 0), (3, ""), (290, false), (4, ""), (291, false), (91, 0), (292, false), (73, 3), (290, 42), (290, 43), (290, 44), (74, 0), (75, 0), (76, 0), (77, 0), (40, 0.0), (293, false), (294, false) ); // verify writing as binary doesn't crash using (var ms = new MemoryStream()) { file.Save(ms, asText: false); } } [Fact] public void ReadTableStyleTest() { var table = (DxfTableStyle)GenObject("TABLESTYLE", (5, "123"), (100, "AcDbTableStyle"), (280, 0), (3, ""), (70, 0), (71, 0), (40, 0.06), (41, 0.06), (280, 0), (281, 0), (7, "one"), (140, 0.0), (170, 0), (62, 0), (63, 7), (283, 0), (90, 0), (91, 0), (274, 0), (275, 0), (276, 0), (277, 0), (278, 0), (279, 0), (284, 1), (285, 1), (286, 1), (287, 1), (288, 1), (289, 1), (64, 0), (65, 0), (66, 0), (67, 0), (68, 0), (69, 0), (7, "two"), (140, 0.0), (170, 0), (62, 0), (63, 7), (283, 0), (90, 0), (91, 0), (274, 0), (275, 0), (276, 0), (277, 0), (278, 0), (279, 0), (284, 1), (285, 1), (286, 1), (287, 1), (288, 1), (289, 1), (64, 0), (65, 0), (66, 0), (67, 0), (68, 0), (69, 0) ); Assert.Equal(2, table.CellStyles.Count); Assert.Equal("one", table.CellStyles[0].Name); Assert.Equal("two", table.CellStyles[1].Name); } [Fact] public void WriteTableStyleTest() { var table = new DxfTableStyle(); table.CellStyles.Add(new DxfTableCellStyle() { Name = "one" }); table.CellStyles.Add(new DxfTableCellStyle() { Name = "two" }); var file = new DxfFile(); file.Header.Version = DxfAcadVersion.R2004; file.Objects.Add(table); VerifyFileContains(file, (0, "TABLESTYLE"), (5, "#"), (100, "AcDbTableStyle"), (3, ""), (70, 0), (71, 0), (40, 0.06), (41, 0.06), (280, 0), (281, 0), (7, "one"), (140, 0.0), (170, 0), (62, 0), (63, 7), (283, 0), (90, 0), (91, 0), (274, 0), (275, 0), (276, 0), (277, 0), (278, 0), (279, 0), (284, 1), (285, 1), (286, 1), (287, 1), (288, 1), (289, 1), (64, 0), (65, 0), (66, 0), (67, 0), (68, 0), (69, 0), (7, "two"), (140, 0.0), (170, 0), (62, 0), (63, 7), (283, 0), (90, 0), (91, 0), (274, 0), (275, 0), (276, 0), (277, 0), (278, 0), (279, 0), (284, 1), (285, 1), (286, 1), (287, 1), (288, 1), (289, 1), (64, 0), (65, 0), (66, 0), (67, 0), (68, 0), (69, 0) ); } [Fact] public void ReadObjectWithUnterminatedXData() { // dictionary value with XDATA var file = Section("OBJECTS", (0, "ACDBPLACEHOLDER"), (1001, "IxMilia.Dxf"), (0, "ACDBPLACEHOLDER"), (1001, "IxMilia.Dxf") ); Assert.Equal(2, file.Objects.Count); Assert.IsType<DxfPlaceHolder>(file.Objects[0]); Assert.IsType<DxfPlaceHolder>(file.Objects[1]); } [Fact] public void ReadXRecordWithMultipleXDataTest1() { var xrecord = (DxfXRecordObject)GenObject("XRECORD", (102, "{ACAD_REACTORS_1"), (330, "111"), (102, "}"), (102, "{ACAD_REACTORS_2"), (330, "222"), (102, "}"), (102, "{ACAD_REACTORS_3"), (330, "333"), (102, "}"), (100, "AcDbXrecord"), (280, 1), (102, "VTR_0.000_0.000_1.000_1.000_VISUALSTYLE"), (340, "195"), (102, "VTR_0.000_0.000_1.000_1.000_GRIDDISPLAY"), (70, 3), (102, "VTR_0.000_0.000_1.000_1.000_GRIDMAJOR"), (70, 5), (102, "VTR_0.000_0.000_1.000_1.000_DEFAULTLIGHTING"), (280, 1), (102, "VTR_0.000_0.000_1.000_1.000_DEFAULTLIGHTINGTYPE"), (70, 1), (102, "VTR_0.000_0.000_1.000_1.000_BRIGHTNESS"), (141, 0.0), (102, "VTR_0.000_0.000_1.000_1.000_CONTRAST"), (142, 0.0) ); Assert.Equal(3, xrecord.ExtensionDataGroups.Count); Assert.Equal("ACAD_REACTORS_1", xrecord.ExtensionDataGroups[0].GroupName); Assert.Equal("ACAD_REACTORS_2", xrecord.ExtensionDataGroups[1].GroupName); Assert.Equal("ACAD_REACTORS_3", xrecord.ExtensionDataGroups[2].GroupName); Assert.Equal(DxfDictionaryDuplicateRecordHandling.KeepExisting, xrecord.DuplicateRecordHandling); Assert.Equal(14, xrecord.DataPairs.Count); Assert.Equal(102, xrecord.DataPairs[0].Code); Assert.Equal("VTR_0.000_0.000_1.000_1.000_VISUALSTYLE", xrecord.DataPairs[0].StringValue); } [Fact] public void ReadXRecordWithMultipleXDataTest2() { // reads an XRECORD object that hasn't specified it's 280 code pair for duplicate record handling var xrecord = (DxfXRecordObject)GenObject("XRECORD", (100, "AcDbXrecord"), (102, "VTR_0.000_0.000_1.000_1.000_VISUALSTYLE"), (340, "195"), (102, "VTR_0.000_0.000_1.000_1.000_GRIDDISPLAY"), (70, 3), (102, "VTR_0.000_0.000_1.000_1.000_GRIDMAJOR"), (70, 5), (102, "VTR_0.000_0.000_1.000_1.000_DEFAULTLIGHTING"), (280, 1), (102, "VTR_0.000_0.000_1.000_1.000_DEFAULTLIGHTINGTYPE"), (70, 1), (102, "VTR_0.000_0.000_1.000_1.000_BRIGHTNESS"), (141, 0.0), (102, "VTR_0.000_0.000_1.000_1.000_CONTRAST"), (142, 0.0) ); Assert.Equal(0, xrecord.ExtensionDataGroups.Count); Assert.Equal(14, xrecord.DataPairs.Count); Assert.Equal(102, xrecord.DataPairs[6].Code); Assert.Equal("VTR_0.000_0.000_1.000_1.000_DEFAULTLIGHTING", xrecord.DataPairs[6].StringValue); Assert.Equal(1, xrecord.DataPairs[7].ShortValue); } [Fact] public void ReadDictionaryWithEveryEntityTest() { // read a dictionary with a reference to every entity var assembly = typeof(DxfFile).GetTypeInfo().Assembly; foreach (var type in assembly.GetTypes()) { // dimensions are hard if (IsDxfEntityOrDerived(type) && type.GetTypeInfo().BaseType != typeof(DxfDimensionBase)) { var ctor = type.GetConstructor(Type.EmptyTypes); if (ctor != null) { var ent = (DxfEntity)ctor.Invoke(new object[0]); var file = Parse( (0, "SECTION"), (2, "ENTITIES"), (0, ent.EntityTypeString), (5, "AAAA"), (0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS"), (0, "DICTIONARY"), (3, "the-entity"), (350, "AAAA"), (0, "ENDSEC"), (0, "EOF") ); var dict = (DxfDictionary)file.Objects.Single(); var parsedEntity = dict["the-entity"] as DxfEntity; Assert.Equal(type, parsedEntity.GetType()); } } } } [Fact] public void WriteAllDefaultObjectsTest() { var file = new DxfFile(); var assembly = typeof(DxfFile).GetTypeInfo().Assembly; foreach (var type in assembly.GetTypes()) { if (IsDxfObjectOrDerived(type)) { var ctor = type.GetConstructor(Type.EmptyTypes); if (ctor != null) { // add the object with its default initialized values var obj = (DxfObject)ctor.Invoke(new object[0]); file.Objects.Add(obj); // add the entity with its default values and 2 items added to each List<T> collection obj = (DxfObject)ctor.Invoke(new object[0]); foreach (var property in type.GetProperties().Where(p => IsListOfT(p.PropertyType))) { var itemType = property.PropertyType.GenericTypeArguments.Single(); var itemValue = itemType.GetTypeInfo().IsValueType ? Activator.CreateInstance(itemType) : null; var addMethod = property.PropertyType.GetMethod("Add"); var propertyValue = property.GetValue(obj); addMethod.Invoke(propertyValue, new object[] { itemValue }); addMethod.Invoke(propertyValue, new object[] { itemValue }); } // add an object with all non-indexer properties set to `default(T)` obj = (DxfObject)SetAllPropertiesToDefault(ctor.Invoke(new object[0])); file.Objects.Add(obj); } } } // write each version of the objects with default versions foreach (var version in new[] { DxfAcadVersion.R10, DxfAcadVersion.R11, DxfAcadVersion.R12, DxfAcadVersion.R13, DxfAcadVersion.R14, DxfAcadVersion.R2000, DxfAcadVersion.R2004, DxfAcadVersion.R2007, DxfAcadVersion.R2010, DxfAcadVersion.R2013 }) { file.Header.Version = version; using (var ms = new MemoryStream()) { file.Save(ms); } } } private static bool IsDxfEntityOrDerived(Type type) { return IsTypeOrDerived(type, typeof(DxfEntity)); } private static bool IsDxfObjectOrDerived(Type type) { return IsTypeOrDerived(type, typeof(DxfObject)); } private static bool IsTypeOrDerived(Type type, Type expectedType) { if (type == expectedType) { return true; } if (type.GetTypeInfo().BaseType != null) { return IsTypeOrDerived(type.GetTypeInfo().BaseType, expectedType); } return false; } } }
// 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 Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ApiOperations. /// </summary> public static partial class ApiOperationsExtensions { /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<ApiContract> ListByService(this IApiOperations operations, string resourceGroupName, string serviceName, ODataQuery<ApiContract> odataQuery = default(ODataQuery<ApiContract>)) { return ((IApiOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApiContract>> ListByServiceAsync(this IApiOperations operations, string resourceGroupName, string serviceName, ODataQuery<ApiContract> odataQuery = default(ODataQuery<ApiContract>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the details of the API specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> public static ApiContract Get(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId) { return operations.GetAsync(resourceGroupName, serviceName, apiId).GetAwaiter().GetResult(); } /// <summary> /// Gets the details of the API specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApiContract> GetAsync(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates new or updates existing specified API of the API Management service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the Api Entity. For Create Api Etag should not be specified. For /// Update Etag should match the existing Entity or it can be * for /// unconditional update. /// </param> public static ApiContract CreateOrUpdate(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, ApiCreateOrUpdateParameter parameters, string ifMatch = default(string)) { return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, apiId, parameters, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Creates new or updates existing specified API of the API Management service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the Api Entity. For Create Api Etag should not be specified. For /// Update Etag should match the existing Entity or it can be * for /// unconditional update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApiContract> CreateOrUpdateAsync(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, ApiCreateOrUpdateParameter parameters, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the specified API of the API Management service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// API Update Contract parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API entity. ETag should match the current entity state in the /// header response of the GET request or it should be * for unconditional /// update. /// </param> public static void Update(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, ApiUpdateContract parameters, string ifMatch) { operations.UpdateAsync(resourceGroupName, serviceName, apiId, parameters, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Updates the specified API of the API Management service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// API Update Contract parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API entity. ETag should match the current entity state in the /// header response of the GET request or it should be * for unconditional /// update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, ApiUpdateContract parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Deletes the specified API of the API Management service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Entity. ETag should match the current entity state from the /// header response of the GET request or it should be * for unconditional /// update. /// </param> public static void Delete(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, string ifMatch) { operations.DeleteAsync(resourceGroupName, serviceName, apiId, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified API of the API Management service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Entity. ETag should match the current entity state from the /// header response of the GET request or it should be * for unconditional /// update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IApiOperations operations, string resourceGroupName, string serviceName, string apiId, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </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<ApiContract> ListByServiceNext(this IApiOperations operations, string nextPageLink) { return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all APIs of the API Management service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-create-apis" /> /// </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<ApiContract>> ListByServiceNextAsync(this IApiOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using Opswat.Metadefender.Core.Client; using Opswat.Metadefender.Core.Client.Exceptions; using Opswat.Metadefender.Core.Client.Responses; using System; using System.Collections.Generic; using System.IO; namespace Opswat.Metadefender.Core.ClientExample { public class Example { public static void Main(string[] args) { Dictionary<string, string> arguments = ProcessArguments(args); string apiUrl = arguments.Get("-h"); string apiUser = arguments.Get("-u"); string apiUserPass = arguments.Get("-p"); string action = arguments.Get("-a"); string file = arguments.Get("-f"); string hash = arguments.Get("-m"); if (file != null && file.Length != 0) { if ("scan".Equals(action)) { ScanFile(apiUrl, file); } else if ("scan_sync".Equals(action)) { ScanFileSync(apiUrl, file); } } if (hash != null && hash.Length != 0) { FetchScanResultByHash(apiUrl, hash); } if ("info".Equals(action)) { ShowApiInfo(apiUrl, apiUser, apiUserPass); } } private static void ScanFileSync(string apiUrl, string file) { MetadefenderCoreClient metadefenderCoreClient = new MetadefenderCoreClient(apiUrl); try { Stream inputStream = File.Open(file, FileMode.Open); FileScanResult result = metadefenderCoreClient.ScanFileSync(inputStream, new FileScanOptions().SetFileName(GetFileNameFromPath(file)), 200, 1000 * 30, 5000); Console.WriteLine("File scan finished with result: " + result.process_info.result); if (result.process_info.post_processing != null) { Console.WriteLine("post processing: " + result.process_info.post_processing); } } catch (MetadefenderClientException e) { Console.WriteLine("Error during file scan: " + e.GetDetailedMessage()); } catch (FileNotFoundException e) { Console.WriteLine("File not found: " + file + " Exception: " + e.Message); } } private static void ScanFile(string apiUrl, string file) { MetadefenderCoreClient metadefenderCoreClient = new MetadefenderCoreClient(apiUrl); // This is optional: using custom HttpConnector metadefenderCoreClient.SetHttpConnector(new CustomHttpConnector()); try { Stream inputStream = File.Open(file, FileMode.Open); string dataId = metadefenderCoreClient.ScanFile(inputStream, new FileScanOptions().SetFileName(GetFileNameFromPath(file))); Console.WriteLine("File scan started. The data id is: " + dataId); } catch (MetadefenderClientException e) { Console.WriteLine("Error during file scan: " + e.GetDetailedMessage()); } catch (FileNotFoundException e) { Console.WriteLine("File not found: " + file + " Exception: " + e.Message); } } private static void FetchScanResultByHash(string apiUrl, string hash) { MetadefenderCoreClient metadefenderCoreClient = new MetadefenderCoreClient(apiUrl); try { FileScanResult result = metadefenderCoreClient.FetchScanResultByHash(hash); Console.WriteLine("Fetch result by file hash: " + result.process_info.result); if (result.process_info.post_processing != null) { Console.WriteLine("post processing: " + result.process_info.post_processing); } } catch (MetadefenderClientException e) { Console.WriteLine("Error during fetch scan by hash: " + e.GetDetailedMessage()); } } private static void ShowApiInfo(string apiUrl, string apiUser, string apiUserPass) { MetadefenderCoreClient metadefenderCoreClient; try { metadefenderCoreClient = new MetadefenderCoreClient(apiUrl, apiUser, apiUserPass); metadefenderCoreClient.SetHttpConnector(new CustomHttpConnector()); Console.WriteLine("Metadefender client created. Session id is: " + metadefenderCoreClient.GetSessionId()); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot login to this API. Error message: " + e.GetDetailedMessage()); return; } try { License license = metadefenderCoreClient.GetCurrentLicenseInformation(); Console.WriteLine("Licensed to: " + license.licensed_to); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot get license details: " + e.GetDetailedMessage()); } try { List<EngineVersion> result = metadefenderCoreClient.GetEngineVersions(); Console.WriteLine("Fetched engine/database versions: " + result.Count); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot get engine/database versions: " + e.GetDetailedMessage()); } try { ApiVersion apiVersion = metadefenderCoreClient.GetVersion(); Console.WriteLine("Api endpoint apiVersion: " + apiVersion.version); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot get api endpoint version: " + e.GetDetailedMessage()); } try { List<ScanRule> scanRules = metadefenderCoreClient.GetAvailableScanRules(); Console.WriteLine("Available scan rules: " + scanRules.Count); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot get available scan rules: " + e.GetDetailedMessage()); } try { metadefenderCoreClient.Logout(); Console.WriteLine("Client successfully logged out."); } catch (MetadefenderClientException e) { Console.WriteLine("Cannot log out: " + e.GetDetailedMessage()); } } ////// Util methods public static void PrintUsage(string message) { if (message != null) { Console.WriteLine(message); } Console.WriteLine("\n\n\nExample usages: \n\n" + " Example -h http://localhost:8008 -a scan -f fileToScan\n" + " Example -h http://localhost:8008 -u yourUser -p yourPass -a info\n\n\n" + "\t -h host Required\n" + "\t -u username Required if action is 'info'\n" + "\t -p password Required if action is 'info'\n" + "\t -a action to do Required (scan|scan_sync|info|hash)\n" + "\t -f path to file to scan Required if action is (scan|scan_sync)\n" + "\t -m hash (md5|sha1|sha256) Required if action is (hash)" + "\n\n\n"); } /** * Processing, and validating command line arguments * @param args command line arguments * @return processed parameters */ private static Dictionary<string, string> ProcessArguments(string[] args) { Dictionary<string, string> parameters = new Dictionary<string, string>(); List<string> switches = new List<string>() {"-h", "-u", "-p", "-a", "-f", "-m"}; foreach (string switchStr in switches) { int index = GetSwitchIndex(args, switchStr); if (index >= 0) { if (args.Length > index + 1) { parameters[switchStr] = args[index + 1]; } else { PrintUsage("Missing value for switch: " + switchStr); Environment.Exit(1); } } } if (!parameters.ContainsKey("-h")) { PrintUsage("-h is required"); Environment.Exit(1); } if (!parameters.ContainsKey("-a")) { PrintUsage("-a is required"); Environment.Exit(1); } string action = parameters["-a"]; List<string> allowedActions = new List<string>() {"scan", "scan_sync", "info", "hash"}; if (!allowedActions.Contains(action)) { PrintUsage("Invalid action: " + action); Environment.Exit(1); } if ("info".Equals(action)) { if (!parameters.ContainsKey("-u")) { PrintUsage("-u is required"); Environment.Exit(1); } if (!parameters.ContainsKey("-p")) { PrintUsage("-p is required"); Environment.Exit(1); } } if ("scan".Equals(action) || "scan_sync".Equals(action)) { if (!parameters.ContainsKey("-f")) { PrintUsage("-f is required"); Environment.Exit(1); } } if ("hash".Equals(action)) { if (!parameters.ContainsKey("-m")) { PrintUsage("-m is required"); Environment.Exit(1); } } return parameters; } private static int GetSwitchIndex(string[] args, string switchStr) { for (int i = 0; i < args.Length; i++) { if (switchStr.Equals(args[i])) { return i; } } return -1; } private static string GetFileNameFromPath(string file) { string[] parts; if (file.Contains("/")) { parts = file.Split('/'); } else if (file.Contains("\\")) { parts = file.Split('\\'); } else { return file; } if (parts.Length > 1) { return parts[parts.Length - 1]; } return file; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Globalization; using System.Web.UI.WebControls; using Subtext.Extensibility.Interfaces; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Web.Admin.Commands; namespace Subtext.Web.Admin.Pages { // TODO: import - reconcile duplicates // TODO: CheckAll client-side, confirm bulk delete (add cmd) public partial class EditKeyWords : AdminOptionsPage { private const string VSKEY_KEYWORDID = "LinkID"; private bool _isListHidden = false; private int _resultsPageNumber; #region Accessors public int KeyWordID { get { if (ViewState[VSKEY_KEYWORDID] != null) { return (int)ViewState[VSKEY_KEYWORDID]; } else { return NullValue.NullInt32; } } set { ViewState[VSKEY_KEYWORDID] = value; } } #endregion private new void Page_Load(object sender, EventArgs e) { //BindLocalUI(); //no need to call if (!IsPostBack) { if (null != Request.QueryString[Keys.QRYSTR_PAGEINDEX]) { _resultsPageNumber = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_PAGEINDEX]); } resultsPager.PageSize = Preferences.ListingItemCount; resultsPager.PageIndex = _resultsPageNumber; BindList(); //BindImportExportCategories(); } } /* private void BindLocalUI() { //wasn't working. I have added a button to GUI for this. - GY LinkButton lkbNewLink = Utilities.CreateLinkButton("New KeyWord"); lkbNewLink.Click += new System.EventHandler(lkbNewKeyWord_Click); lkbNewLink.CausesValidation =false; PageContainer.AddToActions(lkbNewLink); } */ private void BindList() { Edit.Visible = false; IPagedCollection<KeyWord> selectionList = Repository.GetPagedKeyWords(_resultsPageNumber, resultsPager.PageSize); if (selectionList.Count > 0) { resultsPager.ItemCount = selectionList.MaxItems; rprSelectionList.DataSource = selectionList; rprSelectionList.DataBind(); } } private void BindLinkEdit() { KeyWord kw = Repository.GetKeyWord(KeyWordID); Results.Visible = false; Edit.Visible = true; txbTitle.Text = kw.Title; txbUrl.Text = kw.Url; txbWord.Text = kw.Word; txbRel.Text = kw.Rel; txbText.Text = kw.Text; chkFirstOnly.Checked = kw.ReplaceFirstTimeOnly; chkCaseSensitive.Checked = kw.CaseSensitive; if (AdminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, "Editing KeyWord \"{0}\"", kw.Title); AdminMasterPage.Title = title; } } private void UpdateLink() { string successMessage = Constants.RES_SUCCESSNEW; try { var keyword = new KeyWord { Title = txbTitle.Text, Url = txbUrl.Text, Text = txbText.Text, ReplaceFirstTimeOnly = chkFirstOnly.Checked, CaseSensitive = chkCaseSensitive.Checked, Rel = txbRel.Text, Word = txbWord.Text }; if (KeyWordID > 0) { successMessage = Constants.RES_SUCCESSEDIT; keyword.Id = KeyWordID; Repository.UpdateKeyWord(keyword); } else { KeyWordID = Repository.InsertKeyWord(keyword); } if (KeyWordID > 0) { BindList(); Messages.ShowMessage(successMessage); } else { Messages.ShowError(Constants.RES_FAILUREEDIT + " There was a baseline problem posting your KeyWord."); } } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); } finally { Results.Visible = true; } } private void ResetPostEdit(bool showEdit) { KeyWordID = NullValue.NullInt32; Results.Visible = !showEdit; Edit.Visible = showEdit; txbTitle.Text = string.Empty; txbText.Text = string.Empty; txbUrl.Text = string.Empty; txbRel.Text = string.Empty; txbWord.Text = string.Empty; chkFirstOnly.Checked = false; chkCaseSensitive.Checked = false; } private void ConfirmDelete(int keywordId, string keyword) { var command = new DeleteKeyWordCommand(Repository, keywordId, keyword) { ExecuteSuccessMessage = String.Format(CultureInfo.CurrentCulture, "Keyword '{0}' deleted", keyword) }; Messages.ShowMessage(command.Execute()); BindList(); } // REFACTOR public string CheckHiddenStyle() { if (_isListHidden) { return Constants.CSSSTYLE_HIDDEN; } else { return String.Empty; } } protected void rprSelectionList_ItemCommand(object source, RepeaterCommandEventArgs e) { switch (e.CommandName.ToLower(CultureInfo.InvariantCulture)) { case "edit": KeyWordID = Convert.ToInt32(e.CommandArgument); BindLinkEdit(); break; case "delete": int id = Convert.ToInt32(e.CommandArgument); KeyWord kw = Repository.GetKeyWord(id); ConfirmDelete(id, kw.Word); break; default: break; } } protected void lkbCancel_Click(object sender, EventArgs e) { ResetPostEdit(false); } protected void lkbPost_Click(object sender, EventArgs e) { UpdateLink(); } protected void btnCreate_Click(object sender, EventArgs e) { ResetPostEdit(true); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }
// // HeaderCollection.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright 2012 Rdio, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace Vernacular.Potato { public sealed class HeaderCollection : Container<Header>, INotifyCollectionChanged, IList<Header> { private ObservableCollection<Header> headers = new ObservableCollection<Header> (); public override event NotifyCollectionChangedEventHandler CollectionChanged { add { headers.CollectionChanged += value; } remove { headers.CollectionChanged -= value; } } private Header Find (Header header) { int index; return Find (header.Name, out index); } private Header Find (string header) { int index; return Find (header, out index); } private Header Find (Header header, out int index) { return Find (header.Name, out index); } private Header Find (string headerName, out int index) { int i = 0; foreach (var header in this) { if (String.Equals (header.Name, headerName, StringComparison.InvariantCultureIgnoreCase)) { index = i; return header; } i++; } index = -1; return null; } public Header this [int index] { get { return headers [index]; } set { headers [index] = value; } } public string this [string headerName] { get { var header = Find (headerName); return header == null ? null : header.Value; } set { var header = Find (headerName); if (header == null) { Add (headerName, value); } else { header.Value = value; } } } public void Insert (int index, Header header) { if (Contains (header)) { throw new Exception ("header already exists"); } headers.Insert (index, header); } public int IndexOf (Header header) { int index; Find (header, out index); return index; } public int IndexOf (string headerName) { int index; Find (headerName, out index); return index; } public void Add (string name, string value) { Add (new Header { Name = name, Value = value }); } public void Add (Header header) { if (Contains (header)) { throw new Exception ("header already exists; use this[string] to replace"); } headers.Add (header); } public bool Remove (Header header) { var found = Find (header); if (found == null) { return false; } return headers.Remove (found); } public bool Remove (string headerName) { var found = Find (headerName); if (found == null) { return false; } return headers.Remove (found); } public void RemoveAt (int index) { headers.RemoveAt (index); } public bool Contains (Header header) { return Find (header) != null; } public bool Contains (string headerName) { return Find (headerName) != null; } public void Clear () { headers.Clear (); } public bool IsReadOnly { get { return false; } } public int Count { get { return headers.Count; } } public void CopyTo (Header [] array, int index) { headers.CopyTo (array, index); } public override string Generate () { var builder = new StringBuilder (); foreach (var header in headers) { if (header.HasValue) { builder.Append (header.Generate ()); builder.Append ('\n'); } } if (builder.Length > 0) { builder.Length--; } return builder.ToString (); } public override IEnumerator<Header> GetEnumerator () { foreach (var header in headers) { yield return header; } } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } public void PopulateWithRequiredHeaders () { if (!Contains ("Project-Id-Version")) { Add ("Project-Id-Version", "PACKAGE VERSION"); } if (!Contains ("PO-Revision-Date")) { Add ("PO-Revision-Date", DateTime.Now.ToString (@"yyyy\-MM\-dd HH\:mmzz", System.Globalization.CultureInfo.InvariantCulture) ); } if (!Contains ("Last-Translator")) { Add ("Last-Translator", String.Empty); } if (!Contains ("Language-Team")) { Add ("Language-Team", String.Empty); } if (!Contains ("MIME-Version")) { Add ("MIME-Version", "1.0"); } if (!Contains ("Content-Type")) { Add ("Content-Type", "text/plain; charset=UTF-8"); } if (!Contains ("Content-Transfer-Encoding")) { Add ("Content-Transfer-Encoding", "8bit"); } if (!Contains ("Plural-Forms")) { Add ("Plural-Forms", "nplurals=2; plural=(n != 1);"); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults; using TestRunContext = Microsoft.TeamFoundation.TestClient.PublishTestResults.TestRunContext; using Moq; using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.TestResults { public class TrxReaderTests : IDisposable { private string _trxResultFile; private Mock<IExecutionContext> _ec; [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithoutTestNamesAreSkipped() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"\" outcome=\"Passed\" />" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod name=\"\" />" + "<TestMethod />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutTestNames.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(0, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void PendingOutcomeTreatedAsNotExecuted() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Pending\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "NotExecuted"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ThereAreNoResultsWithInvalidGuid() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"asdf\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"asdf\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"asdf\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"asdf\" testId = \"asdf\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"asfd\" outcome = \"Failed\" testListId = \"asdf\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "</Results></TestRun>"; _trxResultFile = "ResultsWithInvalidGuid.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(1, runData.Results.Length); Assert.Equal(null, runData.Results[0].AutomatedTestId); Assert.Equal(null, runData.Results[0].AutomatedTestTypeId); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithInvalidStartDate() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"asdf\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"asdf\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"asdf\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"asdf\" testId = \"asdf\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"0001-01-01T00:00:00.0000000-08:00\" endTime = \"0001-01-01T00:00:00.0000000-08:00\" testType = \"asfd\" outcome = \"Failed\" testListId = \"asdf\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "</Results></TestRun>"; _trxResultFile = "ResultsWithInvalidGuid.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(1, runData.Results.Length); Assert.Equal(true, DateTime.Compare((DateTime) SqlDateTime.MinValue, runData.Results[0].StartedDate) < 0); Assert.Equal(true, DateTime.Compare((DateTime) SqlDateTime.MinValue, runData.Results[0].CompletedDate) < 0); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ResultsWithoutMandatoryFieldsAreSkipped() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"\" outcome=\"Passed\" />" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod name=\"\" />" + "<TestMethod />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutMandatoryFields.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.NotNull(runData); Assert.Equal(0, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValues() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.Results[0].StartedDate, StartedDate); TimeSpan Duration; TimeSpan.TryParse("00:00:00.0834563", out Duration); Assert.Equal(runData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(runData.Results[0].CompletedDate, CompletedDate); Assert.Equal(runData.Name, "VSTest Test Run debug any cpu"); Assert.Equal(runData.State, "InProgress"); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "Failed"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(runData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(runData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(runData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(runData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(runData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(runData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(runData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(runData.Results[0].Priority.ToString(), "1"); Assert.Equal(runData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(runData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(runData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(runData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(runData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(runData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(runData.Results[2].ComputerName, "random-DT"); Assert.Equal(runData.Results[2].AutomatedTestType, "OrderedTest"); Assert.Equal(runData.BuildFlavor, "debug"); Assert.Equal(runData.BuildPlatform, "any cpu"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(runData.Attachments.Length, 7); int buildId; int.TryParse(runData.Build.Id, out buildId); Assert.Equal(buildId, 1); Assert.Equal(runData.ReleaseUri, "releaseUri"); Assert.Equal(runData.ReleaseEnvironmentUri, "releaseEnvironmentUri"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValuesForHierarchicalResults() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" />" + "</UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "<InnerResults>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"SubResult 1 (TestMethod2)\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "</InnerResults>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var testRunData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime StartedDate); Assert.Equal(testRunData.Results[0].StartedDate, StartedDate); TimeSpan.TryParse("00:00:00.0834563", out TimeSpan Duration); Assert.Equal(testRunData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(testRunData.Results[0].CompletedDate, CompletedDate); Assert.Equal(testRunData.Results.Length, 3); Assert.Equal(testRunData.Results[0].Outcome, "Failed"); Assert.Equal(testRunData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(testRunData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(testRunData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(testRunData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(testRunData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(testRunData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(testRunData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(testRunData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(testRunData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(testRunData.Results[0].Priority.ToString(), "1"); Assert.Equal(testRunData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(testRunData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(testRunData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); // Testing subResult properties Assert.Equal(testRunData.Results[0].TestCaseSubResultData.Count, 1); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].DisplayName, "SubResult 1 (TestMethod2)"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].Outcome, "Failed"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[0].TestCaseSubResultData[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(testRunData.Results[1].Outcome, "Passed"); Assert.Equal(testRunData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(testRunData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(testRunData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(testRunData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(testRunData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(testRunData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(testRunData.Results[2].Outcome, "Passed"); Assert.Equal(testRunData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(testRunData.Results[2].ComputerName, "random-DT"); Assert.Equal(testRunData.Results[2].AutomatedTestType, "OrderedTest"); // Testing subResult properties Assert.Equal(testRunData.Results[2].TestCaseSubResultData.Count, 2); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[0].DisplayName, "01- CodedUITestMethod1 (OrderedTest1)"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[1].DisplayName, "02- CodedUITestMethod2 (OrderedTest1)"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[0].Outcome, "Passed"); Assert.Equal(testRunData.Results[2].TestCaseSubResultData[1].Outcome, "Passed"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(testRunData.Attachments.Length, 7); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadsResultsReturnsCorrectValuesInDifferentCulture() { SetupMocks(); CultureInfo current = CultureInfo.CurrentCulture; try { //German is used, as in this culture decimal seperator is comma & thousand seperator is dot CultureInfo.CurrentCulture = new CultureInfo("de-DE"); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "</TestSettings>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><StdErr>This is standard error message.</StdErr><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3099353+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.Results[0].StartedDate, StartedDate); TimeSpan Duration; TimeSpan.TryParse("00:00:00.0834563", out Duration); Assert.Equal(runData.Results[0].DurationInMs, Duration.TotalMilliseconds); DateTime CompletedDate = StartedDate.AddTicks(Duration.Ticks); Assert.Equal(runData.Results[0].CompletedDate, CompletedDate); Assert.Equal(runData.Name, "VSTest Test Run debug any cpu"); Assert.Equal(runData.State, "InProgress"); Assert.Equal(runData.Results.Length, 3); Assert.Equal(runData.Results[0].Outcome, "Failed"); Assert.Equal(runData.Results[0].TestCaseTitle, "TestMethod2"); Assert.Equal(runData.Results[0].ComputerName, "SOMERANDOMCOMPUTERNAME"); Assert.Equal(runData.Results[0].AutomatedTestType, "UnitTest"); Assert.Equal(runData.Results[0].AutomatedTestName, "UnitTestProject4.UnitTest1.TestMethod2"); Assert.Equal(runData.Results[0].AutomatedTestId, "f0d6b58f-dc08-9c0b-aab7-0a1411d4a346"); Assert.Equal(runData.Results[0].AutomatedTestStorage, "unittestproject4.dll"); Assert.Equal(runData.Results[0].AutomatedTestTypeId, "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); Assert.Equal(runData.Results[0].ErrorMessage, "Assert.Fail failed."); Assert.Equal(runData.Results[0].StackTrace, "at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21"); Assert.Equal(runData.Results[0].Priority.ToString(), "1"); Assert.Equal(runData.Results[0].AttachmentData.ConsoleLog, "Show console log output."); Assert.Equal(runData.Results[0].AttachmentData.StandardError, "This is standard error message."); Assert.Equal(runData.Results[0].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[0].AttachmentData.AttachmentsFilePathList[0].Contains("x.txt")); Assert.Equal(runData.Results[1].Outcome, "Passed"); Assert.Equal(runData.Results[1].TestCaseTitle, "PSD_Startseite"); Assert.Equal(runData.Results[1].ComputerName, "LAB-BUILDVNEXT"); Assert.Equal(runData.Results[1].AutomatedTestType, "WebTest"); Assert.Equal(runData.Results[1].AttachmentData.ConsoleLog, null); Assert.Equal(runData.Results[1].AttachmentData.AttachmentsFilePathList.Count, 1); Assert.True(runData.Results[1].AttachmentData.AttachmentsFilePathList[0].Contains("PSD_Startseite.webtestResult")); Assert.Equal(runData.Results[2].Outcome, "Passed"); Assert.Equal(runData.Results[2].TestCaseTitle, "OrderedTest1"); Assert.Equal(runData.Results[2].ComputerName, "random-DT"); Assert.Equal(runData.Results[2].AutomatedTestType, "OrderedTest"); Assert.Equal(runData.BuildFlavor, "debug"); Assert.Equal(runData.BuildPlatform, "any cpu"); // 3 files related mstest.static, 3 files related to vstest.static, and 1 file for vstest.dynamic Assert.Equal(runData.Attachments.Length, 7); int buildId; int.TryParse(runData.Build.Id, out buildId); Assert.Equal(buildId, 1); Assert.Equal(runData.ReleaseUri, "releaseUri"); Assert.Equal(runData.ReleaseEnvironmentUri, "releaseEnvironmentUri"); } finally { CultureInfo.CurrentCulture = current; } } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void CustomRunTitleIsHonoured() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithCustomRunTitle.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri", "My Run Title")); Assert.Equal(runData.Name, "My Run Title"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailForBareMinimumTrx() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun>" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Inconclusive\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "bareMinimum.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); Assert.Equal(runData.Results[0].Outcome, "Inconclusive"); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithoutStartTime() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutStartTime.trx"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithoutFinishTime() { SetupMocks(); string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; _trxResultFile = "resultsWithoutFinishTime"; File.WriteAllText(_trxResultFile, trxContents); TrxResultReader reader = new TrxResultReader(); TestRunData runData = reader.ReadResults(_ec.Object, _trxResultFile, new TestRunContext(null, null, null, 1, null, null, null)); Assert.Equal(runData.Results.Length, 1); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void ReadResultsDoesNotFailWithFinishTimeLessThanStartTime() { SetupMocks(); var runData = GetTestRunDataBasic(); Assert.Equal(1, runData.Results.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunLevelResultsFilePresentByDefault() { SetupMocks(); var runData = GetTestRunDataBasic(); Assert.Equal(_trxResultFile, runData.Attachments[0]); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunLevelResultsFileAbsentIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataBasic(myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyResultsFilesAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(2); Assert.Equal(4, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(1); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachmentsWithDeployment() { SetupMocks(); var runData = GetTestRunDataWithAttachments(13); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyDataCollectorFilesAndPdbsAreAddedAsRunLevelAttachments() { SetupMocks(); var runData = GetTestRunDataWithAttachments(0); Assert.Equal(3, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoDataCollectorFilesAndPdbsAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(0, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoResultsFilesAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(2, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyNoCoverageSourceFilesAndPdbsAreAddedAsRunLevelAttachmentsIfSkipFlagIsSet() { SetupMocks(); var myReader = new TrxResultReader() { AddResultsFileToRunLevelAttachments = false }; var runData = GetTestRunDataWithAttachments(1, myReader); Assert.Equal(0, runData.Attachments.Length); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyRunTypeIsSet() { SetupMocks(); var runData = GetTestRunDataWithAttachments(0); Assert.Equal("unittest".ToLowerInvariant(), runData.Results[0].AutomatedTestType.ToLowerInvariant()); } [Fact] [Trait("Level", "L0")] [Trait("Category", "PublishTestResults")] public void VerifyReadResultsReturnsCorrectTestStartAndEndDateTime() { SetupMocks(); String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "</ResultSummary>" + "</TestRun>"; var runData = GetTestRunData(trxContents, null, new TestRunContext("Owner", "any cpu", "debug", 1, "", "releaseUri", "releaseEnvironmentUri")); DateTime StartedDate; DateTime.TryParse("2015-03-20T16:53:32.3349628+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out StartedDate); Assert.Equal(runData.StartDate, StartedDate.ToString("o")); DateTime CompletedDate; DateTime.TryParse("2015-03-20T16:53:32.9232329+05:30", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out CompletedDate); Assert.Equal(runData.CompleteDate, CompletedDate.ToString("o")); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { try { File.Delete(_trxResultFile); } catch { } } } private TestRunData GetTestRunDataBasic(TrxResultReader myReader = null) { string trxContents = "<?xml version =\"1.0\" encoding=\"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2014-03-20T16:53:32.3349628+05:30\" />" + "<Results>" + "<UnitTestResult testId=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\" testName=\"TestMethod1\" outcome=\"Passed\" />" + "</Results>" + "<TestDefinitions>" + "<UnitTest id=\"fd1a9d66-d059-cd84-23d7-f655dce255f5\">" + "<TestMethod className=\"UnitTestProject1.UnitTest1\" name=\"TestMethod1\" />" + "</UnitTest>" + "</TestDefinitions>" + "</TestRun>"; return GetTestRunData(trxContents, myReader); } private TestRunData GetTestRunDataWithAttachments(int val, TrxResultReader myReader = null, TestRunContext trContext = null) { var trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + "<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" + "<TestDefinitions>" + "<UnitTest name = \"TestMethod2\" storage = \"c:\\users\\somerandomusername\\source\\repos\\projectx\\unittestproject4\\unittestproject4\\bin\\debug\\unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\bin\\Debug\\UnitTestProject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" + "<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" + "<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" + "<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" + "<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" + "</TestDefinitions>" + "<TestSettings name=\"TestSettings1\" id=\"e9d264e9-30da-48df-aa95-c6b53f699464\"><Description>These are default test settings for a local test run.</Description>" + "<Execution>" + "<AgentRule name=\"LocalMachineDefaultRole\">" + "<DataCollectors>" + "<DataCollector uri=\"datacollector://microsoft/CodeCoverage/1.0\" assemblyQualifiedName=\"Microsoft.VisualStudio.TestTools.CodeCoverage.CoveragePlugIn, Microsoft.VisualStudio.QualityTools.Plugins.CodeCoverage, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" friendlyName=\"Code Coverage (Visual Studio 2010)\">" + "<Configuration><CodeCoverage xmlns=\"\"><Regular>" + "<CodeCoverageItem binaryFile=\"C:\\mstest.static.UnitTestProject3.dll\" pdbFile=\"C:\\mstest.static.UnitTestProject3.instr.pdb\" instrumentInPlace=\"true\" />" + "</Regular></CodeCoverage></Configuration>" + "</DataCollector>" + "</DataCollectors>" + "</AgentRule>" + "</Execution>" + "{3}" + "</TestSettings>" + "{0}" + "{1}" + "<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" + "{2}" + "</ResultSummary>" + "</TestRun>"; var part0 = "<Results>" + "<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Failed\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" + "<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" + "</UnitTestResult>" + "<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\">" + "<ResultFiles>" + "<ResultFile path=\"PSD_Startseite.webtestResult\" />" + "</ResultFiles>" + "<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" + "</WebTestResult>" + "<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" + "<InnerResults>" + "<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" + "<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" + "</InnerResults>" + "</TestResultAggregation>" + "</Results>"; var part1 = "<CollectorDataEntries>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/2.0\" collectorDisplayName=\"Code Coverage\"><UriAttachments><UriAttachment>" + "<A href=\"DIGANR-DEV4\\vstest_console.dynamic.data.coverage\"></A></UriAttachment></UriAttachments>" + "</Collector>" + "<Collector agentName=\"DIGANR-DEV4\" uri=\"datacollector://microsoft/CodeCoverage/1.0\" collectorDisplayName=\"MSTestAdapter\"><UriAttachments>" + "<UriAttachment><A href=\"DIGANR-DEV4\\unittestproject3.dll\">c:\\vstest.static.unittestproject3.dll</A></UriAttachment>" + "<UriAttachment><A href=\"DIGANR-DEV4\\UnitTestProject3.instr.pdb\">C:\\vstest.static.UnitTestProject3.instr.pdb</A></UriAttachment>" + "</UriAttachments></Collector>" + "</CollectorDataEntries>"; var part2 = "<ResultFiles>" + "<ResultFile path=\"vstest_console.static.data.coverage\" /></ResultFiles>" + "<ResultFile path=\"DIGANR-DEV4\\mstest.static.data.coverage\" />"; var part3 = "<Deployment runDeploymentRoot=\"results\"></Deployment>"; switch (val) { case 0: trxContents = string.Format(trxContents, part0, string.Empty, string.Empty, string.Empty); break; case 1: trxContents = string.Format(trxContents, string.Empty, part1, string.Empty, string.Empty); break; case 2: trxContents = string.Format(trxContents, string.Empty, string.Empty, part2, string.Empty); break; case 3: trxContents = string.Format(trxContents, string.Empty, string.Empty, string.Empty, string.Empty); break; case 13: trxContents = string.Format(trxContents, string.Empty, part1, string.Empty, part3); break; default: trxContents = string.Format(trxContents, part0, part1, part2); break; } return GetTestRunData(trxContents, myReader, trContext); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "TestHostContext")] private void SetupMocks([CallerMemberName] string name = "") { TestHostContext hc = new TestHostContext(this, name); _ec = new Mock<IExecutionContext>(); List<string> warnings; var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings); _ec.Setup(x => x.Variables).Returns(variables); } private TestRunData GetTestRunData(string trxContents, TrxResultReader myReader = null, TestRunContext trContext = null) { _trxResultFile = "results.trx"; File.WriteAllText(_trxResultFile, trxContents); var reader = myReader ?? new TrxResultReader(); var runData = reader.ReadResults(_ec.Object, _trxResultFile, trContext ?? new TestRunContext(null, null, null, 1, null, null, null)); return runData; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Details of a Parcel of land /// </summary> public class LandData { private Vector3 _AABBMax = new Vector3(); private Vector3 _AABBMin = new Vector3(); private int _area = 0; private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category private int _claimDate = 0; private int _claimPrice = 0; //Unemplemented private UUID _globalID = UUID.Zero; private UUID _groupID = UUID.Zero; private int _groupPrims = 0; private bool _isGroupOwned = false; private byte[] _bitmap = new byte[512]; private string _description = String.Empty; private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark | (uint) ParcelFlags.AllowAPrimitiveEntry | (uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform | (uint) ParcelFlags.CreateObjects | (uint) ParcelFlags.AllowOtherScripts | (uint) ParcelFlags.SoundLocal; private byte _landingType = 0; private string _name = "Your Parcel"; private ParcelStatus _status = ParcelStatus.Leased; private int _localID = 0; private byte _mediaAutoScale = 0; private UUID _mediaID = UUID.Zero; private string _mediaURL = String.Empty; private string _musicURL = String.Empty; private int _otherPrims = 0; private UUID _ownerID = UUID.Zero; private int _ownerPrims = 0; private List<ParcelManager.ParcelAccessEntry> _parcelAccessList = new List<ParcelManager.ParcelAccessEntry>(); private float _passHours = 0; private int _passPrice = 0; private int _salePrice = 0; //Unemeplemented. Parcels price. private int _selectedPrims = 0; private int _simwideArea = 0; private int _simwidePrims = 0; private UUID _snapshotID = UUID.Zero; private Vector3 _userLocation = new Vector3(); private Vector3 _userLookAt = new Vector3(); private int _dwell = 0; private int _otherCleanTime = 0; /// <summary> /// Upper corner of the AABB for the parcel /// </summary> public Vector3 AABBMax { get { return _AABBMax; } set { _AABBMax = value; } } /// <summary> /// Lower corner of the AABB for the parcel /// </summary> public Vector3 AABBMin { get { return _AABBMin; } set { _AABBMin = value; } } /// <summary> /// Area in meters^2 the parcel contains /// </summary> public int Area { get { return _area; } set { _area = value; } } /// <summary> /// ID of auction (3rd Party Integration) when parcel is being auctioned /// </summary> public uint AuctionID { get { return _auctionID; } set { _auctionID = value; } } /// <summary> /// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it. /// </summary> public UUID AuthBuyerID { get { return _authBuyerID; } set { _authBuyerID = value; } } /// <summary> /// Category of parcel. Used for classifying the parcel in classified listings /// </summary> public ParcelCategory Category { get { return _category; } set { _category = value; } } /// <summary> /// Date that the current owner purchased or claimed the parcel /// </summary> public int ClaimDate { get { return _claimDate; } set { _claimDate = value; } } /// <summary> /// The last price that the parcel was sold at /// </summary> public int ClaimPrice { get { return _claimPrice; } set { _claimPrice = value; } } /// <summary> /// Global ID for the parcel. (3rd Party Integration) /// </summary> public UUID GlobalID { get { return _globalID; } set { _globalID = value; } } /// <summary> /// Unique ID of the Group that owns /// </summary> public UUID GroupID { get { return _groupID; } set { _groupID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by a Group /// </summary> public int GroupPrims { get { return _groupPrims; } set { _groupPrims = value; } } /// <summary> /// Returns true if the Land Parcel is owned by a group /// </summary> public bool IsGroupOwned { get { return _isGroupOwned; } set { _isGroupOwned = value; } } /// <summary> /// jp2 data for the image representative of the parcel in the parcel dialog /// </summary> public byte[] Bitmap { get { return _bitmap; } set { _bitmap = value; } } /// <summary> /// Parcel Description /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags /// </summary> public uint Flags { get { return _flags; } set { _flags = value; } } /// <summary> /// Determines if people are able to teleport where they please on the parcel or if they /// get constrainted to a specific point on teleport within the parcel /// </summary> public byte LandingType { get { return _landingType; } set { _landingType = value; } } /// <summary> /// Parcel Name /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Status of Parcel, Leased, Abandoned, For Sale /// </summary> public ParcelStatus Status { get { return _status; } set { _status = value; } } /// <summary> /// Internal ID of the parcel. Sometimes the client will try to use this value /// </summary> public int LocalID { get { return _localID; } set { _localID = value; } } /// <summary> /// Determines if we scale the media based on the surface it's on /// </summary> public byte MediaAutoScale { get { return _mediaAutoScale; } set { _mediaAutoScale = value; } } /// <summary> /// Texture Guid to replace with the output of the media stream /// </summary> public UUID MediaID { get { return _mediaID; } set { _mediaID = value; } } /// <summary> /// URL to the media file to display /// </summary> public string MediaURL { get { return _mediaURL; } set { _mediaURL = value; } } /// <summary> /// URL to the shoutcast music stream to play on the parcel /// </summary> public string MusicURL { get { return _musicURL; } set { _musicURL = value; } } /// <summary> /// Number of SceneObjectPart that are owned by users who do not own the parcel /// and don't have the 'group. These are elegable for AutoReturn collection /// </summary> public int OtherPrims { get { return _otherPrims; } set { _otherPrims = value; } } /// <summary> /// Owner Avatar or Group of the parcel. Naturally, all land masses must be /// owned by someone /// </summary> public UUID OwnerID { get { return _ownerID; } set { _ownerID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by the owner of the parcel /// </summary> public int OwnerPrims { get { return _ownerPrims; } set { _ownerPrims = value; } } /// <summary> /// List of access data for the parcel. User data, some bitflags, and a time /// </summary> public List<ParcelManager.ParcelAccessEntry> ParcelAccessList { get { return _parcelAccessList; } set { _parcelAccessList = value; } } /// <summary> /// How long in hours a Pass to the parcel is given /// </summary> public float PassHours { get { return _passHours; } set { _passHours = value; } } /// <summary> /// Price to purchase a Pass to a restricted parcel /// </summary> public int PassPrice { get { return _passPrice; } set { _passPrice = value; } } /// <summary> /// When the parcel is being sold, this is the price to purchase the parcel /// </summary> public int SalePrice { get { return _salePrice; } set { _salePrice = value; } } /// <summary> /// Number of SceneObjectPart that are currently selected by avatar /// </summary> public int SelectedPrims { get { return _selectedPrims; } set { _selectedPrims = value; } } /// <summary> /// Number of meters^2 in the Simulator /// </summary> public int SimwideArea { get { return _simwideArea; } set { _simwideArea = value; } } /// <summary> /// Number of SceneObjectPart in the Simulator /// </summary> public int SimwidePrims { get { return _simwidePrims; } set { _simwidePrims = value; } } /// <summary> /// ID of the snapshot used in the client parcel dialog of the parcel /// </summary> public UUID SnapshotID { get { return _snapshotID; } set { _snapshotID = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the location /// that the user will be redirected to /// </summary> public Vector3 UserLocation { get { return _userLocation; } set { _userLocation = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the rotation /// that the user will be positioned /// </summary> public Vector3 UserLookAt { get { return _userLookAt; } set { _userLookAt = value; } } /// <summary> /// Deprecated idea. Number of visitors ~= free money /// </summary> public int Dwell { get { return _dwell; } set { _dwell = value; } } /// <summary> /// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own /// the parcel and isn't set to the same 'group' as the parcel. /// </summary> public int OtherCleanTime { get { return _otherCleanTime; } set { _otherCleanTime = value; } } public LandData() { _globalID = UUID.Random(); } /// <summary> /// Make a new copy of the land data /// </summary> /// <returns></returns> public LandData Copy() { LandData landData = new LandData(); landData._AABBMax = _AABBMax; landData._AABBMin = _AABBMin; landData._area = _area; landData._auctionID = _auctionID; landData._authBuyerID = _authBuyerID; landData._category = _category; landData._claimDate = _claimDate; landData._claimPrice = _claimPrice; landData._globalID = _globalID; landData._groupID = _groupID; landData._groupPrims = _groupPrims; landData._otherPrims = _otherPrims; landData._ownerPrims = _ownerPrims; landData._selectedPrims = _selectedPrims; landData._isGroupOwned = _isGroupOwned; landData._localID = _localID; landData._landingType = _landingType; landData._mediaAutoScale = _mediaAutoScale; landData._mediaID = _mediaID; landData._mediaURL = _mediaURL; landData._musicURL = _musicURL; landData._ownerID = _ownerID; landData._bitmap = (byte[]) _bitmap.Clone(); landData._description = _description; landData._flags = _flags; landData._name = _name; landData._status = _status; landData._passHours = _passHours; landData._passPrice = _passPrice; landData._salePrice = _salePrice; landData._snapshotID = _snapshotID; landData._userLocation = _userLocation; landData._userLookAt = _userLookAt; landData._otherCleanTime = _otherCleanTime; landData._dwell = _dwell; landData._parcelAccessList.Clear(); foreach (ParcelManager.ParcelAccessEntry entry in _parcelAccessList) { ParcelManager.ParcelAccessEntry newEntry = new ParcelManager.ParcelAccessEntry(); newEntry.AgentID = entry.AgentID; newEntry.Flags = entry.Flags; newEntry.Time = entry.Time; landData._parcelAccessList.Add(newEntry); } return landData; } } }
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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.Diagnostics; using System.IO; using System.Runtime.Serialization; using System.Xml; using ICSharpCode.NRefactory.Editor; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem.Implementation; namespace ICSharpCode.NRefactory.Documentation { /// <summary> /// Provides documentation from an .xml file (as generated by the Microsoft C# compiler). /// </summary> /// <remarks> /// This class first creates an in-memory index of the .xml file, and then uses that to read only the requested members. /// This way, we avoid keeping all the documentation in memory. /// The .xml file is only opened when necessary, the file handle is not kept open all the time. /// If the .xml file is changed, the index will automatically be recreated. /// </remarks> [Serializable] public class XmlDocumentationProvider : IDocumentationProvider, IDeserializationCallback { #region Cache sealed class XmlDocumentationCache { readonly KeyValuePair<string, string>[] entries; int pos; public XmlDocumentationCache(int size = 50) { if (size <= 0) throw new ArgumentOutOfRangeException("size", size, "Value must be positive"); this.entries = new KeyValuePair<string, string>[size]; } internal string Get(string key) { foreach (var pair in entries) { if (pair.Key == key) return pair.Value; } return null; } internal void Add(string key, string value) { entries[pos++] = new KeyValuePair<string, string>(key, value); if (pos == entries.Length) pos = 0; } } #endregion [Serializable] struct IndexEntry : IComparable<IndexEntry> { /// <summary> /// Hash code of the documentation tag /// </summary> internal readonly int HashCode; /// <summary> /// Position in the .xml file where the documentation starts /// </summary> internal readonly int PositionInFile; internal IndexEntry(int hashCode, int positionInFile) { this.HashCode = hashCode; this.PositionInFile = positionInFile; } public int CompareTo(IndexEntry other) { return this.HashCode.CompareTo(other.HashCode); } } [NonSerialized] XmlDocumentationCache cache = new XmlDocumentationCache(); readonly string fileName; DateTime lastWriteDate; IndexEntry[] index; // SORTED array of index entries #region Constructor / Redirection support /// <summary> /// Creates a new XmlDocumentationProvider. /// </summary> /// <param name="fileName">Name of the .xml file.</param> public XmlDocumentationProvider(string fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { using (XmlTextReader xmlReader = new XmlTextReader(fs)) { xmlReader.XmlResolver = null; // no DTD resolving xmlReader.MoveToContent(); if (string.IsNullOrEmpty(xmlReader.GetAttribute("redirect"))) { this.fileName = fileName; ReadXmlDoc(xmlReader); } else { string redirectionTarget = GetRedirectionTarget(fileName, xmlReader.GetAttribute("redirect")); if (redirectionTarget != null) { Debug.WriteLine("XmlDoc " + fileName + " is redirecting to " + redirectionTarget); using (FileStream redirectedFs = new FileStream(redirectionTarget, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { using (XmlTextReader redirectedXmlReader = new XmlTextReader(redirectedFs)) { this.fileName = redirectionTarget; ReadXmlDoc(redirectedXmlReader); } } } else { throw new XmlException("XmlDoc " + fileName + " is redirecting to " + xmlReader.GetAttribute("redirect") + ", but that file was not found."); } } } } } static string GetRedirectionTarget(string xmlFileName, string target) { string programFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); programFilesDir = AppendDirectorySeparator(programFilesDir); string corSysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); corSysDir = AppendDirectorySeparator(corSysDir); var fileName = target.Replace ("%PROGRAMFILESDIR%", programFilesDir) .Replace ("%CORSYSDIR%", corSysDir); if (!Path.IsPathRooted (fileName)) fileName = Path.Combine (Path.GetDirectoryName (xmlFileName), fileName); return LookupLocalizedXmlDoc(fileName); } static string AppendDirectorySeparator(string dir) { if (dir.EndsWith("\\", StringComparison.Ordinal) || dir.EndsWith("/", StringComparison.Ordinal)) return dir; else return dir + Path.DirectorySeparatorChar; } /// <summary> /// Given the assembly file name, looks up the XML documentation file name. /// Returns null if no XML documentation file is found. /// </summary> public static string LookupLocalizedXmlDoc(string fileName) { string xmlFileName = Path.ChangeExtension(fileName, ".xml"); string currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName; string localizedXmlDocFile = GetLocalizedName(xmlFileName, currentCulture); Debug.WriteLine("Try find XMLDoc @" + localizedXmlDocFile); if (File.Exists(localizedXmlDocFile)) { return localizedXmlDocFile; } Debug.WriteLine("Try find XMLDoc @" + xmlFileName); if (File.Exists(xmlFileName)) { return xmlFileName; } if (currentCulture != "en") { string englishXmlDocFile = GetLocalizedName(xmlFileName, "en"); Debug.WriteLine("Try find XMLDoc @" + englishXmlDocFile); if (File.Exists(englishXmlDocFile)) { return englishXmlDocFile; } } return null; } static string GetLocalizedName(string fileName, string language) { string localizedXmlDocFile = Path.GetDirectoryName(fileName); localizedXmlDocFile = Path.Combine(localizedXmlDocFile, language); localizedXmlDocFile = Path.Combine(localizedXmlDocFile, Path.GetFileName(fileName)); return localizedXmlDocFile; } #endregion #region Load / Create Index void ReadXmlDoc(XmlTextReader reader) { lastWriteDate = File.GetLastWriteTimeUtc(fileName); // Open up a second file stream for the line<->position mapping using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { LinePositionMapper linePosMapper = new LinePositionMapper(fs); List<IndexEntry> indexList = new List<IndexEntry>(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.LocalName) { case "members": ReadMembersSection(reader, linePosMapper, indexList); break; } } } indexList.Sort(); this.index = indexList.ToArray(); } } sealed class LinePositionMapper { readonly FileStream fs; int currentLine = 1; public LinePositionMapper(FileStream fs) { this.fs = fs; } public int GetPositionForLine(int line) { Debug.Assert(line >= currentLine); while (line > currentLine) { int b = fs.ReadByte(); if (b < 0) throw new EndOfStreamException(); if (b == '\n') { currentLine++; } } return checked((int)fs.Position); } } static void ReadMembersSection(XmlTextReader reader, LinePositionMapper linePosMapper, List<IndexEntry> indexList) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.EndElement: if (reader.LocalName == "members") { return; } break; case XmlNodeType.Element: if (reader.LocalName == "member") { int pos = linePosMapper.GetPositionForLine(reader.LineNumber) + Math.Max(reader.LinePosition - 2, 0); string memberAttr = reader.GetAttribute("name"); if (memberAttr != null) indexList.Add(new IndexEntry(memberAttr.GetHashCode(), pos)); reader.Skip(); } break; } } } #endregion #region GetDocumentation /// <summary> /// Get the documentation for the member with the specified documentation key. /// </summary> public string GetDocumentation(string key) { if (key == null) throw new ArgumentNullException("key"); int hashcode = key.GetHashCode(); // index is sorted, so we can use binary search int m = Array.BinarySearch(index, new IndexEntry(hashcode, 0)); if (m < 0) return null; // correct hash code found. // possibly there are multiple items with the same hash, so go to the first. while (--m >= 0 && index[m].HashCode == hashcode); // m is now 1 before the first item with the correct hash XmlDocumentationCache cache = this.cache; lock (cache) { string val = cache.Get(key); if (val == null) { // go through all items that have the correct hash while (++m < index.Length && index[m].HashCode == hashcode) { val = LoadDocumentation(key, index[m].PositionInFile); if (val != null) break; } // cache the result (even if it is null) cache.Add(key, val); } return val; } } #endregion #region GetDocumentation for entity /// <inheritdoc/> public DocumentationComment GetDocumentation(IEntity entity) { string xmlDoc = GetDocumentation(IdStringProvider.GetIdString(entity)); if (xmlDoc != null) { return new DocumentationComment(new StringTextSource(xmlDoc), new SimpleTypeResolveContext(entity)); } else { return null; } } #endregion #region Load / Read XML string LoadDocumentation(string key, int positionInFile) { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { fs.Position = positionInFile; using (XmlTextReader r = new XmlTextReader(fs, XmlNodeType.Element, null)) { r.XmlResolver = null; // no DTD resolving while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { string memberAttr = r.GetAttribute("name"); if (memberAttr == key) { return r.ReadInnerXml(); } else { return null; } } } return null; } } } #endregion public virtual void OnDeserialization(object sender) { cache = new XmlDocumentationCache(); } } }
using System; using System.Linq; using System.Collections.Generic; using NUnit.Framework; using NServiceKit.DataAnnotations; using System.ComponentModel.DataAnnotations; namespace NServiceKit.OrmLite.Tests { /// <summary>An ORM lite get scalar tests.</summary> [TestFixture] public class OrmLiteGetScalarTests:OrmLiteTestBase { /// <summary>Can get scalar value.</summary> [Test] public void Can_get_scalar_value(){ List<Author> authors = new List<Author>(); authors.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London", FloatProperty=10.25f, DoubleProperty=3.23 }); authors.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota",FloatProperty=7.59f,DoubleProperty=4.23 }); authors.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London",FloatProperty=15.5f,DoubleProperty=5.42 }); authors.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota",FloatProperty=0.57f, DoubleProperty=8.76}); authors.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=8.43f, DoubleProperty=7.35}); authors.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=1.25f, DoubleProperty=0.3652}); authors.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota", FloatProperty=1.5f, DoubleProperty=100.563}); authors.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena", FloatProperty=3.5f,DoubleProperty=7.23 }); authors.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena", FloatProperty=0.25f,DoubleProperty=9.23 }); authors.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London", FloatProperty=9.95f,DoubleProperty=4.91 }); authors.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin",FloatProperty=4.44f,DoubleProperty=6.41 }); authors.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid", FloatProperty=6.67f, DoubleProperty=8.05 }); authors.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid", FloatProperty=1.25f, DoubleProperty=3.99}); authors.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10, City = "Mexico", LastActivity= DateTime.Today, NRate=5, FloatProperty=1.25f, NFloatProperty=3.15f, DoubleProperty= 1.25, NDoubleProperty= 8.25 }); using (var db = OpenDbConnection()) { db.CreateTable<Author>(true); db.DeleteAll<Author>(); db.InsertAll(authors); var expectedDate = authors.Max(e=>e.Birthday); var r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) ); Assert.That(expectedDate, Is.EqualTo(r1)); expectedDate = authors.Where(e=>e.City=="London").Max(e=>e.Birthday); r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="London" ); Assert.That(expectedDate, Is.EqualTo(r1)); r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="SinCity" ); Assert.That( default(DateTime), Is.EqualTo(r1)); var expectedNullableDate= authors.Max(e=>e.LastActivity); DateTime? r2 = db.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity)); Assert.That(expectedNullableDate, Is.EqualTo(r2)); expectedNullableDate= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity); r2 = db.GetScalar<Author,DateTime?>( e=> Sql.Max(e.LastActivity), e=> e.City=="Bogota" ); Assert.That(expectedNullableDate, Is.EqualTo(r2)); r2 = db.GetScalar<Author, DateTime?>( e => Sql.Max(e.LastActivity), e=>e.City=="SinCity" ); Assert.That( default(DateTime?), Is.EqualTo(r2)); var expectedDecimal= authors.Max(e=>e.Earnings); decimal r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings)); Assert.That(expectedDecimal, Is.EqualTo(r3)); expectedDecimal= authors.Where(e=>e.City=="London").Max(e=>e.Earnings); r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="London"); Assert.That(expectedDecimal, Is.EqualTo(r3)); r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="SinCity"); Assert.That( default(decimal), Is.EqualTo(r3)); var expectedNullableDecimal= authors.Max(e=>e.NEarnings); decimal? r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings)); Assert.That(expectedNullableDecimal, Is.EqualTo(r4)); expectedNullableDecimal= authors.Where(e=>e.City=="London").Max(e=>e.NEarnings); r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="London"); Assert.That(expectedNullableDecimal, Is.EqualTo(r4)); r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="SinCity"); Assert.That( default(decimal?), Is.EqualTo(r4)); var expectedDouble =authors.Max(e=>e.DoubleProperty); double r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty)); Assert.That(expectedDouble, Is.EqualTo(r5)); expectedDouble =authors.Where(e=>e.City=="London").Max(e=>e.DoubleProperty); r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="London"); Assert.That(expectedDouble, Is.EqualTo(r5)); r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="SinCity"); Assert.That(default(double),Is.EqualTo(r5)); var expectedNullableDouble =authors.Max(e=>e.NDoubleProperty); double? r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty)); Assert.That(expectedNullableDouble, Is.EqualTo(r6)); expectedNullableDouble =authors.Where(e=>e.City=="London").Max(e=>e.NDoubleProperty); r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="London"); Assert.That(expectedNullableDouble, Is.EqualTo(r6)); r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="SinCity"); Assert.That(default(double?),Is.EqualTo(r6)); var expectedFloat =authors.Max(e=>e.FloatProperty); var r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty)); Assert.That(expectedFloat, Is.EqualTo(r7)); expectedFloat =authors.Where(e=>e.City=="London").Max(e=>e.FloatProperty); r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="London"); Assert.That(expectedFloat, Is.EqualTo(r7)); r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="SinCity"); Assert.That(default(float),Is.EqualTo(r7)); var expectedNullableFloat =authors.Max(e=>e.NFloatProperty); var r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty)); Assert.That(expectedNullableFloat, Is.EqualTo(r8)); expectedNullableFloat =authors.Where(e=>e.City=="London").Max(e=>e.NFloatProperty); r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="London"); Assert.That(expectedNullableFloat, Is.EqualTo(r8)); r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="SinCity"); Assert.That(default(float?),Is.EqualTo(r8)); var expectedString=authors.Min(e=>e.Name); var r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name)); Assert.That(expectedString, Is.EqualTo(r9)); expectedString=authors.Where(e=>e.City=="London").Min(e=>e.Name); r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name), e=>e.City=="London"); Assert.That(expectedString, Is.EqualTo(r9)); r9 = db.GetScalar<Author,string>(e=> Sql.Max(e.Name), e=>e.City=="SinCity"); Assert.IsNullOrEmpty(r9); //Can't MIN(bit)/MAX(bit) in SQL Server var expectedBool=authors.Min(e=>e.Active); var r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active)); Assert.That(expectedBool, Is.EqualTo(r10)); expectedBool=authors.Max(e=>e.Active); r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active)); Assert.That(expectedBool, Is.EqualTo(r10)); r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active), e => e.City == "SinCity"); Assert.IsFalse(r10); var expectedShort =authors.Max(e=>e.Rate); var r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate)); Assert.That(expectedShort, Is.EqualTo(r11)); expectedShort =authors.Where(e=>e.City=="London").Max(e=>e.Rate); r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="London"); Assert.That(expectedShort, Is.EqualTo(r11)); r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="SinCity"); Assert.That(default(short),Is.EqualTo(r7)); var expectedNullableShort =authors.Max(e=>e.NRate); var r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate)); Assert.That(expectedNullableShort, Is.EqualTo(r12)); expectedNullableShort =authors.Where(e=>e.City=="London").Max(e=>e.NRate); r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="London"); Assert.That(expectedNullableShort, Is.EqualTo(r12)); r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="SinCity"); Assert.That(default(short?),Is.EqualTo(r12)); } } } /// <summary>An author.</summary> public class Author { /// <summary> /// Initializes a new instance of the NServiceKit.OrmLite.Tests.Author class. /// </summary> public Author(){} /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> [AutoIncrement] [Alias("AuthorID")] public Int32 Id { get; set;} /// <summary>Gets or sets the name.</summary> /// <value>The name.</value> [Index(Unique = true)] [StringLength(40)] public string Name { get; set;} /// <summary>Gets or sets the Date/Time of the birthday.</summary> /// <value>The birthday.</value> public DateTime Birthday { get; set;} /// <summary>Gets or sets the Date/Time of the last activity.</summary> /// <value>The last activity.</value> public DateTime? LastActivity { get; set;} /// <summary>Gets or sets the earnings.</summary> /// <value>The earnings.</value> public decimal Earnings { get; set;} /// <summary>Gets or sets the earnings.</summary> /// <value>The n earnings.</value> public decimal? NEarnings { get; set;} /// <summary>Gets or sets a value indicating whether the active.</summary> /// <value>true if active, false if not.</value> public bool Active { get; set; } /// <summary>Gets or sets the city.</summary> /// <value>The city.</value> [StringLength(80)] [Alias("JobCity")] public string City { get; set;} /// <summary>Gets or sets the comments.</summary> /// <value>The comments.</value> [StringLength(80)] [Alias("Comment")] public string Comments { get; set;} /// <summary>Gets or sets the rate.</summary> /// <value>The rate.</value> public short Rate{ get; set;} /// <summary>Gets or sets the rate.</summary> /// <value>The n rate.</value> public short? NRate{ get; set;} /// <summary>Gets or sets the float property.</summary> /// <value>The float property.</value> public float FloatProperty { get; set;} /// <summary>Gets or sets the float property.</summary> /// <value>The n float property.</value> public float? NFloatProperty { get; set;} /// <summary>Gets or sets the double property.</summary> /// <value>The double property.</value> public double DoubleProperty { get; set;} /// <summary>Gets or sets the double property.</summary> /// <value>The n double property.</value> public double? NDoubleProperty { get; set;} } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // THIS FILE IS NOT INTENDED TO BE EDITED. // // This file can be updated in-place using the Package Manager Console. To check for updates, run the following command: // // PM> Get-Package -Updates using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Microsoft.Its.Domain.Serialization; using Microsoft.Its.Domain.Sql.CommandScheduler; using Microsoft.ServiceBus.Messaging; using Newtonsoft.Json; namespace Microsoft.Its.Domain.ServiceBus { #if !RecipesProject /// <summary> /// Receives messages from a service bus queue and attempts to trigger corresponding commands via the command scheduler. /// </summary> [DebuggerStepThrough] [ExcludeFromCodeCoverage] #endif public class ServiceBusCommandQueueReceiver : IMessageSessionAsyncHandlerFactory, IDisposable { private readonly ServiceBusSettings settings; private readonly ISchedulerClockTrigger clockTrigger; private readonly Subject<Exception> exceptionSubject = new Subject<Exception>(); private QueueClient queueClient; private readonly Subject<IScheduledCommand> messageSubject = new Subject<IScheduledCommand>(); private readonly Func<CommandSchedulerDbContext> createCommandSchedulerDbContext; /// <summary> /// Initializes a new instance of the <see cref="ServiceBusCommandQueueReceiver"/> class. /// </summary> /// <param name="settings">The service bus settings.</param> /// <param name="clockTrigger">The command clockTrigger.</param> /// <exception cref="System.ArgumentNullException"> /// settings /// or /// clockTrigger /// </exception> public ServiceBusCommandQueueReceiver( ServiceBusSettings settings, ISchedulerClockTrigger clockTrigger, Func<CommandSchedulerDbContext> createCommandSchedulerDbContext) { if (settings == null) { throw new ArgumentNullException("settings"); } if (clockTrigger == null) { throw new ArgumentNullException("clockTrigger"); } if (createCommandSchedulerDbContext == null) { throw new ArgumentNullException("createCommandSchedulerDbContext"); } this.settings = settings; this.clockTrigger = clockTrigger; this.createCommandSchedulerDbContext = createCommandSchedulerDbContext; #if DEBUG exceptionSubject .Where(ex => !(ex is OperationCanceledException)) .Subscribe(ex => Debug.WriteLine("ServiceBusCommandQueueReceiver error: " + ex)); #endif } /// <summary> /// Creates an instance of the handler factory. /// </summary> /// <returns> /// The created instance. /// </returns> /// <param name="session">The message session.</param> /// <param name="message">The message.</param> IMessageSessionAsyncHandler IMessageSessionAsyncHandlerFactory.CreateInstance(MessageSession session, BrokeredMessage message) { return new SessionHandler( msg => messageSubject.OnNext(msg), ex => exceptionSubject.OnNext(ex), clockTrigger, createCommandSchedulerDbContext); } /// <summary> /// Releases the resources associated with the handler factory instance. /// </summary> /// <param name="handler">The handler instance.</param> void IMessageSessionAsyncHandlerFactory.DisposeInstance(IMessageSessionAsyncHandler handler) { } /// <summary> /// Gets an observable sequence of the messages that the receiver dequeues from the service bus. /// </summary> public Subject<IScheduledCommand> Messages { get { return messageSubject; } } public Task StartReceivingMessages() { queueClient = ServiceBusCommandQueueSender.CreateQueueClient(settings); var options = new SessionHandlerOptions { AutoComplete = false, MessageWaitTimeout = TimeSpan.FromSeconds(3) }; if (settings.MaxConcurrentSessions != null) { options.MaxConcurrentSessions = settings.MaxConcurrentSessions.Value; } options.ExceptionReceived += (sender, e) => exceptionSubject.OnNext(e.Exception); return queueClient.RegisterSessionHandlerFactoryAsync(this, options); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { var client = queueClient; if (client != null) { client.Close(); } } private class SessionHandler : IMessageSessionAsyncHandler { private readonly ISchedulerClockTrigger clockTrigger; private readonly Action<IScheduledCommand> onMessage; private readonly Action<Exception> onError; private readonly Func<CommandSchedulerDbContext> createCommandSchedulerDbContext; public SessionHandler( Action<IScheduledCommand> onMessage, Action<Exception> onError, ISchedulerClockTrigger clockTrigger, Func<CommandSchedulerDbContext> createCommandSchedulerDbContext) { this.onMessage = onMessage; this.onError = onError; this.clockTrigger = clockTrigger; this.createCommandSchedulerDbContext = createCommandSchedulerDbContext; } /// <summary> /// Raises an event that occurs when a message has been brokered. /// </summary> /// <returns> /// The task object representing the asynchronous operation. /// </returns> /// <param name="session">The message session.</param> /// <param name="message">The brokered message.</param> public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { var json = message.GetBody<string>(); var @event = json.FromJsonTo<ServiceBusScheduledCommand>(); @event.BrokeredMessage = message; onMessage(@event); var result = await clockTrigger.Trigger(commands => commands.Due(@event.DueTime) .Where(c => c.AggregateId == @event.AggregateId)); if (!result.FailedCommands.Any()) { if (result.SuccessfulCommands.Any()) { Debug.WriteLine("ServiceBusCommandQueueReceiver: completing on success: " + @event.AggregateId); await message.CompleteAsync(); return; } using (var db = createCommandSchedulerDbContext()) { // if the command was already applied, we can complete the message. its job is done. if (db.ScheduledCommands .Where(cmd => cmd.AppliedTime != null || cmd.FinalAttemptTime != null) .Where(cmd => cmd.SequenceNumber == @event.SequenceNumber) .Any(cmd => cmd.AggregateId == @event.AggregateId)) { Debug.WriteLine("ServiceBusCommandQueueReceiver: completing because command was previously applied: " + @event.AggregateId); await message.CompleteAsync(); } } } } /// <summary> /// Raises an event that occurs when the session has been asynchronously closed. /// </summary> /// <returns> /// The task object representing the asynchronous operation. /// </returns> /// <param name="session">The closed session.</param> public async Task OnCloseSessionAsync(MessageSession session) { } /// <summary> /// Raises an event that occurs when the session has been lost. /// </summary> /// <returns> /// The task object representing the asynchronous operation. /// </returns> /// <param name="exception">The exception that occurred that caused the lost session.</param> public Task OnSessionLostAsync(Exception exception) { return Task.Run(() => onError(exception)); } } /// <summary> /// Serves as a deserialization target for commands queued to the service bus. These commands contain the full command JSON, but ServiceBusScheduledCommand is actually only used to look up the command from the command clockTrigger database. /// </summary> private class ServiceBusScheduledCommand : Event, IScheduledCommand { public DateTimeOffset? DueTime { get; private set; } public EventHasBeenRecordedPrecondition DeliveryPrecondition { get; set; } IPrecondition IScheduledCommand.DeliveryPrecondition { get { return DeliveryPrecondition; } } [JsonIgnore] public ScheduledCommandResult Result { get; set; } private int NumberOfPreviousAttempts { get; set; } int IScheduledCommand.NumberOfPreviousAttempts { get { return this.NumberOfPreviousAttempts; } } public BrokeredMessage BrokeredMessage { get; internal set; } } } }
/* * X509Certificate.cs - Implementation of the * "System.Security.Cryptography.X509Certificates.X509Certificate" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Cryptography.X509Certificates { #if CONFIG_X509_CERTIFICATES using System; using System.IO; using System.Text; using System.Security.Cryptography; #if CONFIG_FRAMEWORK_2_0 using System.Runtime.Serialization; #endif [Serializable] #if CONFIG_FRAMEWORK_2_0 public class X509Certificate: IDeserializationCallback, ISerializable #else public class X509Certificate #endif { // Internal state. private byte[] rawData; private byte[] hash; private String effectiveDate; private String expirationDate; private String issuer; private String keyAlgorithm; private byte[] keyAlgorithmParameters; private String name; private byte[] publicKey; private byte[] serialNumber; // Constructors. #if CONFIG_FRAMEWORK_2_0 [TODO] public X509Certificate() { throw new NotImplementedException("X509Certificate()"); } #endif public X509Certificate(byte[] data) { if(data == null) { throw new ArgumentNullException("data"); } Parse(data); } #if CONFIG_FRAMEWORK_2_0 [TODO] public X509Certificate(byte[] rawData, String password) { throw new NotImplementedException("X509Certificate(byte[], String)"); } [TODO] public X509Certificate(byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags) { throw new NotImplementedException("X509Certificate(byte[], String, X509KeyStorageFlags)"); } #endif public X509Certificate(IntPtr handle) { // Handle-based certificate construction is not supported. throw new NotSupportedException (_("Crypto_CertNotSupp")); } #if CONFIG_FRAMEWORK_2_0 [TODO] public X509Certificate(SerializationInfo info, StreamingContext context) { throw new NotImplementedException("X509Certificate(SerializationInfo, StreamingContext)"); } [TODO] public X509Certificate(String fileName) { throw new NotImplementedException("X509Certificate(String)"); } [TODO] public X509Certificate(String fileName, String password) { throw new NotImplementedException("X509Certificate(String, String)"); } [TODO] public X509Certificate(String fileName, String password, X509KeyStorageFlags keyStorageFlags) { throw new NotImplementedException("X509Certificate(String, String, X509KeyStorageFlags)"); } #endif public X509Certificate(X509Certificate cert) { if(cert == null) { throw new ArgumentNullException("cert"); } Parse(cert.rawData); } // Parse the contents of a certificate data block. private void Parse(byte[] data) { // Clone the data for internal storage. rawData = (byte[])(data.Clone()); // Parse the ASN.1 data to get the field we are interested in. ASN1Parser parser = new ASN1Parser(rawData); ASN1Parser signed = parser.GetSequence(); ASN1Parser certInfo = signed.GetSequence(); if(certInfo.Type == ASN1Parser.ContextSpecific(0)) { // Skip the version field. certInfo.Skip(); } serialNumber = certInfo.GetContentsAsArray(ASN1Type.Integer); ASN1Parser algId = certInfo.GetSequence(); issuer = ParseName(certInfo); ASN1Parser validity = certInfo.GetSequence(); effectiveDate = validity.GetUTCTime(); expirationDate = validity.GetUTCTime(); name = ParseName(certInfo); ASN1Parser keyInfo = certInfo.GetSequence(); algId = keyInfo.GetSequence(); keyAlgorithm = ToHex(algId.GetObjectIdentifier()); if(algId.IsAtEnd() || algId.IsNull()) { keyAlgorithmParameters = null; } else { keyAlgorithmParameters = algId.GetWholeAsArray(); } publicKey = keyInfo.GetBitString(); #if CONFIG_CRYPTO // Construct an MD5 hash of the certificate. Is this correct? MD5 md5 = new MD5CryptoServiceProvider(); md5.InternalHashCore(rawData, 0, rawData.Length); hash = md5.InternalHashFinal(); md5.Initialize(); #endif } // Parse an X.509-format name and convert it into a string. private static String ParseName(ASN1Parser certInfo) { StringBuilder builder = new StringBuilder(); ASN1Parser outer; ASN1Parser set; ASN1Parser pair; // Process the outer sequence. outer = certInfo.GetSequence(); while(!outer.IsAtEnd()) { // Process the next name attribute set. set = outer.GetSet(); while(!set.IsAtEnd()) { // Process the next attribute name/value pair. pair = set.GetSequence(); pair.Skip(ASN1Type.ObjectIdentifier); if(pair.IsString()) { // Add the value to the string we are building. if(builder.Length > 0) { builder.Append(", "); } builder.Append(pair.GetString()); } } } // Convert the result into a name. return builder.ToString(); } // Create a certificate from the contents of a certification file. public static X509Certificate CreateFromCertFile(String filename) { // Read the entire file into memory and create // a certificate from it. FileStream stream = new FileStream(filename, FileMode.Open); byte[] data = new byte [(int)(stream.Length)]; stream.Read(data, 0, data.Length); stream.Close(); return new X509Certificate(data); } // Create a certificate from the contents of a signed certificate file. public static X509Certificate CreateFromSignedFile(String filename) { // Not yet supported - we don't know what the "signed" // file format is supposed to be. throw new NotSupportedException(_("Crypto_CertNotSupp")); } // Compare two certificate objects for equality. Certificates are // considered equal if the issuer and serial numbers are the same. public virtual bool Equals(X509Certificate other) { if(other == null) { return false; } if(issuer != other.issuer || serialNumber.Length != other.serialNumber.Length) { return false; } for(int index = 0; index < serialNumber.Length; ++index) { if(serialNumber[index] != other.serialNumber[index]) { return false; } } return true; } #if CONFIG_FRAMEWORK_2_0 [TODO] public virtual byte[] Export(X509ContentType contentType) { throw new NotImplementedException("Export"); } [TODO] public virtual byte[] Export(X509ContentType contentType, String password) { throw new NotImplementedException("Export"); } #endif // Convert a byte array into a hexadecimal string. private static String ToHex(byte[] array) { if(array == null) { return null; } StringBuilder builder = new StringBuilder(); String hexChars = "01234567abcdef"; for(int index = 0; index < array.Length; ++index) { builder.Append(hexChars[array[index] >> 4]); builder.Append(hexChars[array[index] & 0x0F]); } return builder.ToString(); } // Get the hash of the certificate. public virtual byte[] GetCertHash() { return hash; } // Get the hash of the certificate as a hexadecimal string. public virtual String GetCertHashString() { return ToHex(GetCertHash()); } // Get the effective date of this certificate as a string. public virtual String GetEffectiveDateString() { return effectiveDate; } // Get the expiration date of this certificate as a string. public virtual String GetExpirationDateString() { return expirationDate; } // Get the name of the certificate format. public virtual String GetFormat() { return "X509"; } // Get the hash code for this certificate. public override int GetHashCode() { byte[] certHash = GetCertHash(); int hash = 0; if(certHash != null) { for(int index = 0; index < certHash.Length; ++index) { hash = (hash << 5) + hash + certHash[index]; } } return hash & 0x7FFFFFFF; } // Get the name of the certificate issuer. public virtual String GetIssuerName() { return issuer; } // Get the name of the key algorithm as a hexadecimal string. public virtual String GetKeyAlgorithm() { return keyAlgorithm; } // Get the key algorithm parameters for this certificate. public virtual byte[] GetKeyAlgorithmParameters() { return keyAlgorithmParameters; } // Get the key algorithm parameters for this certificate as a string. public virtual String GetKeyAlgorithmParametersString() { return ToHex(GetKeyAlgorithmParameters()); } // Get the name of the certificate's principal. public virtual String GetName() { return name; } // Get the public key for this certificate. public virtual byte[] GetPublicKey() { return publicKey; } // Get the public key for this certificate as a hexadecimal string. public virtual String GetPublicKeyString() { return ToHex(GetPublicKey()); } // Get the raw data for the certificate. public virtual byte[] GetRawCertData() { return rawData; } // Get the raw data for the certificate as a hexadecimal string. public virtual String GetRawCertDataString() { return ToHex(GetRawCertData()); } // Get the serial number of the certificate. public virtual byte[] GetSerialNumber() { return serialNumber; } // Get the serial number of the certificate as a hexadecimal string. public virtual String GetSerialNumberString() { return ToHex(GetSerialNumber()); } #if CONFIG_FRAMEWORK_2_0 [TODO] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException("GetObjectData"); } [TODO] public IntPtr Handle { get { throw new NotImplementedException("Handle"); } } [TODO] public virtual void Import(byte[] rawData) { throw new NotImplementedException("Import"); } [TODO] public virtual void Import(byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags) { throw new NotImplementedException("Import"); } [TODO] public virtual void Import(String fileName) { throw new NotImplementedException("Import"); } [TODO] public virtual void Import(String fileName, String password, X509KeyStorageFlags keyStorageFlags) { throw new NotImplementedException("Import"); } [TODO] void IDeserializationCallback.OnDeserialization(Object sender) { throw new NotImplementedException("OnDeserialization"); } [TODO] public virtual void Reset() { throw new NotImplementedException("Reset"); } #endif // Get the string represenation of this certificate. public override String ToString() { return ToString(false); } public virtual String ToString(bool verbose) { StringBuilder builder = new StringBuilder(); String newLine; if(verbose) { // Print all of the fields. newLine = Environment.NewLine; builder.Append("Issuer: "); builder.Append(issuer); builder.Append(newLine); builder.Append("Serial Number: "); builder.Append(ToHex(serialNumber)); builder.Append(newLine); builder.Append("Subject: "); builder.Append(name); builder.Append(newLine); builder.Append("Effective Date: "); builder.Append(effectiveDate); builder.Append(newLine); builder.Append("Expiration Date: "); builder.Append(expirationDate); builder.Append(newLine); builder.Append("Key Algorithm: "); builder.Append(keyAlgorithm); builder.Append(newLine); builder.Append("MD5 Hash: "); builder.Append(hash); builder.Append(newLine); } else { // Print the issuer name and serial number only. builder.Append(issuer); builder.Append(", "); builder.Append(ToHex(serialNumber)); } return builder.ToString(); } }; // class X509Certificate #endif // CONFIG_X509_CERTIFICATES }; // namespace System.Security.Cryptography.X509Certificates
using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEditor; #if UNITY_5_3 using UnityEditor.SceneManagement; #endif [CustomEditor(typeof(ETCButton))] public class ETCButtonInspector : Editor { public string[] unityAxes; void OnEnable(){ var inputManager = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]; SerializedObject obj = new SerializedObject(inputManager); SerializedProperty axisArray = obj.FindProperty("m_Axes"); if (axisArray.arraySize > 0){ unityAxes = new string[axisArray.arraySize]; for( int i = 0; i < axisArray.arraySize; ++i ){ var axis = axisArray.GetArrayElementAtIndex(i); unityAxes[i] = axis.FindPropertyRelative("m_Name").stringValue; } } } public override void OnInspectorGUI(){ ETCButton t = (ETCButton)target; EditorGUILayout.Space(); t.gameObject.name = EditorGUILayout.TextField("Button name",t.gameObject.name); t.axis.name = t.gameObject.name; t.activated = ETCGuiTools.Toggle("Activated",t.activated,true); t.visible = ETCGuiTools.Toggle("Visible",t.visible,true); EditorGUILayout.Space(); t.useFixedUpdate = ETCGuiTools.Toggle("Use Fixed Update",t.useFixedUpdate,true); t.isUnregisterAtDisable = ETCGuiTools.Toggle("Unregister at disabling time",t.isUnregisterAtDisable,true); #region Position & Size t.showPSInspector = ETCGuiTools.BeginFoldOut( "Position & Size",t.showPSInspector); if (t.showPSInspector){ ETCGuiTools.BeginGroup();{ // Anchor t.anchor = (ETCBase.RectAnchor)EditorGUILayout.EnumPopup( "Anchor",t.anchor); if (t.anchor != ETCBase.RectAnchor.UserDefined){ t.anchorOffet = EditorGUILayout.Vector2Field("Offset",t.anchorOffet); } EditorGUILayout.Space(); // Area sprite ratio if (t.GetComponent<Image>().sprite != null){ Rect rect = t.GetComponent<Image>().sprite.rect; float ratio = rect.width / rect.height; // Area Size if (ratio>=1){ float s = EditorGUILayout.FloatField("Size", t.rectTransform().rect.width); t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,s); t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,s/ratio); } else{ float s = EditorGUILayout.FloatField("Size", t.rectTransform().rect.height); t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,s); t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,s*ratio); } } }ETCGuiTools.EndGroup(); } #endregion #region Behaviour t.showBehaviourInspector = ETCGuiTools.BeginFoldOut( "Behaviour",t.showBehaviourInspector); if (t.showBehaviourInspector){ ETCGuiTools.BeginGroup();{ EditorGUILayout.Space(); ETCGuiTools.BeginGroup(5);{ t.enableKeySimulation = ETCGuiTools.Toggle("Enable Unity axes",t.enableKeySimulation,true); if (t.enableKeySimulation){ t.allowSimulationStandalone = ETCGuiTools.Toggle("Allow Unity axes on standalone",t.allowSimulationStandalone,true); t.visibleOnStandalone = ETCGuiTools.Toggle("Force visible",t.visibleOnStandalone,true); } }ETCGuiTools.EndGroup(); #region General propertie EditorGUI.indentLevel++; t.axis.showGeneralInspector = EditorGUILayout.Foldout(t.axis.showGeneralInspector,"General setting"); if (t.axis.showGeneralInspector){ ETCGuiTools.BeginGroup(20);{ EditorGUI.indentLevel--; t.isSwipeIn = ETCGuiTools.Toggle("Swipe in",t.isSwipeIn,true); t.isSwipeOut = ETCGuiTools.Toggle("Swipe out",t.isSwipeOut,true); t.axis.isValueOverTime = ETCGuiTools.Toggle("Value over the time",t.axis.isValueOverTime,true); if (t.axis.isValueOverTime){ ETCGuiTools.BeginGroup(5);{ t.axis.overTimeStep = EditorGUILayout.FloatField("Step",t.axis.overTimeStep); t.axis.maxOverTimeValue = EditorGUILayout.FloatField("Max value",t.axis.maxOverTimeValue); }ETCGuiTools.EndGroup(); } t.axis.speed = EditorGUILayout.FloatField("Value",t.axis.speed); EditorGUI.indentLevel++; }ETCGuiTools.EndGroup(); } EditorGUI.indentLevel--; #endregion #region Direct Action EditorGUI.indentLevel++; t.axis.showDirectInspector = EditorGUILayout.Foldout(t.axis.showDirectInspector,"Direction ation"); if (t.axis.showDirectInspector){ ETCGuiTools.BeginGroup(20);{ EditorGUI.indentLevel--; t.axis.autoLinkTagPlayer = EditorGUILayout.ToggleLeft("Auto link on tag",t.axis.autoLinkTagPlayer, GUILayout.Width(200)); if (t.axis.autoLinkTagPlayer){ t.axis.autoTag = EditorGUILayout.TagField("",t.axis.autoTag); } else{ t.axis.directTransform = (Transform)EditorGUILayout.ObjectField("Direct action to",t.axis.directTransform,typeof(Transform),true); } EditorGUILayout.Space(); t.axis.actionOn = (ETCAxis.ActionOn)EditorGUILayout.EnumPopup("Action on",t.axis.actionOn); t.axis.directAction = (ETCAxis.DirectAction ) EditorGUILayout.EnumPopup( "Action",t.axis.directAction); if (t.axis.directAction != ETCAxis.DirectAction.Jump){ t.axis.axisInfluenced = (ETCAxis.AxisInfluenced) EditorGUILayout.EnumPopup("Affected axis",t.axis.axisInfluenced); } else{ EditorGUILayout.HelpBox("Required character controller", MessageType.Info); t.axis.gravity = EditorGUILayout.FloatField("Gravity",t.axis.gravity); } EditorGUI.indentLevel++; }ETCGuiTools.EndGroup(); } EditorGUI.indentLevel--; #endregion #region Unity axis EditorGUI.indentLevel++; t.axis.showSimulatinInspector = EditorGUILayout.Foldout(t.axis.showSimulatinInspector,"Unity axes"); if (t.axis.showSimulatinInspector){ ETCGuiTools.BeginGroup(20);{ EditorGUI.indentLevel--; int index = System.Array.IndexOf(unityAxes,t.axis.unityAxis ); int tmpIndex = EditorGUILayout.Popup(index,unityAxes); if (tmpIndex != index){ t.axis.unityAxis = unityAxes[tmpIndex]; } EditorGUI.indentLevel++; }ETCGuiTools.EndGroup(); } EditorGUI.indentLevel--; #endregion }ETCGuiTools.EndGroup(); } #endregion #region Sprite t.showSpriteInspector = ETCGuiTools.BeginFoldOut( "Sprites",t.showSpriteInspector); if (t.showSpriteInspector){ ETCGuiTools.BeginGroup();{ // Normal state EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck (); t.normalSprite = (Sprite)EditorGUILayout.ObjectField("Normal",t.normalSprite,typeof(Sprite),true,GUILayout.MinWidth(100)); t.normalColor = EditorGUILayout.ColorField("",t.normalColor,GUILayout.Width(50)); if (EditorGUI.EndChangeCheck ()) { t.GetComponent<Image>().sprite = t.normalSprite; t.GetComponent<Image>().color = t.normalColor; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if ( t.normalSprite){ Rect spriteRect = new Rect( t.normalSprite.rect.x/ t.normalSprite.texture.width, t.normalSprite.rect.y/ t.normalSprite.texture.height, t.normalSprite.rect.width/ t.normalSprite.texture.width, t.normalSprite.rect.height/ t.normalSprite.texture.height); GUILayout.Space(8); Rect lastRect = GUILayoutUtility.GetLastRect(); lastRect.x = 20; lastRect.width = 100; lastRect.height = 100; GUILayout.Space(100); ETCGuiTools.DrawTextureRectPreview( lastRect,spriteRect,t.normalSprite.texture,Color.white); } // Press state EditorGUILayout.BeginHorizontal(); t.pressedSprite = (Sprite)EditorGUILayout.ObjectField("Pressed",t.pressedSprite,typeof(Sprite),true,GUILayout.MinWidth(100)); t.pressedColor = EditorGUILayout.ColorField("",t.pressedColor,GUILayout.Width(50)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (t.pressedSprite){ Rect spriteRect = new Rect( t.pressedSprite.rect.x/ t.pressedSprite.texture.width, t.pressedSprite.rect.y/ t.pressedSprite.texture.height, t.pressedSprite.rect.width/ t.pressedSprite.texture.width, t.pressedSprite.rect.height/ t.pressedSprite.texture.height); GUILayout.Space(8); Rect lastRect = GUILayoutUtility.GetLastRect(); lastRect.x = 20; lastRect.width = 100; lastRect.height = 100; GUILayout.Space(100); ETCGuiTools.DrawTextureRectPreview( lastRect,spriteRect,t.pressedSprite.texture,Color.white); } }ETCGuiTools.EndGroup(); } #endregion #region Events t.showEventInspector = ETCGuiTools.BeginFoldOut( "Events",t.showEventInspector); if (t.showEventInspector){ ETCGuiTools.BeginGroup();{ serializedObject.Update(); SerializedProperty down = serializedObject.FindProperty("onDown"); EditorGUILayout.PropertyField(down, true, null); serializedObject.ApplyModifiedProperties(); serializedObject.Update(); SerializedProperty press = serializedObject.FindProperty("onPressed"); EditorGUILayout.PropertyField(press, true, null); serializedObject.ApplyModifiedProperties(); serializedObject.Update(); SerializedProperty pressTime = serializedObject.FindProperty("onPressedValue"); EditorGUILayout.PropertyField(pressTime, true, null); serializedObject.ApplyModifiedProperties(); serializedObject.Update(); SerializedProperty up = serializedObject.FindProperty("onUp"); EditorGUILayout.PropertyField(up, true, null); serializedObject.ApplyModifiedProperties(); }ETCGuiTools.EndGroup(); } #endregion if (t.anchor != ETCBase.RectAnchor.UserDefined){ t.SetAnchorPosition(); } if (GUI.changed){ EditorUtility.SetDirty(t); #if UNITY_5_3 EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene()); #endif } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ExampleWebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System.Collections.Generic; using System.IO; using System.Xml; using Ecosim.SceneData.Action; using Ecosim.EcoScript.Eval; namespace Ecosim.SceneData { public class Scene { public const string XML_ELEMENT = "scene"; public const int OVERVIEW_TEXTURE_SIZE = 1024; public string sceneName; // name of scene public string description; // scene description public int slotNr = -1; // name of savegame slot public SuccessionType[] successionTypes; public PlantType[] plantTypes; public ActionObjectsGroup[] actionObjectGroups; public AnimalType[] animalTypes; public CalculatedData.Calculation[] calculations; public ActionMgr actions; public ReportsMgr reports; public ExportMgr exporter; public Progression progression; public PlayerInfo playerInfo; public Buildings buildings; public Roads roads; public ExtraAssets assets; public Articles articles; public readonly EcoExpression expression; public readonly int width; public readonly int height; public UnityEngine.Texture2D[,] overview; public event System.Action onGameEnd; public Progression GetHistoricProgression (int year) { if (progression != null) { if (year == progression.year) { return progression; } else if (year < progression.startYear) { year = 0; // we have to load default progression info } } return Progression.Load (this, year); } /** * Deletes savegame with given slotnr */ public static void DeleteSaveGame (int slotNr) { string path = GameSettings.GetPathForSlotNr (slotNr); if (Directory.Exists (path)) { Directory.Delete (path, true); } } /** * We do InitActions separate from StartNewGame / LoadExistingGame * to make sure all contexts (like scene variable) have been completely * set up and scripts will work correctly when accessing scene or progression * properties. */ public void InitActions (bool isNewGame) { progression.InitActions (isNewGame); if (isNewGame) { progression.Save (); } } /** * We do InitActions separate from StartNewGame / LoadExistingGame * to make sure all contexts (like scene variable) have been completely * set up and scripts will work correctly when accessing scene or progression * properties. */ public void InitReports (bool isNewGame) { if (!isNewGame) { // Exception: Check if this is the first year still if (progression.startYear >= progression.year) { isNewGame = true; } } if (isNewGame) { reports.Init (); } } /** * Start a new game with scene named name, progress of the game is saved * at slot slotNr. */ public static Scene StartNewGame (string name, int slotNr, PlayerInfo playerInfo) { // first try loading scene Scene scene = Load (name); if (scene != null) { // now create the save game... scene.slotNr = slotNr; // we delete old save game information DeleteSaveGame (slotNr); scene.progression = Progression.Load (scene, 0); // loads initial progression data scene.playerInfo = playerInfo; scene.progression.year = scene.progression.startYear; // start with first year scene.SetupListeners (); // we make an initial save in the slot SaveGame saveGame = new SaveGame (scene); saveGame.Save (scene); scene.UpdateReferences (); bool success = EcoScript.Compiler.LoadAssemblyFromDisk (scene); if (!success) { Log.LogError ("Failed to load EcoScript assembly"); } // scene.progression.InitActions (true); // scene.progression.Save (); } return scene; } /** * Load a saved game at stored at slotNr, if previewOnly == true, only basic scene information is loaded * for showing info about saved game */ public static Scene LoadExistingGame (int slotNr) { SaveGame saveGame = SaveGame.Load (slotNr); if (saveGame == null) { Log.LogError ("Slot " + slotNr + " does not contain a valid savegame"); return null; } Scene scene = Load (saveGame.sceneName); if (scene == null) { Log.LogError ("Scene '" + saveGame.sceneName + "' not found."); return null; } scene.playerInfo = saveGame.playerInfo; scene.slotNr = slotNr; scene.progression = Progression.Load (scene, saveGame.year); if (scene.progression == null) { Log.LogError ("Progression not found."); } scene.SetupListeners (); // Check if the game was already ended if (scene.progression.gameEnded == true) { if (scene.onGameEnd != null) scene.onGameEnd (); } scene.UpdateReferences (); bool success = EcoScript.Compiler.LoadAssemblyFromDisk (scene); if (!success) { Log.LogError ("Failed to load EcoScript assembly"); } // scene.progression.InitActions (false); return scene; } /** * Loads in scene 'name' for editing purposes, no player info will be defined and slotnr = -1 */ public static Scene LoadForEditing (string name, System.Action<string> onError) { Scene scene = Load (name); scene.progression = Progression.Load (scene, 0); // loads initial progression data scene.SetupListeners (); scene.UpdateReferences (); bool success = EcoScript.Compiler.LoadAssemblyFromDisk (scene); if (!success) { string err = "Failed to load EcoScript assembly"; Log.LogError (err); if (onError != null) onError (err); } scene.progression.InitActions (true); return scene; } public static Scene CreateNewScene (string name, int width, int height, SuccessionType[] successionTypes, PlantType[] plantTypes, AnimalType[] animalTypes, ActionObjectsGroup[] actionObjectGroups, CalculatedData.Calculation[] calculations, ActionMgr actionMgr, ManagedDictionary<string, object> variables) { Scene scene = new Scene (name, width, height, successionTypes, plantTypes, animalTypes, actionObjectGroups, calculations); scene.assets = new ExtraAssets (scene); scene.actions = (actionMgr!=null) ? new ActionMgr (scene, actionMgr) : new ActionMgr (scene); scene.reports = new ReportsMgr (scene); scene.buildings = new Buildings (scene); scene.roads = new Roads (scene); scene.progression = new Progression (scene); scene.exporter = new ExportMgr (scene); scene.articles = new Articles (scene); if (variables != null) { scene.progression.variables = variables; } // add the basic data to progression // we start with land at 2m above absolute 0 // we start with water at 1m above absolute 0 HeightMap heightMap = new HeightMap (scene); heightMap.AddAll (200); HeightMap waterHeightMap = new HeightMap (scene); waterHeightMap.AddAll (100); scene.progression.CreateBasicData (); scene.UpdateReferences (); scene.progression.InitActions (true); scene.SetupListeners (); scene.Save (scene.sceneName); return scene; } /** * Forces all current data is loaded into memory * This is useful if an edited scenario is to be saved under * a different name */ public void ForceLoadAllData () { List<string> keys = progression.GetAllDataNames (); foreach (string key in keys) { // force load if not already loaded progression.GetData (key); } } /** * Gives back array with scene preview of all available scenes */ public static Scene[] ListAvailableScenarios () { List<Scene> list = new List<Scene> (); string[] dirs = Directory.GetDirectories (GameSettings.ScenePath); foreach (string dir in dirs) { try { string name = Path.GetFileName (dir); Scene scene = LoadForPreview (name); if (scene != null) { list.Add (scene); } } catch (System.Exception) { } } return list.ToArray (); } /** * Gives back array with slotNrs as index, for used slots a preview of the scene is given, otherwise null */ public static SaveGame[] ListSaveGames () { SaveGame[] saveGames = new SaveGame[GameSettings.MAX_SAVEGAME_SLOTS]; for (int i = 0; i < saveGames.Length; i++) { try { saveGames [i] = SaveGame.Load (i); } catch (System.Exception) { } } return saveGames; } void LoadTiles (string path) { path = path + "Map" + Path.DirectorySeparatorChar; for (int y = 0; y < overview.GetLength (0); y++) { for (int x = 0; x < overview.GetLength (1); x++) { string filePath = path + "tile" + x + "x" + y + ".png"; if (File.Exists (filePath)) { byte[] bytes = File.ReadAllBytes (filePath); UnityEngine.Texture2D tex = new UnityEngine.Texture2D (OVERVIEW_TEXTURE_SIZE, OVERVIEW_TEXTURE_SIZE, UnityEngine.TextureFormat.RGB24, false); tex.LoadImage (bytes); tex.wrapMode = UnityEngine.TextureWrapMode.Clamp; overview [y, x] = tex; } } } } void SaveTiles (string path) { path = path + "Map" + Path.DirectorySeparatorChar; if (!Directory.Exists (path)) { Directory.CreateDirectory (path); } if (Directory.Exists (path)) { for (int y = 0; y < overview.GetLength (0); y++) { for (int x = 0; x < overview.GetLength (1); x++) { if (overview [y, x] != null) { byte[] bytes = overview [y, x].EncodeToPNG (); File.WriteAllBytes (path + "tile" + x + "x" + y + ".png", bytes); } } } } } /** * Save the scene (only for editor use, for game play use SaveProgress, although this actually doesn't * save the scene itself, as it doesn't change during gameplay (but Progression does change)) */ public void Save (string newSceneName) { if (!isSameScene (sceneName, newSceneName)) { CopyIfNeeded (sceneName, newSceneName, "Scripts"); CopyIfNeeded (sceneName, newSceneName, "Assets"); CopyIfNeeded (sceneName, newSceneName, "ArticleData"); sceneName = newSceneName; } string path = GameSettings.GetPathForScene (sceneName); if (!Directory.Exists (path)) { Directory.CreateDirectory (path); } XmlTextWriter writer = new XmlTextWriter (path + "scene.xml", System.Text.Encoding.UTF8); writer.WriteStartDocument (true); writer.WriteStartElement (XML_ELEMENT); writer.WriteAttributeString ("width", width.ToString ()); writer.WriteAttributeString ("height", height.ToString ()); writer.WriteAttributeString ("description", description); writer.WriteEndElement (); writer.WriteEndDocument (); writer.Close (); SaveTiles (path); LoadSaveVegetation.Save (path, successionTypes, this); LoadSavePlants.Save (path, plantTypes, this); LoadSaveAnimals.Save (path, animalTypes, this); ActionObjectsGroup.Save (path, actionObjectGroups, this); CalculatedData.Calculation.Save (path, calculations, this); assets.Save (path); reports.Save (path); buildings.Save (path); roads.Save (path); progression.Save (); articles.Save (path); actions.Save (path); exporter.Save (path); } static Scene Load (string name, XmlTextReader reader) { // budget = long.Parse (reader.GetAttribute ("budget")); int width = int.Parse (reader.GetAttribute ("width")); int height = int.Parse (reader.GetAttribute ("height")); Scene scene = new Scene (name, width, height, new SuccessionType[0], new PlantType[0], new AnimalType[0], new ActionObjectsGroup[0], new CalculatedData.Calculation[0]); scene.description = reader.GetAttribute ("description"); if (!reader.IsEmptyElement) { while (reader.Read()) { XmlNodeType nType = reader.NodeType; if ((nType == XmlNodeType.EndElement) && (reader.Name.ToLower () == XML_ELEMENT)) { break; } } } return scene; } /** * Loads only basic scene info for preview in start new game */ static Scene LoadForPreview (string name) { string path = GameSettings.GetPathForScene (name); Scene scene = null; XmlTextReader reader = new XmlTextReader (new System.IO.StreamReader (path + "scene.xml")); try { while (reader.Read()) { XmlNodeType nType = reader.NodeType; if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == XML_ELEMENT)) { scene = Scene.Load (name, reader); } } } finally { reader.Close (); } return scene; } static Scene Load (string name) { string path = GameSettings.GetPathForScene (name); Scene scene = null; XmlTextReader reader = new XmlTextReader (new System.IO.StreamReader (path + "scene.xml")); try { while (reader.Read()) { XmlNodeType nType = reader.NodeType; if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == XML_ELEMENT)) { scene = Scene.Load (name, reader); } } } finally { reader.Close (); } if (scene != null) { scene.LoadTiles (path); scene.assets = ExtraAssets.Load (path, scene); scene.successionTypes = LoadSaveVegetation.Load (path, scene); scene.plantTypes = LoadSavePlants.Load (path, scene); scene.animalTypes = LoadSaveAnimals.Load (path, scene); scene.calculations = CalculatedData.Calculation.LoadAll (path, scene); EcoTerrainElements.self.AddExtraBuildings (scene.assets); scene.buildings = Buildings.Load (path, scene); scene.actionObjectGroups = ActionObjectsGroup.Load (path, scene); scene.roads = Roads.Load (path, scene); scene.articles = Articles.Load (path, scene); scene.actions = ActionMgr.Load (path, scene); scene.exporter = ExportMgr.Load (path, scene); scene.reports = ReportsMgr.Load (path, scene); } return scene; } /** * Create a new scene with given name, size and optional vegetation (successionTypes) * if vegetation == null a default Succession with one vegetation will be created */ Scene (string name, int width, int height, SuccessionType[] successionTypes, PlantType[] plantTypes, AnimalType[] animalTypes, ActionObjectsGroup[] actionObjectGroups, CalculatedData.Calculation[] calculations) { sceneName = name; description = ""; this.width = width; this.height = height; if (successionTypes != null) { this.successionTypes = successionTypes; } else { this.successionTypes = new SuccessionType[] { }; SuccessionType suc = new SuccessionType (this); new VegetationType (suc); } this.plantTypes = (plantTypes != null) ? plantTypes : new PlantType[] { }; this.animalTypes = (animalTypes != null) ? animalTypes : new AnimalType[] { }; this.actionObjectGroups = (actionObjectGroups != null) ? actionObjectGroups : new ActionObjectsGroup[] { }; this.calculations = (calculations != null) ? calculations : new CalculatedData.Calculation[] { }; overview = new UnityEngine.Texture2D[height / TerrainMgr.CELL_SIZE, width / TerrainMgr.CELL_SIZE]; expression = new EcoExpression (this); } /** * Needs to be called after handling succession * Stores the progress to the gameslot for this game * year must be set to the new year otherwise the progression * will be stored under incorrect year nr. */ public void SaveProgress () { progression.Advance (); } public void UpdateReferences () { actions.UpdateReferences (); exporter.UpdateReferences (); reports.UpdateReferences (); int i = 0; foreach (SuccessionType s in successionTypes) { s.index = i++; } foreach (SuccessionType s in successionTypes) { s.UpdateReferences (this); } i = 0; foreach (PlantType p in plantTypes) { p.index = i++; } foreach (PlantType p in plantTypes) { p.UpdateReferences (this); } i = 0; foreach (AnimalType a in animalTypes) { a.index = i++; } foreach (AnimalType a in animalTypes) { a.UpdateReferences (this); } i = 0; foreach (ActionObjectsGroup g in actionObjectGroups) { g.index = i++; } foreach (ActionObjectsGroup g in actionObjectGroups) { g.UpdateReferences (this); } foreach (CalculatedData.Calculation c in calculations) { c.UpdateReferences (this); } } public static bool isSameScene (string scene1Name, string scene2Name) { string path1 = GameSettings.GetPathForScene (scene1Name); string path2 = GameSettings.GetPathForScene (scene2Name); return (Path.GetFullPath (path1) == Path.GetFullPath (path2)); } private static void CopyIfNeeded (string oldScene, string newScene, string dir) { if (isSameScene (oldScene, newScene)) return; string srcPath = GameSettings.GetPathForScene (oldScene) + dir + Path.DirectorySeparatorChar; string dstPath = GameSettings.GetPathForScene (newScene) + dir + Path.DirectorySeparatorChar; if (!Directory.Exists (srcPath)) return; IOUtil.DirectoryCopy (srcPath, dstPath, true); } public Scene ResizeTo (string newSceneName, int offsetX, int offsetY, int newWidth, int newHeight) { Scene newScene = new Scene (newSceneName, newWidth, newHeight, successionTypes, plantTypes, animalTypes, actionObjectGroups, calculations); Progression newProgression = new Progression (newScene); newScene.progression = newProgression; newScene.SetupListeners (); foreach (string name in progression.GetAllDataNames()) { Data data = progression.GetData (name); Data newData = data.CloneAndResize (newProgression, offsetX, offsetY); newProgression.AddData (name, newData); } CopyIfNeeded (sceneName, newSceneName, "Scripts"); CopyIfNeeded (sceneName, newSceneName, "Assets"); CopyIfNeeded (sceneName, newSceneName, "ArticleData"); string newScenePath = GameSettings.GetPathForScene (newSceneName); actions.Save (newScenePath); newScene.actions = ActionMgr.Load (newScenePath, newScene); exporter.Save (newScenePath); newScene.exporter = ExportMgr.Load (newScenePath, newScene); reports.Save (newScenePath); newScene.reports = ReportsMgr.Load (newScenePath, newScene); articles.Save (newScenePath); newScene.articles = Articles.Load (newScenePath, newScene); assets.Save (newScenePath); newScene.assets = ExtraAssets.Load (newScenePath, newScene); roads.SaveAndClip (newScenePath, offsetX, offsetY, newWidth, newHeight); newScene.roads = Roads.Load (newScenePath, newScene); buildings.SaveAndClip (newScenePath, offsetX, offsetY, newWidth, newHeight); newScene.buildings = Buildings.Load (newScenePath, newScene); newScene.Save (newSceneName); return newScene; } private void SetupListeners () { if (progression != null) { progression.onGameEndChanged -= OnGameEndChanged; progression.onGameEndChanged += OnGameEndChanged; } } private void OnGameEndChanged (bool value) { if (value && this.onGameEnd != null) this.onGameEnd (); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using JobMatcher.Service.Areas.HelpPage.ModelDescriptions; using JobMatcher.Service.Areas.HelpPage.Models; namespace JobMatcher.Service.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//----------------------------------------------------------------------- // <copyright file="SafeDataReaderTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading; using Csla.Test.DataBinding; using System.Data; using System.Data.SqlClient; using System.Configuration; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; using System.Configuration; #endif #if DEBUG namespace Csla.Test.SafeDataReader { [TestClass()] public class SafeDataReaderTests { [TestInitialize] public void Initialize() { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); } //pull from ConfigurationManager private static string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["Csla.Test.Properties.Settings.DataPortalTestDatabaseConnectionString"].ConnectionString; public void ClearDataBase() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = new SqlCommand("DELETE FROM Table2", cn); try { cn.Open(); cm.ExecuteNonQuery(); } catch (Exception ex) { //do nothing } finally { cn.Close(); } } [TestMethod()] public void CloseSafeDataReader() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName FROM Table2"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { Assert.AreEqual(false, dr.IsClosed); dr.Close(); Assert.AreEqual(true, dr.IsClosed); } } } [TestMethod()] public void TestFieldCount() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName, LastName FROM Table2"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { Assert.IsTrue(dr.FieldCount > 0); Assert.AreEqual(false, dr.NextResult()); dr.Close(); } cn.Close(); } } [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public void GetSchemaTable() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); DataTable dtSchema = null; cm.CommandText = "SELECT * FROM MultiDataTypes"; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dtSchema = dr.GetSchemaTable(); dr.Close(); } } cn.Close(); Assert.AreEqual("BIGINTFIELD", dtSchema.Rows[0][0]); Assert.AreEqual(typeof(System.Int64), dtSchema.Rows[0][12]); Assert.AreEqual(typeof(System.Byte[]), dtSchema.Rows[1][12]); } [TestMethod()] public void IsDBNull() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); cm.CommandText = "SELECT TEXT, BIGINTFIELD, IMAGEFIELD FROM MultiDataTypes"; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dr.Read(); Assert.AreEqual(true, dr.IsDBNull(2)); Assert.AreEqual(false, dr.IsDBNull(1)); dr.Close(); } } cn.Close(); } [TestMethod()] public void GetDataTypes() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); cm.CommandText = "SELECT BITFIELD, CHARFIELD, DATETIMEFIELD, UNIQUEIDENTIFIERFIELD, SMALLINTFIELD, INTFIELD, BIGINTFIELD, TEXT FROM MultiDataTypes"; bool bitfield; char charfield; Csla.SmartDate datetimefield; Guid uniqueidentifierfield; System.Int16 smallintfield; System.Int32 intfield; System.Int64 bigintfield; System.String text; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dr.Read(); bitfield = dr.GetBoolean("BITFIELD"); //this causes an error in vb version (char array initialized to nothing in vb version //and it's initialized with new Char[1] in c# version) charfield = dr.GetChar("CHARFIELD"); datetimefield = dr.GetSmartDate("DATETIMEFIELD"); uniqueidentifierfield = dr.GetGuid("UNIQUEIDENTIFIERFIELD"); smallintfield = dr.GetInt16("SMALLINTFIELD"); intfield = dr.GetInt32("INTFIELD"); bigintfield = dr.GetInt64("BIGINTFIELD"); text = dr.GetString("TEXT"); dr.Close(); } } cn.Close(); Assert.AreEqual(false, bitfield); Assert.AreEqual('z', charfield); Assert.AreEqual("12/13/2005", datetimefield.ToString()); Assert.AreEqual("c0f92820-61b5-11da-8cd6-0800200c9a66", uniqueidentifierfield.ToString()); Assert.AreEqual(32767, smallintfield); Assert.AreEqual(2147483647, intfield); Assert.AreEqual(92233720368547111, bigintfield); Assert.AreEqual("a bunch of text...a bunch of text...a bunch of text...a bunch of text...", text); } [TestMethod()] [ExpectedException(typeof(SqlException))] public void ThrowSqlException() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName FROM NonExistantTable"; Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader()); } } [TestMethod()] public void TestSafeDataReader() { List<string> list = new List<string>(); SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT Name, Date, Age FROM Table1"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { while (dr.Read()) //returns two results { string output = dr.GetString("Name") + ", age " + dr.GetInt32("Age") + ", added on " + dr.GetSmartDate("Date"); Assert.AreEqual("varchar", dr.GetDataTypeName("Name")); Assert.AreEqual(false, dr.IsClosed); list.Add(output); Console.WriteLine(output); } dr.Close(); Assert.AreEqual(true, dr.IsClosed); } cn.Close(); } Assert.AreEqual("Bill, age 56, added on 12/23/2004", list[0]); Assert.AreEqual("Jim, age 33, added on 1/14/2003", list[1]); } } } #endif
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.ObjectModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </remarks> [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class SimpleLayout : Layout { private const int MaxInitialRenderBufferLength = 16384; private int maxRenderedLength; private string fixedText; private string layoutText; private ConfigurationItemFactory configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout(string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.Text = txt; } internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.SetRenderers(renderers, text); } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get { return this.layoutText; } set { LayoutRenderer[] renderers; string txt; renderers = LayoutParser.CompileLayout( this.configurationItemFactory, new SimpleStringReader(value), false, out txt); this.SetRenderers(renderers, txt); } } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText { get { return this.fixedText != null; } } /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText { get { return fixedText; } } /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public ReadOnlyCollection<LayoutRenderer> Renderers { get; private set; } /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout(string text) { return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape(string text) { return text.Replace("${", "${literal:text=${}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var l = new SimpleLayout(text); return l.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current object. /// </returns> public override string ToString() { return "'" + this.Text + "'"; } internal void SetRenderers(LayoutRenderer[] renderers, string text) { this.Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers); if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer) { this.fixedText = ((LiteralLayoutRenderer)this.Renderers[0]).Text; } else { this.fixedText = null; } this.layoutText = text; } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers /// that make up the event. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return this.fixedText; } string cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue; } int initialSize = this.maxRenderedLength; if (initialSize > MaxInitialRenderBufferLength) { initialSize = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialSize); foreach (LayoutRenderer renderer in this.Renderers) { try { renderer.Render(builder, logEvent); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (InternalLogger.IsWarnEnabled) { InternalLogger.Warn("Exception in {0}.Append(): {1}.", renderer.GetType().FullName, exception); } } } if (builder.Length > this.maxRenderedLength) { this.maxRenderedLength = builder.Length; } string value = builder.ToString(); logEvent.AddCachedLayoutValue(this, value); return value; } } }
using System.Collections; using System.Collections.Generic; namespace UnicornHack.Utils.DataStructures { public class PriorityQueue<T> : ISnapshotableCollection<T> { private readonly List<T> _list = new List<T>(); private readonly IComparer<T> _comparer; public PriorityQueue() : this(Comparer<T>.Default, 0) { } public PriorityQueue(IComparer<T> comparer) : this(comparer, 0) { } public PriorityQueue(IComparer<T> comparer, int capacity) { _comparer = comparer; if (capacity != 0) { _list.Capacity = capacity; } } public PriorityQueue(IEnumerable<T> source) : this(source, Comparer<T>.Default) { } public PriorityQueue(IEnumerable<T> source, IComparer<T> comparer) : this(comparer, 0) { foreach (var element in source) { Push(element); } } public PriorityQueue(ICollection<T> source) : this(source, Comparer<T>.Default) { } public PriorityQueue(ICollection<T> source, IComparer<T> comparer) : this(comparer, source.Count) { foreach (var element in source) { Push(element); } } public int Count => _list.Count; public HashSet<T> Snapshot { get; private set; } public HashSet<T> CreateSnapshot() { if (Snapshot == null) { Snapshot = new HashSet<T>(_list); } else { Snapshot.Clear(); Snapshot.AddRange(_list); } return Snapshot; } public int Push(T element) { var newElementPosition = _list.Count; _list.Add(element); return BubbleUp(newElementPosition); } public T Pop() => RemoveAt(0); public bool Remove(T item) { var i = GetPosition(item); if (i == -1) { return false; } RemoveAt(i); return true; } private T RemoveAt(int position) { var result = _list[position]; _list[position] = _list[_list.Count - 1]; _list.RemoveAt(_list.Count - 1); if (position != _list.Count) { BubbleDown(position); } return result; } public void Clear() => _list.Clear(); public int Update(int position) { var newPosition = BubbleUp(position); return newPosition != position ? newPosition : BubbleDown(newPosition); } public int Update(T item) => Update(GetPosition(item)); private int BubbleUp(int position) { while (position != 0) { var parentPosition = (position - 1) >> 1; if (CompareItemsAt(parentPosition, position) <= 0) { break; } SwitchElements(parentPosition, position); position = parentPosition; } return position; } private int BubbleDown(int position) { while (true) { var parentPosition = position; var leftChildPosition = (position << 1) + 1; var rightChildPosition = (position << 1) + 2; if (_list.Count > leftChildPosition && CompareItemsAt(position, leftChildPosition) > 0) { position = leftChildPosition; } if (_list.Count > rightChildPosition && CompareItemsAt(position, rightChildPosition) > 0) { position = rightChildPosition; } if (position == parentPosition) { break; } SwitchElements(position, parentPosition); } return position; } public T Peek() => _list.Count > 0 ? _list[index: 0] : default; private int GetPosition(T item) { for (var i = 0; i < _list.Count; i++) { if (item.Equals(_list[i])) { return i; } } return -1; } private void SwitchElements(int i, int j) { var temp = _list[i]; _list[i] = _list[j]; _list[j] = temp; } private int CompareItemsAt(int i, int j) => _comparer.Compare(_list[i], _list[j]); bool ICollection<T>.IsReadOnly => false; void ICollection<T>.Add(T item) => Push(item); bool ICollection<T>.Contains(T item) => GetPosition(item) != -1; void ICollection<T>.CopyTo(T[] array, int arrayIndex) { for (var i = 0; i < _list.Count; i++) { array[i + arrayIndex] = _list[i]; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Magecrawl.Actors; using Magecrawl.GameEngine.Interface; using Magecrawl.Interfaces; using Magecrawl.Items; using Magecrawl.StatusEffects; using Magecrawl.StatusEffects.Interfaces; using Magecrawl.Utilities; namespace Magecrawl.GameEngine.Magic { internal class MagicEffectsEngine { private CombatEngine m_combatEngine; private PhysicsEngine m_physicsEngine; private EffectEngine m_effectEngine; internal MagicEffectsEngine(PhysicsEngine physicsEngine, CombatEngine combatEngine) { m_combatEngine = combatEngine; m_physicsEngine = physicsEngine; m_effectEngine = new EffectEngine(CoreGameEngineInterface.Instance); } internal bool CastSpell(Player caster, Spell spell, Point target) { if (caster.CouldCastSpell(spell)) { string effectString = string.Format("{0} casts {1}.", caster.Name, spell.Name); if (DoEffect(caster, spell, spell, caster.SpellStrength(spell.School), true, target, effectString)) { caster.SpendMP(spell.Cost); return true; } } return false; } internal bool UseItemWithEffect(Character invoker, Item item, Point targetedPoint) { if (!item.ContainsAttribute("Invokable")) throw new System.InvalidOperationException("UseItemWithEffect without invokable object? - " + item.DisplayName); string effectString = string.Format(item.GetAttribute("OnInvokeString"), invoker.Name, item.DisplayName); Spell spellEffect = SpellFactory.Instance.CreateSpell(item.GetAttribute("InvokeSpellEffect")); return DoEffect(invoker, item, spellEffect, int.Parse(item.GetAttribute("CasterLevel"), CultureInfo.InvariantCulture), false, targetedPoint, effectString); } internal List<Point> TargettedDrawablePoints(string spellName, int strength, Point target) { return TargettedDrawablePoints(SpellFactory.Instance.CreateSpell(spellName).Targeting, strength, target); } internal List<Point> TargettedDrawablePoints(TargetingInfo targeting, int strength, Point target) { switch (targeting.Type) { case TargetingInfo.TargettingType.Stream: { List<Point> returnList = m_physicsEngine.GenerateBlastListOfPoints(CoreGameEngine.Instance.Map, CoreGameEngine.Instance.Player.Position, target, false); // 5 being the stream length - XXX where better to put this? TrimPath(5, returnList); Point playerPosition = CoreGameEngine.Instance.Player.Position; m_physicsEngine.FilterNotTargetablePointsFromList(returnList, playerPosition, CoreGameEngine.Instance.Player.Vision, true); return returnList; } case TargetingInfo.TargettingType.RangedBlast: { List<Point> returnList = m_physicsEngine.GenerateBlastListOfPointsShowBounceIfSeeWall(CoreGameEngine.Instance.Map, CoreGameEngine.Instance.Player, target); TrimPathDueToSpellLength(strength, returnList); return returnList; } case TargetingInfo.TargettingType.Cone: { Point playerPosition = CoreGameEngine.Instance.Player.Position; Direction direction = PointDirectionUtils.ConvertTwoPointsToDirection(playerPosition, target); List<Point> returnList = PointListUtils.PointListFromCone(playerPosition, direction, 3); m_physicsEngine.FilterNotTargetablePointsFromList(returnList, playerPosition, CoreGameEngine.Instance.Player.Vision, true); CoreGameEngine.Instance.FilterNotVisibleBothWaysFromList(target, returnList); return returnList; } case TargetingInfo.TargettingType.RangedExplodingPoint: { List<Point> returnList = PointListUtils.PointListFromBurstPosition(target, 2); m_physicsEngine.FilterNotTargetablePointsFromList(returnList, CoreGameEngine.Instance.Player.Position, CoreGameEngine.Instance.Player.Vision, true); CoreGameEngine.Instance.FilterNotVisibleBothWaysFromList(target, returnList); return returnList; } case TargetingInfo.TargettingType.RangedSingle: case TargetingInfo.TargettingType.Self: default: return null; } } private static void DamageDoneDelegate(int damage, Character target, bool targetKilled) { string centerString = targetKilled ? "was killed ({0} damage)" : "took {0} damage"; string prefix = target is IPlayer ? "" : "The "; CoreGameEngine.Instance.SendTextOutput(string.Format("{0}{1} {2}.", prefix, target.Name, string.Format(centerString, damage))); } private bool DoEffect(Character invoker, object invokingMethod, Spell spell, int strength, bool couldBeLongTerm, Point target, string printOnEffect) { switch (spell.EffectType) { case "HealCaster": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); int amountToHeal = (new DiceRoll(20, 3, 0)).Roll(); for (int i = 1 ; i < strength ; ++i) amountToHeal += (new DiceRoll(6, 3, 0)).Roll(); int healAmount = invoker.Heal(amountToHeal, true); CoreGameEngine.Instance.SendTextOutput(string.Format("{0} was healed for {1} health.", invoker.Name, healAmount)); return true; } case "HealMPCaster": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); Player player = invoker as Player; if (player != null) { player.GainMP((new DiceRoll(strength, 3, 4)).Roll()); } return true; } case "RangedSingleTarget": { // This will call ShowRangedAttack inside. CoreGameEngine.Instance.SendTextOutput(printOnEffect); return m_combatEngine.RangedBoltToLocation(invoker, target, CalculateDamgeFromSpell(spell, strength), invokingMethod, DamageDoneDelegate); } case "Stream": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); List<Point> pathOfBlast = m_physicsEngine.GenerateBlastListOfPoints(CoreGameEngine.Instance.Map, invoker.Position, target, false); TrimPath(5, pathOfBlast); List<Point> blastToShow = new List<Point>(pathOfBlast); m_physicsEngine.FilterNotTargetablePointsFromList(blastToShow, invoker.Position, CoreGameEngine.Instance.Player.Vision, true); bool targetAtLastPoint = m_combatEngine.FindTargetAtPosition(pathOfBlast.Last()) != null; CoreGameEngine.Instance.ShowRangedAttack(invokingMethod, ShowRangedAttackType.Stream, blastToShow, targetAtLastPoint); foreach (Point p in pathOfBlast) { Character hitCharacter = m_combatEngine.FindTargetAtPosition(p); if (hitCharacter != null) m_combatEngine.DamageTarget(invoker, CalculateDamgeFromSpell(spell, strength), hitCharacter, DamageDoneDelegate); } return true; } case "RangedBlast": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); List<Point> pathOfBlast = m_physicsEngine.GenerateBlastListOfPoints(CoreGameEngine.Instance.Map, invoker.Position, target, true); TrimPathDueToSpellLength(strength, pathOfBlast); List<Point> blastToShow = new List<Point>(pathOfBlast); m_physicsEngine.FilterNotTargetablePointsFromList(blastToShow, invoker.Position, CoreGameEngine.Instance.Player.Vision, true); CoreGameEngine.Instance.ShowRangedAttack(invokingMethod, ShowRangedAttackType.RangedBlast, blastToShow, false); foreach (Point p in pathOfBlast) { Character hitCharacter = m_combatEngine.FindTargetAtPosition(p); if (hitCharacter != null) m_combatEngine.DamageTarget(invoker, CalculateDamgeFromSpell(spell, strength), hitCharacter, DamageDoneDelegate); } return true; } case "ConeAttack": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); Direction direction = PointDirectionUtils.ConvertTwoPointsToDirection(invoker.Position, target); List<Point> pointsInConeAttack = PointListUtils.PointListFromCone(invoker.Position, direction, 3); CoreGameEngine.Instance.FilterNotVisibleBothWaysFromList(target, pointsInConeAttack); if (pointsInConeAttack == null || pointsInConeAttack.Count == 0) throw new InvalidOperationException("Cone magical attack with nothing to roast?"); ShowConeAttack(invoker, invokingMethod, pointsInConeAttack); foreach (Point p in pointsInConeAttack) { Character hitCharacter = m_combatEngine.FindTargetAtPosition(p); if (hitCharacter != null) m_combatEngine.DamageTarget(invoker, CalculateDamgeFromSpell(spell, strength), hitCharacter, DamageDoneDelegate); } return true; } case "ExplodingRangedPoint": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); const int BurstWidth = 2; ShowExplodingRangedPointAttack(invoker, invokingMethod, target, BurstWidth); List<Point> pointsToEffect = PointListUtils.PointListFromBurstPosition(target, BurstWidth); CoreGameEngine.Instance.FilterNotVisibleBothWaysFromList(target, pointsToEffect); foreach (Point p in pointsToEffect) { Character hitCharacter = m_combatEngine.FindTargetAtPosition(p); if (hitCharacter != null) m_combatEngine.DamageTarget(invoker, CalculateDamgeFromSpell(spell, strength), hitCharacter, DamageDoneDelegate); } return true; } case "Haste": // Should also be added to GetLongTermEffectSpellWouldProduce() case "Light": case "ArmorOfLight": { // These spells can be long term return m_effectEngine.AddEffectToTarget(spell.EffectType, invoker, strength, couldBeLongTerm, target, printOnEffect); } case "Regeneration": case "WordOfHope": { // These spells can't be long term return m_effectEngine.AddEffectToTarget(spell.EffectType, invoker, strength, false, target, printOnEffect); } case "Poison Bolt": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); bool successInRangedBolt = m_combatEngine.RangedBoltToLocation(invoker, target, 1, invokingMethod, DamageDoneDelegate); if (successInRangedBolt) m_effectEngine.AddEffectToTarget("Poison", invoker, strength, false, target); return successInRangedBolt; } case "Slow": { return m_effectEngine.AddEffectToTarget("Slow", invoker, strength, false, target, printOnEffect); } case "Blink": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); HandleRandomTeleport(invoker, 5); return true; } case "Teleport": { CoreGameEngine.Instance.SendTextOutput(printOnEffect); HandleRandomTeleport(invoker, 25); return true; } default: throw new InvalidOperationException("MagicEffectsEngine::DoEffect - don't know how to do: " + spell.EffectType); } } public ILongTermStatusEffect GetLongTermEffectSpellWouldProduce(string effectName) { switch (effectName) { case "Haste": case "Light": case "ArmorOfLight": return (ILongTermStatusEffect)EffectFactory.CreateEffectBaseObject(effectName, true); default: return null; } } private void ShowExplodingRangedPointAttack(Character invoker, object invokingMethod, Point target, int burstWidth) { List<Point> pointsInBallPath = RangedAttackPathfinder.RangedListOfPoints(CoreGameEngine.Instance.Map, invoker.Position, target, false, false); List<List<Point>> pointsInExplosion = new List<List<Point>>(); for (int i = 1; i <= burstWidth; ++i) { List<Point> explosionRing = PointListUtils.PointListFromBurstPosition(target, i); CoreGameEngine.Instance.FilterNotVisibleBothWaysFromList(target, explosionRing); CoreGameEngine.Instance.FilterNotTargetablePointsFromList(explosionRing, invoker.Position, invoker.Vision, true); pointsInExplosion.Add(explosionRing); } var pathData = new Pair<List<Point>, List<List<Point>>>(pointsInBallPath, pointsInExplosion); CoreGameEngine.Instance.ShowRangedAttack(invokingMethod, ShowRangedAttackType.RangedExplodingPoint, pathData, false); } private static void ShowConeAttack(Character invoker, object invokingMethod, List<Point> pointsInConeAttack) { List<Point> coneBlastList = new List<Point>(pointsInConeAttack); CoreGameEngine.Instance.FilterNotTargetablePointsFromList(coneBlastList, invoker.Position, invoker.Vision, true); CoreGameEngine.Instance.ShowRangedAttack(invokingMethod, ShowRangedAttackType.Cone, coneBlastList, false); } private static int CalculateDamgeFromSpell(Spell spell, int strength) { int damage = spell.BaseDamage.Roll(); for (int i = 1; i < strength; ++i) damage += spell.DamagePerLevel.Roll(); return damage; } private static void TrimPath(int range, List<Point> pathOfBlast) { if (pathOfBlast == null) return; pathOfBlast.TrimToLength(range); } private static void TrimPathDueToSpellLength(int strength, List<Point> pathOfBlast) { if (pathOfBlast == null) return; int range = Math.Max(2 * strength, 10); pathOfBlast.TrimToLength(range); } private delegate void OnRangedEffect(Character c, int strength); private bool HandleRandomTeleport(Character caster, int range) { List<EffectivePoint> targetablePoints = PointListUtils.EffectivePointListFromBurstPosition(caster.Position, range); CoreGameEngine.Instance.FilterNotTargetablePointsFromList(targetablePoints, caster.Position, caster.Vision, false); // If there's no where to go, we're done if (targetablePoints.Count == 0) return true; Random random = new Random(); int element = random.getInt(0, targetablePoints.Count - 1); EffectivePoint pointToTeleport = targetablePoints[element]; CoreGameEngine.Instance.SendTextOutput(string.Format("Things become fuzzy as {0} shifts into a new position.", caster.Name)); m_physicsEngine.WarpToPosition(caster, pointToTeleport.Position); return true; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Management.Automation.Language; using System.Diagnostics; using System.Management.Automation.Host; using System.Management.Automation.Internal.Host; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Runspaces; namespace System.Management.Automation.Internal { /// <summary> /// Defines members used by Cmdlets. /// All Cmdlets must derive from /// <see cref="System.Management.Automation.Cmdlet"/>. /// </summary> /// <remarks> /// Only use <see cref="System.Management.Automation.Internal.InternalCommand"/> /// as a subclass of /// <see cref="System.Management.Automation.Cmdlet"/>. /// Do not attempt to create instances of /// <see cref="System.Management.Automation.Internal.InternalCommand"/> /// independently, or to derive other classes than /// <see cref="System.Management.Automation.Cmdlet"/> from /// <see cref="System.Management.Automation.Internal.InternalCommand"/>. /// </remarks> /// <seealso cref="System.Management.Automation.Cmdlet"/> /// <!-- /// These are the Cmdlet members which are also used by other /// non-public command types. /// /// Ideally this would be an internal class, but C# does not support /// public classes deriving from internal classes. /// --> [DebuggerDisplay("Command = {commandInfo}")] public abstract class InternalCommand { #region private_members internal ICommandRuntime commandRuntime; #endregion private_members #region ctor /// <summary> /// Initializes the new instance of Cmdlet class. /// </summary> /// <remarks> /// The only constructor is internal, so outside users cannot create /// an instance of this class. /// </remarks> internal InternalCommand() { this.CommandInfo = null; } #endregion ctor #region internal_members /// <summary> /// Allows you to access the calling token for this command invocation... /// </summary> /// <value></value> internal IScriptExtent InvocationExtent { get; set; } private InvocationInfo _myInvocation = null; /// <summary> /// Return the invocation data object for this command. /// </summary> /// <value>The invocation object for this command.</value> internal InvocationInfo MyInvocation { get { return _myInvocation ?? (_myInvocation = new InvocationInfo(this)); } } /// <summary> /// Represents the current pipeline object under consideration. /// </summary> internal PSObject currentObjectInPipeline = AutomationNull.Value; /// <summary> /// Gets or sets the current pipeline object under consideration /// </summary> internal PSObject CurrentPipelineObject { get { return currentObjectInPipeline; } set { currentObjectInPipeline = value; } } /// <summary> /// Internal helper. Interface that should be used for interaction with host. /// </summary> internal PSHost PSHostInternal { get { return _CBhost; } } private PSHost _CBhost; /// <summary> /// Internal helper to get to SessionState /// </summary> /// internal SessionState InternalState { get { return _state; } } private SessionState _state; /// <summary> /// Internal helper. Indicates whether stop has been requested on this command. /// </summary> internal bool IsStopping { get { MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime; return (mcr != null && mcr.IsStopping); } } /// <summary> /// The information about the command. /// </summary> private CommandInfo _commandInfo; /// <summary> /// Gets or sets the command information for the command. /// </summary> internal CommandInfo CommandInfo { get { return _commandInfo; } set { _commandInfo = value; } } #endregion internal_members #region public_properties /// <summary> /// Gets or sets the execution context. /// </summary> /// <exception cref="System.ArgumentNullException"> /// may not be set to null /// </exception> internal ExecutionContext Context { get { return _context; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Context"); } _context = value; Diagnostics.Assert(_context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost"); _CBhost = (InternalHost)_context.EngineHostInterface; // Construct the session state API set from the new context _state = new SessionState(_context.EngineSessionState); } } private ExecutionContext _context; /// <summary> /// This property tells you if you were being invoked inside the runspace or /// if it was an external request. /// </summary> public CommandOrigin CommandOrigin { get { return CommandOriginInternal; } } internal CommandOrigin CommandOriginInternal = CommandOrigin.Internal; #endregion public_properties #region Override /// <summary> /// When overridden in the derived class, performs initialization /// of command execution. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoBeginProcessing() { } /// <summary> /// When overridden in the derived class, performs execution /// of the command. /// </summary> internal virtual void DoProcessRecord() { } /// <summary> /// When overridden in the derived class, performs clean-up /// after the command execution. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoEndProcessing() { } /// <summary> /// When overridden in the derived class, interrupts currently /// running code within the command. It should interrupt BeginProcessing, /// ProcessRecord, and EndProcessing. /// Default implementation in the base class just returns. /// </summary> internal virtual void DoStopProcessing() { } #endregion Override /// <summary> /// throws if the pipeline is stopping /// </summary> /// <exception cref="System.Management.Automation.PipelineStoppedException"></exception> internal void ThrowIfStopping() { if (IsStopping) throw new PipelineStoppedException(); } #region Dispose /// <summary> /// IDisposable implementation /// When the command is complete, release the associated members /// </summary> /// <remarks> /// Using InternalDispose instead of Dispose pattern because this /// interface was shipped in PowerShell V1 and 3rd cmdlets indirectly /// derive from this interface. If we depend on Dispose() and 3rd /// party cmdlets do not call base.Dispose (which is the case), we /// will still end up having this leak. /// </remarks> internal void InternalDispose(bool isDisposing) { _myInvocation = null; _state = null; _commandInfo = null; _context = null; } #endregion } } namespace System.Management.Automation { #region ActionPreference /// <summary> /// Defines the Action Preference options. These options determine /// what will happen when a particular type of event occurs. /// For example, setting shell variable ErrorActionPreference to "Stop" /// will cause the command to stop when an otherwise non-terminating /// error occurs. /// </summary> public enum ActionPreference { /// <summary>Ignore this event and continue</summary> SilentlyContinue, /// <summary>Stop the command</summary> Stop, /// <summary>Handle this event as normal and continue</summary> Continue, /// <summary>Ask whether to stop or continue</summary> Inquire, /// <summary>Ignore the event completely (not even logging it to the target stream)</summary> Ignore, /// <summary>Suspend the command for further diagnosis. Supported only for workflows.</summary> Suspend, } // enum ActionPreference #endregion ActionPreference #region ConfirmImpact /// <summary> /// Defines the ConfirmImpact levels. These levels describe /// the "destructiveness" of an action, and thus the degree of /// important that the user confirm the action. /// For example, setting the read-only flag on a file might be Low, /// and reformatting a disk might be High. /// These levels are also used in $ConfirmPreference to describe /// which operations should be confirmed. Operations with ConfirmImpact /// equal to or greater than $ConfirmPreference are confirmed. /// Operations with ConfirmImpact.None are never confirmed, and /// no operations are confirmed when $ConfirmPreference is ConfirmImpact.None /// (except when explicitly requested with -Confirm). /// </summary> public enum ConfirmImpact { /// <summary>There is never any need to confirm this action.</summary> None, /// <summary> /// This action only needs to be confirmed when the /// user has requested that low-impact changes must be confirmed. /// </summary> Low, /// <summary> /// This action should be confirmed in most scenarios where /// confirmation is requested. /// </summary> Medium, /// <summary> /// This action is potentially highly "destructive" and should be /// confirmed by default unless otherwise specified. /// </summary> High, } // enum ConfirmImpact #endregion ConfirmImpact /// <summary> /// Defines members and overrides used by Cmdlets. /// All Cmdlets must derive from <see cref="System.Management.Automation.Cmdlet"/>. /// </summary> /// <remarks> /// There are two ways to create a Cmdlet: by deriving from the Cmdlet base class, and by /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// The public members defined by the PSCmdlet class are not designed to be overridden; instead, they /// provided access to different aspects of the MSH runtime. /// In both cases, users should first develop and implement an object model to accomplish their /// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer. /// </remarks> /// <seealso cref="System.Management.Automation.Internal.InternalCommand"/> public abstract partial class PSCmdlet : Cmdlet { #region private_members private ProviderIntrinsics _invokeProvider = null; #endregion private_members #region public_properties /// <summary> /// Gets the host interaction APIs. /// </summary> public PSHost Host { get { using (PSTransactionManager.GetEngineProtectionScope()) { return PSHostInternal; } } } /// <summary> /// Gets the instance of session state for the current runspace. /// </summary> public SessionState SessionState { get { using (PSTransactionManager.GetEngineProtectionScope()) { return this.InternalState; } } } // SessionState /// <summary> /// Gets the event manager for the current runspace. /// </summary> public PSEventManager Events { get { using (PSTransactionManager.GetEngineProtectionScope()) { return this.Context.Events; } } } // Events /// <summary> /// Repository for jobs /// </summary> public JobRepository JobRepository { get { using (PSTransactionManager.GetEngineProtectionScope()) { return ((LocalRunspace)this.Context.CurrentRunspace).JobRepository; } } } /// <summary> /// Manager for JobSourceAdapters registered. /// </summary> public JobManager JobManager { get { using (PSTransactionManager.GetEngineProtectionScope()) { return ((LocalRunspace)this.Context.CurrentRunspace).JobManager; } } } /// <summary> /// Repository for runspaces /// </summary> internal RunspaceRepository RunspaceRepository { get { return ((LocalRunspace)this.Context.CurrentRunspace).RunspaceRepository; } } /// <summary> /// Gets the instance of the provider interface APIs for the current runspace. /// </summary> public ProviderIntrinsics InvokeProvider { get { using (PSTransactionManager.GetEngineProtectionScope()) { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } } } // InvokeProvider #region Provider wrappers /// <Content contentref="System.Management.Automation.PathIntrinsics.CurrentProviderLocation" /> public PathInfo CurrentProviderLocation(string providerId) { using (PSTransactionManager.GetEngineProtectionScope()) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } PathInfo result = SessionState.Path.CurrentProviderLocation(providerId); Diagnostics.Assert(result != null, "DataStoreAdapterCollection.GetNamespaceCurrentLocation() should " + "throw an exception, not return null"); return result; } } /// <Content contentref="System.Management.Automation.PathIntrinsics.GetUnresolvedProviderPathFromPSPath" /> public string GetUnresolvedProviderPathFromPSPath(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); } } // GetUnresolvedProviderPathFromPSPath /// <Content contentref="System.Management.Automation.PathIntrinsics.GetResolvedProviderPathFromPSPath" /> public Collection<string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider) { using (PSTransactionManager.GetEngineProtectionScope()) { return SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); } } // GetResolvedProviderPathFromPSPath #endregion Provider wrappers #endregion internal_members #region ctor /// <summary> /// Initializes the new instance of PSCmdlet class. /// </summary> /// <remarks> /// Only subclasses of <see cref="System.Management.Automation.Cmdlet"/> /// can be created. /// </remarks> protected PSCmdlet() { } #endregion ctor #region public_methods #region PSVariable APIs /// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" /> public object GetVariableValue(string name) { using (PSTransactionManager.GetEngineProtectionScope()) { return this.SessionState.PSVariable.GetValue(name); } } // GetVariableValue /// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" /> public object GetVariableValue(string name, object defaultValue) { using (PSTransactionManager.GetEngineProtectionScope()) { return this.SessionState.PSVariable.GetValue(name, defaultValue); } } // GetVariableValue #endregion PSVariable APIs #region Parameter methods #endregion Parameter methods #endregion public_methods } // PSCmdlet }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class implements a set of methods for comparing // strings. // // //////////////////////////////////////////////////////////////////////////// using System.Reflection; using System.Diagnostics; using System.Runtime.Serialization; namespace System.Globalization { [Flags] public enum CompareOptions { None = 0x00000000, IgnoreCase = 0x00000001, IgnoreNonSpace = 0x00000002, IgnoreSymbols = 0x00000004, IgnoreKanaType = 0x00000008, // ignore kanatype IgnoreWidth = 0x00000010, // ignore width OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags. StringSort = 0x20000000, // use string sort method Ordinal = 0x40000000, // This flag can not be used with other flags. } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class CompareInfo : IDeserializationCallback { // Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags. private const CompareOptions ValidIndexMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if Compare() has the right flags. private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Mask used to check if GetHashCodeOfString() has the right flags. private const CompareOptions ValidHashCodeOfStringMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if we have the right flags. private const CompareOptions ValidSortkeyCtorMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // // CompareInfos have an interesting identity. They are attached to the locale that created them, // ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US. // The interesting part is that since haw-US doesn't have its own sort, it has to point at another // locale, which is what SCOMPAREINFO does. [OptionalField(VersionAdded = 2)] private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization) [NonSerialized] private string _sortName; // The name that defines our behavior. [OptionalField(VersionAdded = 3)] private SortVersion m_SortVersion; // Do not rename (binary serialization) // _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant [NonSerialized] private readonly bool _invariantMode = GlobalizationMode.Invariant; private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization. internal CompareInfo(CultureInfo culture) { m_name = culture._name; InitSort(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** Warning: The assembly versioning mechanism is dead! **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if culture is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { // Parameter checking. if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } return GetCompareInfo(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** The purpose of this method is to provide version for CompareInfo tables. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if name is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(string name, Assembly assembly) { if (name == null || assembly == null) { throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } return GetCompareInfo(name); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. ** This method is provided for ease of integration with NLS-based software. **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture. **Exceptions: ** ArgumentException if culture is invalid. ============================================================================*/ // People really shouldn't be calling LCID versions, no custom support public static CompareInfo GetCompareInfo(int culture) { if (CultureData.IsCustomCultureId(culture)) { // Customized culture cannot be created by the LCID. throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture)); } return CultureInfo.GetCultureInfo(culture).CompareInfo; } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture. **Exceptions: ** ArgumentException if name is invalid. ============================================================================*/ public static CompareInfo GetCompareInfo(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } return CultureInfo.GetCultureInfo(name).CompareInfo; } public static unsafe bool IsSortable(char ch) { if (GlobalizationMode.Invariant) { return true; } char *pChar = &ch; return IsSortable(pChar, 1); } public static unsafe bool IsSortable(string text) { if (text == null) { // A null param is invalid here. throw new ArgumentNullException(nameof(text)); } if (text.Length == 0) { // A zero length string is not invalid, but it is also not sortable. return (false); } if (GlobalizationMode.Invariant) { return true; } fixed (char *pChar = text) { return IsSortable(pChar, text.Length); } } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_name = null; } void IDeserializationCallback.OnDeserialization(Object sender) { OnDeserialized(); } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); } private void OnDeserialized() { // If we didn't have a name, use the LCID if (m_name == null) { // From whidbey, didn't have a name CultureInfo ci = CultureInfo.GetCultureInfo(this.culture); m_name = ci._name; } else { InitSort(CultureInfo.GetCultureInfo(m_name)); } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); } ///////////////////////////----- Name -----///////////////////////////////// // // Returns the name of the culture (well actually, of the sort). // Very important for providing a non-LCID way of identifying // what the sort is. // // Note that this name isn't dereferenced in case the CompareInfo is a different locale // which is consistent with the behaviors of earlier versions. (so if you ask for a sort // and the locale's changed behavior, then you'll get changed behavior, which is like // what happens for a version update) // //////////////////////////////////////////////////////////////////////// public virtual string Name { get { Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set"); if (m_name == "zh-CHT" || m_name == "zh-CHS") { return m_name; } return _sortName; } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two strings with the given options. Returns 0 if the // two strings are equal, a number less than 0 if string1 is less // than string2, and a number greater than 0 if string1 is greater // than string2. // //////////////////////////////////////////////////////////////////////// public virtual int Compare(string string1, string string2) { return (Compare(string1, string2, CompareOptions.None)); } public unsafe virtual int Compare(string string1, string string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return String.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } //Our paradigm is that null sorts less than any other string and //that two nulls sort as equal. if (string1 == null) { if (string2 == null) { return (0); // Equal } return (-1); // null < non-null } if (string2 == null) { return (1); // non-null > null } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length); return String.CompareOrdinal(string1, string2); } return CompareString(string1.AsReadOnlySpan(), string2.AsReadOnlySpan(), options); } // TODO https://github.com/dotnet/coreclr/issues/13827: // This method shouldn't be necessary, as we should be able to just use the overload // that takes two spans. But due to this issue, that's adding significant overhead. internal unsafe int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan()); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return string.CompareOrdinal(string1, string2.AsReadOnlySpan()); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } // null sorts less than any other string. if (string2 == null) { return 1; } if (_invariantMode) { return (options & CompareOptions.IgnoreCase) != 0 ? CompareOrdinalIgnoreCase(string1, string2.AsReadOnlySpan()) : string.CompareOrdinal(string1, string2.AsReadOnlySpan()); } return CompareString(string1, string2, options); } // TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly? internal unsafe virtual int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return CompareOrdinalIgnoreCase(string1, string2); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return string.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return (options & CompareOptions.IgnoreCase) != 0 ? CompareOrdinalIgnoreCase(string1, string2) : string.CompareOrdinal(string1, string2); } return CompareString(string1, string2, options); } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the specified regions of the two strings with the given // options. // Returns 0 if the two strings are equal, a number less than 0 if // string1 is less than string2, and a number greater than 0 if // string1 is greater than string2. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2) { return Compare(string1, offset1, length1, string2, offset2, length2, 0); } public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options) { return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1, string2, offset2, string2 == null ? 0 : string2.Length - offset2, options); } public virtual int Compare(string string1, int offset1, string string2, int offset2) { return Compare(string1, offset1, string2, offset2, 0); } public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); if ((length1 != length2) && result == 0) return (length1 > length2 ? 1 : -1); return (result); } // Verify inputs if (length1 < 0 || length2 < 0) { throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 < 0 || offset2 < 0) { throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength); } if (offset2 > (string2 == null ? 0 : string2.Length) - length2) { throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength); } if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } } else if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } // // Check for the null case. // if (string1 == null) { if (string2 == null) { return (0); } return (-1); } if (string2 == null) { return (1); } if (options == CompareOptions.Ordinal) { return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2); return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } return CompareString( string1.AsReadOnlySpan().Slice(offset1, length1), string2.AsReadOnlySpan().Slice(offset2, length2), options); } private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2) { int result = String.CompareOrdinal(string1, offset1, string2, offset2, (length1 < length2 ? length1 : length2)); if ((length1 != length2) && result == 0) { return (length1 > length2 ? 1 : -1); } return (result); } // // CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case. // it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by // calling the OS. // internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB) { Debug.Assert(indexA + lengthA <= strA.Length); Debug.Assert(indexB + lengthB <= strB.Length); return CompareOrdinalIgnoreCase(strA.AsReadOnlySpan().Slice(indexA, lengthA), strB.AsReadOnlySpan().Slice(indexB, lengthB)); } internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int length = Math.Min(strA.Length, strB.Length); int range = length; fixed (char* ap = &strA.DangerousGetPinnableReference()) fixed (char* bp = &strB.DangerousGetPinnableReference()) { char* a = ap; char* b = bp; // in InvariantMode we support all range and not only the ascii characters. char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80); while (length != 0 && (*a <= maxChar) && (*b <= maxChar)) { int charA = *a; int charB = *b; if (charA == charB) { a++; b++; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= 'z' - 'a') charA -= 0x20; if ((uint)(charB - 'a') <= 'z' - 'a') charB -= 0x20; // Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } if (length == 0) return strA.Length - strB.Length; Debug.Assert(!GlobalizationMode.Invariant); range -= length; return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range); } } //////////////////////////////////////////////////////////////////////// // // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsPrefix(string source, string prefix, CompareOptions options) { if (source == null || prefix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)), SR.ArgumentNull_String); } if (prefix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.StartsWith(prefix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return StartsWith(source, prefix, options); } public virtual bool IsPrefix(string source, string prefix) { return (IsPrefix(source, prefix, 0)); } //////////////////////////////////////////////////////////////////////// // // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsSuffix(string source, string suffix, CompareOptions options) { if (source == null || suffix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)), SR.ArgumentNull_String); } if (suffix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.EndsWith(suffix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return EndsWith(source, suffix, options); } public virtual bool IsSuffix(string source, string suffix) { return (IsSuffix(source, suffix, 0)); } //////////////////////////////////////////////////////////////////////// // // IndexOf // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int IndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, char value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, char value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, new string(value, 1), startIndex, count, options, null); } public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex > source.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, value, startIndex, count, options, null); } // The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated // and the caller is passing a valid matchLengthPtr pointer. internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(source != null); Debug.Assert(value != null); Debug.Assert(startIndex >= 0); Debug.Assert(matchLengthPtr != null); *matchLengthPtr = 0; if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex >= source.Length) { return -1; } if (options == CompareOptions.OrdinalIgnoreCase) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } if (_invariantMode) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr); } internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantIndexOf(source, value, startIndex, count, ignoreCase); } return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // LastIndexOf // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int LastIndexOf(String source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, char value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, char value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } if (_invariantMode) return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value.ToString(), startIndex, count, options); } public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } if (_invariantMode) return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value, startIndex, count, options); } internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase); } return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // GetSortKey // // Gets the SortKey for the given string with the given options. // //////////////////////////////////////////////////////////////////////// public virtual SortKey GetSortKey(string source, CompareOptions options) { if (_invariantMode) return InvariantCreateSortKey(source, options); return CreateSortKey(source, options); } public virtual SortKey GetSortKey(string source) { if (_invariantMode) return InvariantCreateSortKey(source, CompareOptions.None); return CreateSortKey(source, CompareOptions.None); } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CompareInfo as the current // instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { CompareInfo that = value as CompareInfo; if (that != null) { return this.Name == that.Name; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CompareInfo. The hash code is guaranteed to be the same for // CompareInfo A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // GetHashCodeOfString // // This internal method allows a method that allows the equivalent of creating a Sortkey for a // string from CompareInfo, and generate a hashcode value from it. It is not very convenient // to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed. // // The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both // the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects // treat the string the same way, this implementation will treat them differently (the same way that // Sortkey does at the moment). // // This method will never be made public itself, but public consumers of it could be created, e.g.: // // string.GetHashCode(CultureInfo) // string.GetHashCode(CompareInfo) // string.GetHashCode(CultureInfo, CompareOptions) // string.GetHashCode(CompareInfo, CompareOptions) // etc. // // (the methods above that take a CultureInfo would use CultureInfo.CompareInfo) // //////////////////////////////////////////////////////////////////////// internal int GetHashCodeOfString(string source, CompareOptions options) { // // Parameter validation // if (null == source) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidHashCodeOfStringMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } return GetHashCodeOfStringCore(source, options); } public virtual int GetHashCode(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (options == CompareOptions.Ordinal) { return source.GetHashCode(); } if (options == CompareOptions.OrdinalIgnoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(source); } // // GetHashCodeOfString does more parameters validation. basically will throw when // having Ordinal, OrdinalIgnoreCase and StringSort // return GetHashCodeOfString(source, options); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // CompareInfo. // //////////////////////////////////////////////////////////////////////// public override string ToString() { return ("CompareInfo - " + this.Name); } public SortVersion Version { get { if (m_SortVersion == null) { if (_invariantMode) { m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0, (byte) (CultureInfo.LOCALE_INVARIANT >> 24), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8), (byte) (CultureInfo.LOCALE_INVARIANT & 0xFF))); } else { m_SortVersion = GetSortVersion(); } } return m_SortVersion; } } public int LCID { get { return CultureInfo.GetCultureInfo(Name).LCID; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void BufferTest() { JsonTextReaderTest.FakeArrayPool arrayPool = new JsonTextReaderTest.FakeArrayPool(); string longString = new string('A', 2000); string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!"; string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!"; for (int i = 0; i < 1000; i++) { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue(longString); writer.WritePropertyName("Prop3"); writer.WriteValue(longEscapedString); writer.WritePropertyName("Prop4"); writer.WriteValue(longerEscapedString); writer.WriteEndObject(); } if ((i + 1) % 100 == 0) { Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count); } } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(3, arrayPool.FreeArrays.Count); } [Test] public void BufferTest_WithError() { JsonTextReaderTest.FakeArrayPool arrayPool = new JsonTextReaderTest.FakeArrayPool(); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); try { // dispose will free used buffers using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue("This is an escaped \n string!"); writer.WriteValue("Error!"); } Assert.Fail(); } catch { } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(1, arrayPool.FreeArrays.Count); } #if !(NET20 || NET35 || NET40 || NETFX_CORE || PORTABLE || PORTABLE40 || DNXCORE50) [Test] public void BufferErroringWithInvalidSize() { JObject o = new JObject { {"BodyHtml", "<h3>Title!</h3>" + Environment.NewLine + new string(' ', 100) + "<p>Content!</p>"} }; JsonArrayPool arrayPool = new JsonArrayPool(); StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; o.WriteTo(writer); } string result = o.ToString(); Assert.AreEqual(@"{ ""BodyHtml"": ""<h3>Title!</h3>\r\n <p>Content!</p>"" }", result); } #endif [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, #if UNITY3D "Input string was not in the correct format: nDigits == 0.", #endif "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, #if UNITY3D @"Argument cannot be null. Parameter name: value", #endif @"Value cannot be null. Parameter name: value"); } } [Test] public void WriteTokenNullCheck() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null); }); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null, true); }); } } [Test] public void TokenTypeOutOfRange() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ArgumentOutOfRangeException ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue)); Assert.AreEqual("token", ex.ParamName); ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue, "test")); Assert.AreEqual("token", ex.ParamName); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { CultureInfo culture = new CultureInfo("en-NZ"); culture.DateTimeFormat.AMDesignator = "a.m."; culture.DateTimeFormat.PMDesignator = "p.m."; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = culture; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) { throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); } c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) { unicodeBuffer = new char[6]; } StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } if (i > lastWritePosition) { if (chars == null) { chars = s.ToCharArray(); } // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) { writer.Write(escapedValue); } else { writer.Write(unicodeBuffer); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) { chars = s.ToCharArray(); } // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } [Test] public void DisposeSupressesFinalization() { UnmanagedResourceFakingJsonWriter.CreateAndDispose(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.AreEqual(1, UnmanagedResourceFakingJsonWriter.DisposalCalls); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) { _writer.Write("}}}"); } else { base.WriteEnd(token); } } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) { return _value; } throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif public class UnmanagedResourceFakingJsonWriter : JsonWriter { public static int DisposalCalls; public static void CreateAndDispose() { ((IDisposable)new UnmanagedResourceFakingJsonWriter()).Dispose(); } public UnmanagedResourceFakingJsonWriter() { DisposalCalls = 0; } protected override void Dispose(bool disposing) { base.Dispose(disposing); ++DisposalCalls; } ~UnmanagedResourceFakingJsonWriter() { Dispose(false); } public override void Flush() { throw new NotImplementedException(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Mono.Addins; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ObjectAdd")] public class ObjectAdd : INonSharedRegionModule { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; #region INonSharedRegionModule Members public void Initialise(IConfigSource pSource) { } public void AddRegion(Scene scene) { m_scene = scene; m_scene.EventManager.OnRegisterCaps += RegisterCaps; } public void RemoveRegion(Scene scene) { if (m_scene == scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } } public void RegionLoaded(Scene scene) { } public void Close() { } public string Name { get { return "ObjectAddModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion public void RegisterCaps(UUID agentID, Caps caps) { UUID capuuid = UUID.Random(); // m_log.InfoFormat("[OBJECTADD]: {0}", "/CAPS/OA/" + capuuid + "/"); caps.RegisterHandler( "ObjectAdd", new RestHTTPHandler( "POST", "/CAPS/OA/" + capuuid + "/", httpMethod => ProcessAdd(httpMethod, agentID, caps), "ObjectAdd", agentID.ToString())); ; } public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "Request wasn't what was expected"; ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar)) return responsedata; OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]); if (r.Type != OSDType.Map) // not a proper req return responsedata; //UUID session_id = UUID.Zero; bool bypass_raycast = false; uint everyone_mask = 0; uint group_mask = 0; uint next_owner_mask = 0; uint flags = 0; UUID group_id = UUID.Zero; int hollow = 0; int material = 0; int p_code = 0; int path_begin = 0; int path_curve = 0; int path_end = 0; int path_radius_offset = 0; int path_revolutions = 0; int path_scale_x = 0; int path_scale_y = 0; int path_shear_x = 0; int path_shear_y = 0; int path_skew = 0; int path_taper_x = 0; int path_taper_y = 0; int path_twist = 0; int path_twist_begin = 0; int profile_begin = 0; int profile_curve = 0; int profile_end = 0; Vector3 ray_end = Vector3.Zero; bool ray_end_is_intersection = false; Vector3 ray_start = Vector3.Zero; UUID ray_target_id = UUID.Zero; Quaternion rotation = Quaternion.Identity; Vector3 scale = Vector3.Zero; int state = 0; int lastattach = 0; OSDMap rm = (OSDMap)r; if (rm.ContainsKey("ObjectData")) //v2 { if (rm["ObjectData"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has ObjectData key, but data not in expected format"; return responsedata; } OSDMap ObjMap = (OSDMap)rm["ObjectData"]; bypass_raycast = ObjMap["BypassRaycast"].AsBoolean(); everyone_mask = readuintval(ObjMap["EveryoneMask"]); flags = readuintval(ObjMap["Flags"]); group_mask = readuintval(ObjMap["GroupMask"]); material = ObjMap["Material"].AsInteger(); next_owner_mask = readuintval(ObjMap["NextOwnerMask"]); p_code = ObjMap["PCode"].AsInteger(); if (ObjMap.ContainsKey("Path")) { if (ObjMap["Path"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has Path key, but data not in expected format"; return responsedata; } OSDMap PathMap = (OSDMap)ObjMap["Path"]; path_begin = PathMap["Begin"].AsInteger(); path_curve = PathMap["Curve"].AsInteger(); path_end = PathMap["End"].AsInteger(); path_radius_offset = PathMap["RadiusOffset"].AsInteger(); path_revolutions = PathMap["Revolutions"].AsInteger(); path_scale_x = PathMap["ScaleX"].AsInteger(); path_scale_y = PathMap["ScaleY"].AsInteger(); path_shear_x = PathMap["ShearX"].AsInteger(); path_shear_y = PathMap["ShearY"].AsInteger(); path_skew = PathMap["Skew"].AsInteger(); path_taper_x = PathMap["TaperX"].AsInteger(); path_taper_y = PathMap["TaperY"].AsInteger(); path_twist = PathMap["Twist"].AsInteger(); path_twist_begin = PathMap["TwistBegin"].AsInteger(); } if (ObjMap.ContainsKey("Profile")) { if (ObjMap["Profile"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has Profile key, but data not in expected format"; return responsedata; } OSDMap ProfileMap = (OSDMap)ObjMap["Profile"]; profile_begin = ProfileMap["Begin"].AsInteger(); profile_curve = ProfileMap["Curve"].AsInteger(); profile_end = ProfileMap["End"].AsInteger(); hollow = ProfileMap["Hollow"].AsInteger(); } ray_end_is_intersection = ObjMap["RayEndIsIntersection"].AsBoolean(); ray_target_id = ObjMap["RayTargetId"].AsUUID(); state = ObjMap["State"].AsInteger(); lastattach = ObjMap["LastAttachPoint"].AsInteger(); try { ray_end = ((OSDArray)ObjMap["RayEnd"]).AsVector3(); ray_start = ((OSDArray)ObjMap["RayStart"]).AsVector3(); scale = ((OSDArray)ObjMap["Scale"]).AsVector3(); rotation = ((OSDArray)ObjMap["Rotation"]).AsQuaternion(); } catch (Exception) { responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; return responsedata; } if (rm.ContainsKey("AgentData")) { if (rm["AgentData"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has AgentData key, but data not in expected format"; return responsedata; } OSDMap AgentDataMap = (OSDMap)rm["AgentData"]; //session_id = AgentDataMap["SessionId"].AsUUID(); group_id = AgentDataMap["GroupId"].AsUUID(); } } else { //v1 bypass_raycast = rm["bypass_raycast"].AsBoolean(); everyone_mask = readuintval(rm["everyone_mask"]); flags = readuintval(rm["flags"]); group_id = rm["group_id"].AsUUID(); group_mask = readuintval(rm["group_mask"]); hollow = rm["hollow"].AsInteger(); material = rm["material"].AsInteger(); next_owner_mask = readuintval(rm["next_owner_mask"]); hollow = rm["hollow"].AsInteger(); p_code = rm["p_code"].AsInteger(); path_begin = rm["path_begin"].AsInteger(); path_curve = rm["path_curve"].AsInteger(); path_end = rm["path_end"].AsInteger(); path_radius_offset = rm["path_radius_offset"].AsInteger(); path_revolutions = rm["path_revolutions"].AsInteger(); path_scale_x = rm["path_scale_x"].AsInteger(); path_scale_y = rm["path_scale_y"].AsInteger(); path_shear_x = rm["path_shear_x"].AsInteger(); path_shear_y = rm["path_shear_y"].AsInteger(); path_skew = rm["path_skew"].AsInteger(); path_taper_x = rm["path_taper_x"].AsInteger(); path_taper_y = rm["path_taper_y"].AsInteger(); path_twist = rm["path_twist"].AsInteger(); path_twist_begin = rm["path_twist_begin"].AsInteger(); profile_begin = rm["profile_begin"].AsInteger(); profile_curve = rm["profile_curve"].AsInteger(); profile_end = rm["profile_end"].AsInteger(); ray_end_is_intersection = rm["ray_end_is_intersection"].AsBoolean(); ray_target_id = rm["ray_target_id"].AsUUID(); //session_id = rm["session_id"].AsUUID(); state = rm["state"].AsInteger(); lastattach = rm["last_attach_point"].AsInteger(); try { ray_end = ((OSDArray)rm["ray_end"]).AsVector3(); ray_start = ((OSDArray)rm["ray_start"]).AsVector3(); rotation = ((OSDArray)rm["rotation"]).AsQuaternion(); scale = ((OSDArray)rm["scale"]).AsVector3(); } catch (Exception) { responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; return responsedata; } } Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false); PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); pbs.PathBegin = (ushort)path_begin; pbs.PathCurve = (byte)path_curve; pbs.PathEnd = (ushort)path_end; pbs.PathRadiusOffset = (sbyte)path_radius_offset; pbs.PathRevolutions = (byte)path_revolutions; pbs.PathScaleX = (byte)path_scale_x; pbs.PathScaleY = (byte)path_scale_y; pbs.PathShearX = (byte)path_shear_x; pbs.PathShearY = (byte)path_shear_y; pbs.PathSkew = (sbyte)path_skew; pbs.PathTaperX = (sbyte)path_taper_x; pbs.PathTaperY = (sbyte)path_taper_y; pbs.PathTwist = (sbyte)path_twist; pbs.PathTwistBegin = (sbyte)path_twist_begin; pbs.HollowShape = (HollowShape)hollow; pbs.PCode = (byte)p_code; pbs.ProfileBegin = (ushort)profile_begin; pbs.ProfileCurve = (byte)profile_curve; pbs.ProfileEnd = (ushort)profile_end; pbs.Scale = scale; pbs.State = (byte)state; pbs.LastAttachPoint = (byte)lastattach; SceneObjectGroup obj = null; ; if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) { // rez ON the ground, not IN the ground // pos.Z += 0.25F; obj = m_scene.AddNewPrim(avatar.UUID, group_id, pos, rotation, pbs); } if (obj == null) return responsedata; SceneObjectPart rootpart = obj.RootPart; rootpart.Shape = pbs; rootpart.Flags |= (PrimFlags)flags; rootpart.EveryoneMask = everyone_mask; rootpart.GroupID = group_id; rootpart.GroupMask = group_mask; rootpart.NextOwnerMask = next_owner_mask; rootpart.Material = (byte)material; obj.InvalidateDeepEffectivePerms(); m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(obj.LocalId)); return responsedata; } private uint readuintval(OSD obj) { byte[] tmp = obj.AsBinary(); if (BitConverter.IsLittleEndian) Array.Reverse(tmp); return Utils.BytesToUInt(tmp); } private string ConvertUintToBytes(uint val) { byte[] resultbytes = Utils.UIntToBytes(val); if (BitConverter.IsLittleEndian) Array.Reverse(resultbytes); return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Security.AccessControl; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.DebugHelpers; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Layout.LargeGraphLayout; using Microsoft.Msagl.Routing; using Color = Microsoft.Msagl.Drawing.Color; using Edge = Microsoft.Msagl.Drawing.Edge; using Ellipse = Microsoft.Msagl.Core.Geometry.Curves.Ellipse; using LineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment; using Point = Microsoft.Msagl.Core.Geometry.Point; using Polyline = Microsoft.Msagl.Core.Geometry.Curves.Polyline; using Rectangle = Microsoft.Msagl.Core.Geometry.Rectangle; using Size = System.Windows.Size; using WpfColor = System.Windows.Media.Color; namespace Microsoft.Msagl.GraphmapsWpfControl { internal class GraphmapsEdge : IViewerEdge, IInvalidatable { readonly LgLayoutSettings lgSettings; internal FrameworkElement LabelFrameworkElement; public GraphmapsEdge(Edge edge, FrameworkElement labelFrameworkElement) { Edge = edge; CurvePath = new Path { Data = GetICurveWpfGeometry(edge.GeometryEdge.Curve), Tag = this }; EdgeAttrClone = edge.Attr.Clone(); if (edge.Attr.ArrowAtSource) SourceArrowHeadPath = new Path { Data = DefiningSourceArrowHead(), Tag = this }; if (edge.Attr.ArrowAtTarget) TargetArrowHeadPath = new Path { Data = DefiningTargetArrowHead(Edge.GeometryEdge.EdgeGeometry, PathStrokeThickness), Tag = this }; SetPathStroke(); if (labelFrameworkElement != null) { LabelFrameworkElement = labelFrameworkElement; Common.PositionFrameworkElement(LabelFrameworkElement, edge.Label.Center, 1); } edge.Attr.VisualsChanged += (a, b) => Invalidate(); } internal IEnumerable<FrameworkElement> FrameworkElements { get { if (lgSettings == null) { if (SourceArrowHeadPath != null) yield return this.SourceArrowHeadPath; if (TargetArrowHeadPath != null) yield return TargetArrowHeadPath; if (CurvePath != null) yield return CurvePath; if ( LabelFrameworkElement != null) yield return LabelFrameworkElement; } else { } } } internal EdgeAttr EdgeAttrClone { get; set; } internal static Geometry DefiningTargetArrowHead(EdgeGeometry edgeGeometry, double thickness) { if (edgeGeometry.TargetArrowhead == null || edgeGeometry.Curve==null) return null; var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, edgeGeometry.Curve.End, edgeGeometry.TargetArrowhead.TipPosition, thickness); return streamGeometry; } } Geometry DefiningSourceArrowHead() { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, Edge.GeometryEdge.Curve.Start, Edge.GeometryEdge.EdgeGeometry.SourceArrowhead.TipPosition, PathStrokeThickness); return streamGeometry; } } public double PathStrokeThickness { get { return PathStrokeThicknessFunc != null ? PathStrokeThicknessFunc() : this.Edge.Attr.LineWidth; } } internal Path CurvePath { get; set; } internal Path SourceArrowHeadPath { get; set; } internal Path TargetArrowHeadPath { get; set; } static internal Geometry GetICurveWpfGeometry(ICurve curve) { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { FillStreamGeometryContext(context, curve); //test freeze for performace streamGeometry.Freeze(); return streamGeometry; } } static void FillStreamGeometryContext(StreamGeometryContext context, ICurve curve) { if (curve == null) return; FillContextForICurve(context, curve); } static internal void FillContextForICurve(StreamGeometryContext context,ICurve iCurve) { context.BeginFigure(Common.WpfPoint(iCurve.Start),false,false); var c = iCurve as Curve; if(c != null) FillContexForCurve(context,c); else { var cubicBezierSeg = iCurve as CubicBezierSegment; if(cubicBezierSeg != null) context.BezierTo(Common.WpfPoint(cubicBezierSeg.B(1)),Common.WpfPoint(cubicBezierSeg.B(2)), Common.WpfPoint(cubicBezierSeg.B(3)),true,false); else { var ls = iCurve as LineSegment; if(ls != null) context.LineTo(Common.WpfPoint(ls.End),true,false); else { var rr = iCurve as RoundedRect; if(rr != null) FillContexForCurve(context,rr.Curve); else { var poly = iCurve as Polyline; if (poly != null) FillContexForPolyline(context, poly); else { var ellipse = iCurve as Ellipse; if (ellipse != null) { // context.LineTo(Common.WpfPoint(ellipse.End),true,false); double sweepAngle = EllipseSweepAngle(ellipse); bool largeArc = Math.Abs(sweepAngle) >= Math.PI; Rectangle box = ellipse.FullBox(); context.ArcTo(Common.WpfPoint(ellipse.End), new Size(box.Width/2, box.Height/2), sweepAngle, largeArc, sweepAngle < 0 ? SweepDirection.Counterclockwise : SweepDirection.Clockwise, true, true); } else { throw new NotImplementedException(); } } } } } } } static void FillContexForPolyline(StreamGeometryContext context,Polyline poly) { for(PolylinePoint pp = poly.StartPoint.Next;pp != null;pp = pp.Next) context.LineTo(Common.WpfPoint(pp.Point),true,false); } static void FillContexForCurve(StreamGeometryContext context,Curve c) { foreach(ICurve seg in c.Segments) { var bezSeg = seg as CubicBezierSegment; if(bezSeg != null) { context.BezierTo(Common.WpfPoint(bezSeg.B(1)), Common.WpfPoint(bezSeg.B(2)),Common.WpfPoint(bezSeg.B(3)),true,false); } else { var ls = seg as LineSegment; if(ls != null) context.LineTo(Common.WpfPoint(ls.End),true,false); else { var ellipse = seg as Ellipse; if(ellipse != null) { // context.LineTo(Common.WpfPoint(ellipse.End),true,false); double sweepAngle = EllipseSweepAngle(ellipse); bool largeArc = Math.Abs(sweepAngle) >= Math.PI; Rectangle box = ellipse.FullBox(); context.ArcTo(Common.WpfPoint(ellipse.End), new Size(box.Width / 2,box.Height / 2), sweepAngle, largeArc, sweepAngle < 0 ? SweepDirection.Counterclockwise : SweepDirection.Clockwise, true,true); } else throw new NotImplementedException(); } } } } public static double EllipseSweepAngle(Ellipse ellipse) { double sweepAngle = ellipse.ParEnd - ellipse.ParStart; return ellipse.OrientedCounterclockwise() ? sweepAngle : -sweepAngle; } public static void AddArrow(StreamGeometryContext context,Point start,Point end, double thickness) { if(thickness > 1) { Point dir = end - start; Point h = dir; double dl = dir.Length; if(dl < 0.001) return; dir /= dl; var s = new Point(-dir.Y,dir.X); double w = 0.5 * thickness; Point s0 = w * s; s *= h.Length * HalfArrowAngleTan; s += s0; double rad = w / HalfArrowAngleCos; context.BeginFigure(Common.WpfPoint(start + s),true,true); context.LineTo(Common.WpfPoint(start - s),true,false); context.LineTo(Common.WpfPoint(end - s0),true,false); context.ArcTo(Common.WpfPoint(end + s0),new Size(rad,rad), Math.PI - ArrowAngle,false,SweepDirection.Clockwise,true,false); } else { Point dir = end - start; double dl = dir.Length; //take into account the widths double delta = Math.Min(dl / 2, thickness + thickness / 2); dir *= (dl - delta) / dl; end = start + dir; dir = dir.Rotate(Math.PI / 2); Point s = dir * HalfArrowAngleTan; context.BeginFigure(Common.WpfPoint(start + s),true,true); context.LineTo(Common.WpfPoint(end),true,true); context.LineTo(Common.WpfPoint(start - s),true,true); } } static readonly double HalfArrowAngleTan = Math.Tan(ArrowAngle * 0.5 * Math.PI / 180.0); static readonly double HalfArrowAngleCos = Math.Cos(ArrowAngle * 0.5 * Math.PI / 180.0); const double ArrowAngle = 30.0; //degrees #region Implementation of IViewerObject public DrawingObject DrawingObject { get { return Edge; } } public bool MarkedForDragging { get; set; } #pragma warning disable 0067 public event EventHandler MarkedForDraggingEvent; public event EventHandler UnmarkedForDraggingEvent; #pragma warning restore 0067 #endregion #region Implementation of IViewerEdge public Edge Edge { get; set; } public IViewerNode Source { get; set; } public IViewerNode Target { get; set; } public double RadiusOfPolylineCorner { get; set; } public GraphmapsLabel GraphmapsLabel { get; set; } #endregion internal void Invalidate(FrameworkElement fe, Rail rail) { var path = fe as Path; if (path != null) SetPathStrokeToRailPath(rail, path); } public void Invalidate() { var vis = Edge.IsVisible ? Visibility.Visible : Visibility.Hidden; foreach (var fe in FrameworkElements) fe.Visibility = vis; if (vis == Visibility.Hidden) return; if (lgSettings != null) { InvalidateForLgCase(); return; } CurvePath.Data = GetICurveWpfGeometry(Edge.GeometryEdge.Curve); if (Edge.Attr.ArrowAtSource) SourceArrowHeadPath.Data = DefiningSourceArrowHead(); if (Edge.Attr.ArrowAtTarget) TargetArrowHeadPath.Data = DefiningTargetArrowHead(Edge.GeometryEdge.EdgeGeometry, PathStrokeThickness); SetPathStroke(); if (GraphmapsLabel != null) ((IInvalidatable) GraphmapsLabel).Invalidate(); } void InvalidateForLgCase() { throw new NotImplementedException(); } void SetPathStroke() { SetPathStrokeToPath(CurvePath); if (SourceArrowHeadPath != null) { SourceArrowHeadPath.Stroke = SourceArrowHeadPath.Fill = Common.BrushFromMsaglColor(Edge.Attr.Color); SourceArrowHeadPath.StrokeThickness = PathStrokeThickness; } if (TargetArrowHeadPath != null) { TargetArrowHeadPath.Stroke = TargetArrowHeadPath.Fill = Common.BrushFromMsaglColor(Edge.Attr.Color); TargetArrowHeadPath.StrokeThickness = PathStrokeThickness; } } public void SetPathStrokeToRailPath(Rail rail, Path path) { path.Stroke = SetStrokeColorForRail(rail); double thickness = 1.0; if (rail.TopRankedEdgeInfoOfTheRail != null) { thickness = Math.Max(5 - Math.Log(rail.MinPassingEdgeZoomLevel, 1.5), 1); } path.StrokeThickness = thickness * PathStrokeThickness / 2; // todo : figure out a way to do it nicer than dividing by 2 //jyoti added this to make the selected edges prominent if (rail.IsHighlighted) { thickness = 2.5; path.StrokeThickness = thickness * PathStrokeThickness / 2; } ///////////////// foreach (var style in Edge.Attr.Styles) { if (style == Drawing.Style.Dotted) { path.StrokeDashArray = new DoubleCollection {1, 1}; } else if (style == Drawing.Style.Dashed) { var f = DashSize(); path.StrokeDashArray = new DoubleCollection {f, f}; //CurvePath.StrokeDashOffset = f; } } } Brush SetStrokeColorForRail(Rail rail) { // road colors: Brushes.PaleVioletRed; Brushes.PaleGoldenrod; Brushes.White; WpfColor brush; //brush = rail.IsHighlighted == false // ? new SolidColorBrush(new System.Windows.Media.Color { // A = 255, //transparency, // R = Edge.Attr.Color.R, // G = Edge.Attr.Color.G, // B = Edge.Attr.Color.B // }) // : Brushes.Red; brush = rail.IsHighlighted ? Brushes.Red.Color : Brushes.SlateGray.Color; if (rail.TopRankedEdgeInfoOfTheRail == null) return new SolidColorBrush(brush); if (lgSettings != null) { /* var col = lgSettings.GetColorForZoomLevel(rail.MinPassingEdgeZoomLevel); brush = ((SolidColorBrush)(new BrushConverter().ConvertFrom(col))).Color; */ //jyoti: changed rail colors if (rail.MinPassingEdgeZoomLevel <= 1) brush = Brushes.LightSkyBlue.Color; //Brushes.DimGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 2) brush = Brushes.LightSkyBlue.Color; //Brushes.SlateGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 3) brush = Brushes.LightGoldenrodYellow.Color; //Brushes.SlateGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 4) brush = Brushes.WhiteSmoke.Color; //Brushes.SlateGray.Color; else brush = Brushes.LightGray.Color; //Brushes.Gray.Color; } else { //jyoti: changed rail colors if (rail.MinPassingEdgeZoomLevel <= 1) brush = Brushes.LightSkyBlue.Color; //Brushes.DimGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 2) brush = Brushes.LightSteelBlue.Color; //Brushes.SlateGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 3) brush = Brushes.LightGoldenrodYellow.Color; //Brushes.SlateGray.Color; else if (rail.MinPassingEdgeZoomLevel <= 4) brush = Brushes.WhiteSmoke.Color; //Brushes.SlateGray.Color; else brush = Brushes.LightGray.Color; //Brushes.Gray.Color; } brush.A = 100; if (rail.IsHighlighted) { //jyoti changed edge selection color //this is a garbage rail if (rail.Color == null || rail.Color.Count == 0) { rail.IsHighlighted = false; } else { int Ax = 0, Rx = 0, Gx = 0, Bx = 0; foreach (var c in rail.Color) { Ax += c.Color.A; Rx += c.Color.R; Gx += c.Color.G; Bx += c.Color.B; } byte Ay = 0, Ry = 0, Gy = 0, By = 0; Ay = (Byte) ((int) (Ax/rail.Color.Count)); Ry = (Byte) ((int) (Rx/rail.Color.Count)); Gy = (Byte) ((int) (Gx/rail.Color.Count)); By = (Byte) ((int) (Bx/rail.Color.Count)); brush = new System.Windows.Media.Color { A = Ay, R = Ry, G = Gy, B = By }; } //jyoti changed edge selection color //if (rail.MinPassingEdgeZoomLevel <= 1) brush = Brushes.Red.Color; //else if (rail.MinPassingEdgeZoomLevel <= 2) brush = new WpfColor{A = 255, R=235, G=48, B=68}; //else brush = new WpfColor { A = 255, R = 229, G = 92, B = 127 }; } if (rail.Weight == 0 && !rail.IsHighlighted ) { brush = new System.Windows.Media.Color { A = 0, R = 0, G = 0, B = 255 }; } return new SolidColorBrush(brush); } void SetPathStrokeToPath(Path path) { path.Stroke = Common.BrushFromMsaglColor(Edge.Attr.Color); path.StrokeThickness = PathStrokeThickness; foreach (var style in Edge.Attr.Styles) { if (style == Drawing.Style.Dotted) { path.StrokeDashArray = new DoubleCollection {1, 1}; } else if (style == Drawing.Style.Dashed) { var f = DashSize(); path.StrokeDashArray = new DoubleCollection {f, f}; //CurvePath.StrokeDashOffset = f; } } } public override string ToString() { return Edge.ToString(); } internal static double dashSize = 0.05; //inches internal Func<double> PathStrokeThicknessFunc; public GraphmapsEdge(Edge edge, LgLayoutSettings lgSettings) { Edge = edge; EdgeAttrClone = edge.Attr.Clone(); this.lgSettings = lgSettings; } internal double DashSize() { var w = PathStrokeThickness; var dashSizeInPoints = dashSize * GraphmapsViewer.DpiXStatic; return dashSize = dashSizeInPoints / w; } internal void RemoveItselfFromCanvas(Canvas graphCanvas) { if(CurvePath!=null) graphCanvas.Children.Remove(CurvePath); if (SourceArrowHeadPath != null) graphCanvas.Children.Remove(SourceArrowHeadPath); if (TargetArrowHeadPath != null) graphCanvas.Children.Remove(TargetArrowHeadPath); if(GraphmapsLabel!=null) graphCanvas.Children.Remove(GraphmapsLabel.FrameworkElement ); } public FrameworkElement CreateFrameworkElementForRail(Rail rail) { var iCurve = rail.Geometry as ICurve; Path fe = null; if (iCurve != null) { fe = (Path)CreateFrameworkElementForRailCurve(rail, iCurve); // test: rounded ends fe.StrokeEndLineCap = PenLineCap.Round; fe.StrokeStartLineCap = PenLineCap.Round; fe.Tag = rail; } return fe; } public FrameworkElement CreateFrameworkElementForRailArrowhead(Rail rail, Arrowhead arrowhead, Point curveAttachmentPoint, byte edgeTransparency) { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, curveAttachmentPoint, arrowhead.TipPosition, PathStrokeThickness); //arrowhead.BasePoint = curveAttachmentPoint; } var path=new Path { Data = streamGeometry, Tag = this }; SetPathStrokeToRailPath(rail, path); return path; } FrameworkElement CreateFrameworkElementForRailCurve(Rail rail, ICurve iCurve) { var path = new Path { Data = GetICurveWpfGeometry(iCurve), }; SetPathStrokeToRailPath(rail, path); return path; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; using Microsoft.Scripting.Ast; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Compiler; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { /// <summary> /// Represents a piece of code. This can reference either a CompiledCode /// object or a Function. The user can explicitly call FunctionCode by /// passing it into exec or eval. /// </summary> [PythonType("code")] public class FunctionCode : IExpressionSerializable { [PythonHidden] internal Delegate Target, LightThrowTarget; // the current target for the function. This can change based upon adaptive compilation, recursion enforcement, and tracing. internal Delegate _normalDelegate; // the normal delegate - this can be a compiled or interpreted delegate. private Compiler.Ast.ScopeStatement _lambda; // the original DLR lambda that contains the code internal readonly string _initialDoc; // the initial doc string private readonly int _localCount; // the number of local variables in the code private readonly int _argCount; // cached locally because it's used during calls w/ defaults private bool _compilingLight; // true if we're compiling for light exceptions private int _exceptionCount; // debugging/tracing support private LambdaExpression _tracingLambda; // the transformed lambda used for tracing/debugging internal Delegate _tracingDelegate; // the delegate used for tracing/debugging, if one has been created. This can be interpreted or compiled. /// <summary> /// This is both the lock that is held while enumerating the threads or updating the thread accounting /// information. It's also a marker CodeList which is put in place when we are enumerating the thread /// list and all additions need to block. /// /// This lock is also acquired whenever we need to calculate how a function's delegate should be created /// so that we don't race against sys.settrace/sys.setprofile. /// </summary> private static CodeList _CodeCreateAndUpdateDelegateLock = new CodeList(); /// <summary> /// Constructor used to create a FunctionCode for code that's been serialized to disk. /// /// Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// </summary> internal FunctionCode(PythonContext context, Delegate code, Compiler.Ast.ScopeStatement scope, string documentation, int localCount) { _normalDelegate = code; _lambda = scope; _argCount = CalculateArgumentCount(); _initialDoc = documentation; // need to take this lock to ensure sys.settrace/sys.setprofile is not actively changing lock (_CodeCreateAndUpdateDelegateLock) { SetTarget(AddRecursionCheck(context, code)); } RegisterFunctionCode(context); } /// <summary> /// Constructor to create a FunctionCode at runtime. /// /// Code constructed this way supports both being interpreted and debugged. When necessary the code will /// be re-compiled or re-interpreted for that specific purpose. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// /// the initial delegate provided here should NOT be the actual code. It should always be a delegate which updates our Target lazily. /// </summary> internal FunctionCode(PythonContext context, Delegate initialDelegate, Compiler.Ast.ScopeStatement scope, string documentation, bool? tracing, bool register) { _lambda = scope; Target = LightThrowTarget = initialDelegate; _initialDoc = documentation; _localCount = scope.Variables == null ? 0 : scope.Variables.Count; _argCount = CalculateArgumentCount(); if (tracing.HasValue) { if (tracing.Value) { _tracingDelegate = initialDelegate; } else { _normalDelegate = initialDelegate; } } if (register) { RegisterFunctionCode(context); } } private static PythonTuple SymbolListToTuple(IList<string> vars) { if (vars != null && vars.Count != 0) { object[] tupleData = new object[vars.Count]; for (int i = 0; i < vars.Count; i++) { tupleData[i] = vars[i]; } return PythonTuple.MakeTuple(tupleData); } else { return PythonTuple.EMPTY; } } private static PythonTuple StringArrayToTuple(string[] closureVars) { if (closureVars != null && closureVars.Length != 0) { return PythonTuple.MakeTuple((object[])closureVars); } else { return PythonTuple.EMPTY; } } /// <summary> /// Registers the current function code in our global weak list of all function codes. /// /// The weak list can be enumerated with GetAllCode(). /// /// Ultimately there are 3 types of threads we care about races with: /// 1. Other threads which are registering function codes /// 2. Threads calling sys.settrace which require the world to stop and get updated /// 3. Threads running cleanup (thread pool thread, or call to gc.collect). /// /// The 1st two must have perfect synchronization. We cannot have a thread registering /// a new function which another thread is trying to update all of the functions in the world. Doing /// so would mean we could miss adding tracing to a thread. /// /// But the cleanup thread can run in parallel to either registrying or sys.settrace. The only /// thing it needs to take a lock for is updating our accounting information about the /// number of code objects are alive. /// </summary> private void RegisterFunctionCode(PythonContext context) { if (_lambda == null) { return; } WeakReference codeRef = new WeakReference(this); CodeList prevCode; lock (_CodeCreateAndUpdateDelegateLock) { Debug.Assert(context._allCodes != _CodeCreateAndUpdateDelegateLock); // we do an interlocked operation here because this can run in parallel w/ the CodeCleanup thread. The // lock only prevents us from running in parallel w/ an update to all of the functions in the world which // needs to be synchronized. do { prevCode = context._allCodes; } while (Interlocked.CompareExchange(ref context._allCodes, new CodeList(codeRef, prevCode), prevCode) != prevCode); if (context._codeCount++ == context._nextCodeCleanup) { // run cleanup of codes on another thread CleanFunctionCodes(context, false); } } } internal static void CleanFunctionCodes(PythonContext context, bool synchronous) { if (synchronous) { CodeCleanup(context); } else { ThreadPool.QueueUserWorkItem(CodeCleanup, context); } } internal void SetTarget(Delegate target) { Target = LightThrowTarget = target; } internal void LightThrowCompile(CodeContext/*!*/ context) { if (++_exceptionCount > 20) { if (!_compilingLight && (object)Target == (object)LightThrowTarget) { _compilingLight = true; if (!IsOnDiskCode) { ThreadPool.QueueUserWorkItem(x => { var pyCtx = context.LanguageContext; bool enableTracing; lock (pyCtx._codeUpdateLock) { enableTracing = context.LanguageContext.EnableTracing; } Delegate target; if (enableTracing) { target = ((LambdaExpression)LightExceptions.Rewrite(GetGeneratorOrNormalLambdaTracing(pyCtx).Reduce())).Compile(); } else { target = ((LambdaExpression)LightExceptions.Rewrite(GetGeneratorOrNormalLambda().Reduce())).Compile(); } lock (pyCtx._codeUpdateLock) { if (context.LanguageContext.EnableTracing == enableTracing) { LightThrowTarget = target; } } }); } } } } private bool IsOnDiskCode { get { if (_lambda is Compiler.Ast.SerializedScopeStatement) { return true; } else if (_lambda is Compiler.Ast.PythonAst) { return ((Compiler.Ast.PythonAst)_lambda).OnDiskProxy; } return false; } } /// <summary> /// Enumerates all function codes for updating the current type of targets we generate. /// /// While enumerating we hold a lock so that users cannot change sys.settrace/sys.setprofile /// until the lock is released. /// </summary> private static IEnumerable<FunctionCode> GetAllCode(PythonContext context) { // only a single thread can enumerate the current FunctionCodes at a time. lock (_CodeCreateAndUpdateDelegateLock) { CodeList curCodeList = Interlocked.Exchange(ref context._allCodes, _CodeCreateAndUpdateDelegateLock); Debug.Assert(curCodeList != _CodeCreateAndUpdateDelegateLock); CodeList initialCode = curCodeList; try { while (curCodeList != null) { WeakReference codeRef = curCodeList.Code; FunctionCode target = (FunctionCode)codeRef.Target; if (target != null) { yield return target; } curCodeList = curCodeList.Next; } } finally { Interlocked.Exchange(ref context._allCodes, initialCode); } } } internal static void UpdateAllCode(PythonContext context) { foreach (FunctionCode fc in GetAllCode(context)) { fc.UpdateDelegate(context, false); } } private static void CodeCleanup(object state) { PythonContext context = (PythonContext)state; // only allow 1 thread at a time to do cleanup (other threads can continue adding) lock (context._codeCleanupLock) { // the bulk of the work is in scanning the list, this proceeeds lock free int removed = 0, kept = 0; CodeList prev = null; CodeList cur = GetRootCodeNoUpdating(context); while (cur != null) { if (!cur.Code.IsAlive) { if (prev == null) { if (Interlocked.CompareExchange(ref context._allCodes, cur.Next, cur) != cur) { // someone else snuck in and added a new code entry, spin and try again. cur = GetRootCodeNoUpdating(context); continue; } cur = cur.Next; removed++; continue; } else { // remove from the linked list, we're the only one who can change this. Debug.Assert(prev.Next == cur); removed++; cur = prev.Next = cur.Next; continue; } } else { kept++; } prev = cur; cur = cur.Next; } // finally update our bookkeeping statistics which requires locking but is fast. lock (_CodeCreateAndUpdateDelegateLock) { // calculate the next cleanup, we want each pass to remove ~50% of all entries const double removalGoal = .50; if (context._codeCount == 0) { // somehow we would have had to queue a bunch of function codes, have 1 thread // clean them up all up, and a 2nd queued thread waiting to clean them up as well. // At the same time there would have to be no live functions defined which means // we're executing top-level code which is causing this to happen. context._nextCodeCleanup = 200; return; } //Console.WriteLine("Removed {0} entries, {1} remain", removed, context._codeCount); Debug.Assert(removed <= context._codeCount); double pctRemoved = (double)removed / (double)context._codeCount; // % of code removed double targetRatio = pctRemoved / removalGoal; // how we need to adjust our last goal // update the total and next node cleanup int newCount = Interlocked.Add(ref context._codeCount, -removed); Debug.Assert(newCount >= 0); // set the new target for cleanup int nextCleanup = targetRatio != 0 ? newCount + (int)(context._nextCodeCleanup / targetRatio) : -1; if (nextCleanup > 0) { // we're making good progress, use the newly calculated next cleanup point context._nextCodeCleanup = nextCleanup; } else { // none or very small amount cleaned up, just schedule a cleanup for sometime in the future. context._nextCodeCleanup += 500; } Debug.Assert(context._nextCodeCleanup >= context._codeCount, String.Format("{0} vs {1} ({2})", context._nextCodeCleanup, context._codeCount, targetRatio)); } } } private static CodeList GetRootCodeNoUpdating(PythonContext context) { CodeList cur = context._allCodes; if (cur == _CodeCreateAndUpdateDelegateLock) { lock (_CodeCreateAndUpdateDelegateLock) { // wait until enumerating thread is done, but it's alright // if we got cur and then an enumeration started (because we'll // just clear entries out) cur = context._allCodes; Debug.Assert(cur != _CodeCreateAndUpdateDelegateLock); } } return cur; } public SourceSpan Span { [PythonHidden] get { return _lambda.Span; } } internal string[] ArgNames { get { return _lambda.ParameterNames; } } internal FunctionAttributes Flags { get { return _lambda.Flags; } } internal bool IsModule { get { return _lambda is Compiler.Ast.PythonAst; } } #region Public constructors /* /// <summary> /// Standard python siganture /// </summary> /// <param name="argcount"></param> /// <param name="nlocals"></param> /// <param name="stacksize"></param> /// <param name="flags"></param> /// <param name="codestring"></param> /// <param name="constants"></param> /// <param name="names"></param> /// <param name="varnames"></param> /// <param name="filename"></param> /// <param name="name"></param> /// <param name="firstlineno"></param> /// <param name="nlotab"></param> /// <param name="freevars"></param> /// <param name="callvars"></param> public FunctionCode(int argcount, int nlocals, int stacksize, int flags, string codestring, object constants, Tuple names, Tuple varnames, string filename, string name, int firstlineno, object nlotab, [DefaultParameterValue(null)]object freevars, [DefaultParameterValue(null)]object callvars) { }*/ #endregion #region Public Python API Surface public PythonTuple co_varnames { get { return SymbolListToTuple(_lambda.GetVarNames()); } } public int co_argcount { get { return _argCount; } } private int CalculateArgumentCount() { int argCnt = _lambda.ArgCount; FunctionAttributes flags = Flags; if ((flags & FunctionAttributes.ArgumentList) != 0) argCnt--; if ((flags & FunctionAttributes.KeywordDictionary) != 0) argCnt--; return argCnt; } /// <summary> /// Returns a list of variable names which are accessed from nested functions. /// </summary> public PythonTuple co_cellvars { get { return SymbolListToTuple(_lambda.CellVariables != null ? ArrayUtils.ToArray(_lambda.CellVariables) : null); } } /// <summary> /// Returns the byte code. IronPython does not implement this and always /// returns an empty string for byte code. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public object co_code { get { return String.Empty; } } /// <summary> /// Returns a list of constants used by the function. /// /// The first constant is the doc string, or None if no doc string is provided. /// /// IronPython currently does not include any other constants than the doc string. /// </summary> public PythonTuple co_consts { get { if (_initialDoc != null) { return PythonTuple.MakeTuple(_initialDoc, null); } return PythonTuple.MakeTuple((object)null); } } /// <summary> /// Returns the filename that the code object was defined in. /// </summary> public string co_filename { get { return _lambda.Filename; } } /// <summary> /// Returns the 1st line number of the code object. /// </summary> public int co_firstlineno { get { return Span.Start.Line; } } /// <summary> /// Returns a set of flags for the function. /// /// 0x04 is set if the function used *args /// 0x08 is set if the function used **args /// 0x20 is set if the function is a generator /// </summary> public int co_flags { get { return (int)Flags; } } /// <summary> /// Returns a list of free variables (variables accessed /// from an outer scope). This does not include variables /// accessed in the global scope. /// </summary> public PythonTuple co_freevars { get { return SymbolListToTuple(_lambda.FreeVariables != null ? CollectionUtils.ConvertAll(_lambda.FreeVariables, x => x.Name) : null); } } /// <summary> /// Returns a mapping between byte code and line numbers. IronPython does /// not implement this because byte code is not available. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public object co_lnotab { get { throw PythonOps.NotImplementedError(""); } } /// <summary> /// Returns the name of the code (function name, class name, or &lt;module&gt;). /// </summary> public string co_name { get { return _lambda.Name; } } /// <summary> /// Returns a list of global variable names accessed by the code. /// </summary> public PythonTuple co_names { get { return SymbolListToTuple(_lambda.GlobalVariables); } } /// <summary> /// Returns the number of local varaibles defined in the function. /// </summary> public object co_nlocals { get { return _localCount; } } /// <summary> /// Returns the stack size. IronPython does not implement this /// because byte code is not supported. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public object co_stacksize { get { throw PythonOps.NotImplementedError(""); } } #endregion #region Internal API Surface internal LightLambdaExpression Code { get { return _lambda.GetLambda(); } } internal Compiler.Ast.ScopeStatement PythonCode { get { return (Compiler.Ast.ScopeStatement)_lambda; } } internal object Call(CodeContext/*!*/ context) { if (co_freevars != PythonTuple.EMPTY) { throw PythonOps.TypeError("cannot exec code object that contains free variables: {0}", co_freevars.__repr__(context)); } if (Target == null || (Target.GetMethodInfo() != null && Target.GetMethodInfo().DeclaringType == typeof(PythonCallTargets))) { UpdateDelegate(context.LanguageContext, true); } Func<CodeContext, CodeContext> classTarget = Target as Func<CodeContext, CodeContext>; if (classTarget != null) { return classTarget(context); } LookupCompilationDelegate moduleCode = Target as LookupCompilationDelegate; if (moduleCode != null) { return moduleCode(context, this); } Func<FunctionCode, object> optimizedModuleCode = Target as Func<FunctionCode, object>; if (optimizedModuleCode != null) { return optimizedModuleCode(this); } var func = new PythonFunction(context, this, null, ArrayUtils.EmptyObjects, new MutableTuple<object>()); CallSite<Func<CallSite, CodeContext, PythonFunction, object>> site = PythonContext.GetContext(context).FunctionCallSite; return site.Target(site, context, func); } /// <summary> /// Creates a FunctionCode object for exec/eval/execfile'd/compile'd code. /// /// The code is then executed in a specific CodeContext by calling the .Call method. /// /// If the code is being used for compile (vs. exec/eval/execfile) then it needs to be /// registered in case our tracing mode changes. /// </summary> internal static FunctionCode FromSourceUnit(SourceUnit sourceUnit, PythonCompilerOptions options, bool register) { var code = PythonContext.CompilePythonCode(sourceUnit, options, ThrowingErrorSink.Default); if (sourceUnit.CodeProperties == ScriptCodeParseResult.Empty) { // source span is made up throw new SyntaxErrorException("unexpected EOF while parsing", sourceUnit, new SourceSpan(new SourceLocation(0, 1, 1), new SourceLocation(0, 1, 1)), 0, Severity.Error); } return ((RunnableScriptCode)code).GetFunctionCode(register); } #endregion #region Private helper functions private void ExpandArgsTuple(List<string> names, PythonTuple toExpand) { for (int i = 0; i < toExpand.__len__(); i++) { if (toExpand[i] is PythonTuple) { ExpandArgsTuple(names, toExpand[i] as PythonTuple); } else { names.Add(toExpand[i] as string); } } } #endregion public override bool Equals(object obj) { // overridden because CPython defines this on code objects return base.Equals(obj); } public override int GetHashCode() { // overridden because CPython defines this on code objects return base.GetHashCode(); } public int __cmp__(CodeContext/*!*/ context, [NotNull]FunctionCode/*!*/ other) { if (other == this) { return 0; } long lres = IdDispenser.GetId(this) - IdDispenser.GetId(other); return lres > 0 ? 1 : -1; } // these are present in CPython but always return NotImplemented. [return: MaybeNotImplemented] [Python3Warning("code inequality comparisons not supported in 3.x")] public static NotImplementedType operator >(FunctionCode self, FunctionCode other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("code inequality comparisons not supported in 3.x")] public static NotImplementedType operator <(FunctionCode self, FunctionCode other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("code inequality comparisons not supported in 3.x")] public static NotImplementedType operator >=(FunctionCode self, FunctionCode other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("code inequality comparisons not supported in 3.x")] public static NotImplementedType operator <=(FunctionCode self, FunctionCode other) { return PythonOps.NotImplemented; } /// <summary> /// Called the 1st time a function is invoked by our OriginalCallTarget* methods /// over in PythonCallTargets. This computes the real delegate which needs to be /// created for the function. Usually this means starting off interpretering. It /// also involves adding the wrapper function for recursion enforcement. /// /// Because this can race against sys.settrace/setprofile we need to take our /// _ThreadIsEnumeratingAndAccountingLock to ensure no one is actively changing all /// of the live functions. /// </summary> internal void LazyCompileFirstTarget(PythonFunction function) { lock (_CodeCreateAndUpdateDelegateLock) { UpdateDelegate(PythonContext.GetContext(function.Context), true); } } /// <summary> /// Updates the delegate based upon current Python context settings for recursion enforcement /// and for tracing. /// </summary> internal void UpdateDelegate(PythonContext context, bool forceCreation) { Delegate finalTarget; if (context.EnableTracing && _lambda != null) { if (_tracingLambda == null) { if (!forceCreation) { // the user just called sys.settrace(), don't force re-compilation of every method in the system. Instead // we'll just re-compile them as they're invoked. PythonCallTargets.GetPythonTargetType(_lambda.ParameterNames.Length > PythonCallTargets.MaxArgs, _lambda.ParameterNames.Length, out Target); LightThrowTarget = Target; return; } _tracingLambda = GetGeneratorOrNormalLambdaTracing(context); } if (_tracingDelegate == null) { _tracingDelegate = CompileLambda(_tracingLambda, new TargetUpdaterForCompilation(context, this).SetCompiledTargetTracing); } finalTarget = _tracingDelegate; } else { if (_normalDelegate == null) { if (!forceCreation) { // we cannot create the delegate when forceCreation is false because we hold the // _CodeCreateAndUpdateDelegateLock and compiling the delegate may create a FunctionCode // object which requires the lock. PythonCallTargets.GetPythonTargetType(_lambda.ParameterNames.Length > PythonCallTargets.MaxArgs, _lambda.ParameterNames.Length, out Target); LightThrowTarget = Target; return; } _normalDelegate = CompileLambda(GetGeneratorOrNormalLambda(), new TargetUpdaterForCompilation(context, this).SetCompiledTarget); } finalTarget = _normalDelegate; } finalTarget = AddRecursionCheck(context, finalTarget); SetTarget(finalTarget); } /// <summary> /// Called to set the initial target delegate when the user has passed -X:Debug to enable /// .NET style debugging. /// </summary> internal void SetDebugTarget(PythonContext context, Delegate target) { _normalDelegate = target; SetTarget(AddRecursionCheck(context, target)); } /// <summary> /// Gets the LambdaExpression for tracing. /// /// If this is a generator function code then the lambda gets tranformed into the correct generator code. /// </summary> private LambdaExpression GetGeneratorOrNormalLambdaTracing(PythonContext context) { var debugProperties = new PythonDebuggingPayload(this); var debugInfo = new Microsoft.Scripting.Debugging.CompilerServices.DebugLambdaInfo( null, // IDebugCompilerSupport null, // lambda alias false, // optimize for leaf frames null, // hidden variables null, // variable aliases debugProperties // custom payload ); if ((Flags & FunctionAttributes.Generator) == 0) { return context.DebugContext.TransformLambda((LambdaExpression)Compiler.Ast.Node.RemoveFrame(_lambda.GetLambda()), debugInfo); } return Expression.Lambda( Code.Type, new GeneratorRewriter( _lambda.Name, Compiler.Ast.Node.RemoveFrame(Code.Body) ).Reduce( _lambda.ShouldInterpret, _lambda.EmitDebugSymbols, context.Options.CompilationThreshold, Code.Parameters, x => (Expression<Func<MutableTuple, object>>)context.DebugContext.TransformLambda(x, debugInfo) ), Code.Name, Code.Parameters ); } /// <summary> /// Gets the correct final LambdaExpression for this piece of code. /// /// This is either just _lambda or _lambda re-written to be a generator expression. /// </summary> private LightLambdaExpression GetGeneratorOrNormalLambda() { LightLambdaExpression finalCode; if ((Flags & FunctionAttributes.Generator) == 0) { finalCode = Code; } else { finalCode = Code.ToGenerator( _lambda.ShouldInterpret, _lambda.EmitDebugSymbols, _lambda.GlobalParent.PyContext.Options.CompilationThreshold ); } return finalCode; } private Delegate CompileLambda(LightLambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) { #if EMIT_PDB if (_lambda.EmitDebugSymbols) { return CompilerHelpers.CompileToMethod((LambdaExpression)code.Reduce(), DebugInfoGenerator.CreatePdbGenerator(), true); } #endif if (_lambda.ShouldInterpret) { Delegate result = code.Compile(_lambda.GlobalParent.PyContext.Options.CompilationThreshold); // If the adaptive compiler decides to compile this function, we // want to store the new compiled target. This saves us from going // through the interpreter stub every call. var lightLambda = result.Target as LightLambda; if (lightLambda != null) { lightLambda.Compile += handler; } return result; } return code.Compile(); } private Delegate CompileLambda(LambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) { #if EMIT_PDB if (_lambda.EmitDebugSymbols) { return CompilerHelpers.CompileToMethod(code, DebugInfoGenerator.CreatePdbGenerator(), true); } #endif if (_lambda.ShouldInterpret) { Delegate result = CompilerHelpers.LightCompile(code, _lambda.GlobalParent.PyContext.Options.CompilationThreshold); // If the adaptive compiler decides to compile this function, we // want to store the new compiled target. This saves us from going // through the interpreter stub every call. var lightLambda = result.Target as LightLambda; if (lightLambda != null) { lightLambda.Compile += handler; } return result; } return code.Compile(); } internal Delegate AddRecursionCheck(PythonContext context, Delegate finalTarget) { if (context.RecursionLimit != Int32.MaxValue) { if (finalTarget is Func<CodeContext, CodeContext> || finalTarget is Func<FunctionCode, object> || finalTarget is LookupCompilationDelegate) { // no recursion enforcement on classes or modules return finalTarget; } switch (_lambda.ParameterNames.Length) { #region Generated Python Recursion Delegate Switch // *** BEGIN GENERATED CODE *** // generated by function: gen_recursion_delegate_switch from: generate_calls.py case 0: finalTarget = new Func<PythonFunction, object>(new PythonFunctionRecursionCheck0((Func<PythonFunction, object>)finalTarget).CallTarget); break; case 1: finalTarget = new Func<PythonFunction, object, object>(new PythonFunctionRecursionCheck1((Func<PythonFunction, object, object>)finalTarget).CallTarget); break; case 2: finalTarget = new Func<PythonFunction, object, object, object>(new PythonFunctionRecursionCheck2((Func<PythonFunction, object, object, object>)finalTarget).CallTarget); break; case 3: finalTarget = new Func<PythonFunction, object, object, object, object>(new PythonFunctionRecursionCheck3((Func<PythonFunction, object, object, object, object>)finalTarget).CallTarget); break; case 4: finalTarget = new Func<PythonFunction, object, object, object, object, object>(new PythonFunctionRecursionCheck4((Func<PythonFunction, object, object, object, object, object>)finalTarget).CallTarget); break; case 5: finalTarget = new Func<PythonFunction, object, object, object, object, object, object>(new PythonFunctionRecursionCheck5((Func<PythonFunction, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 6: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck6((Func<PythonFunction, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 7: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck7((Func<PythonFunction, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 8: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck8((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 9: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck9((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 10: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck10((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 11: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck11((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 12: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck12((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 13: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck13((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 14: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck14((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; case 15: finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck15((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget); break; // *** END GENERATED CODE *** #endregion default: finalTarget = new Func<PythonFunction, object[], object>(new PythonFunctionRecursionCheckN((Func<PythonFunction, object[], object>)finalTarget).CallTarget); break; } } return finalTarget; } class TargetUpdaterForCompilation { private readonly PythonContext _context; private readonly FunctionCode _code; public TargetUpdaterForCompilation(PythonContext context, FunctionCode code) { _code = code; _context = context; } public void SetCompiledTarget(object sender, Microsoft.Scripting.Interpreter.LightLambdaCompileEventArgs e) { _code.SetTarget(_code.AddRecursionCheck(_context, _code._normalDelegate = e.Compiled)); } public void SetCompiledTargetTracing(object sender, Microsoft.Scripting.Interpreter.LightLambdaCompileEventArgs e) { _code.SetTarget(_code.AddRecursionCheck(_context, _code._tracingDelegate = e.Compiled)); } } #region IExpressionSerializable Members Expression IExpressionSerializable.CreateExpression() { return Expression.Call( typeof(PythonOps).GetMethod("MakeFunctionCode"), Compiler.Ast.PythonAst._globalContext, Expression.Constant(_lambda.Name), Expression.Constant(_initialDoc, typeof(string)), Expression.NewArrayInit( typeof(string), ArrayUtils.ConvertAll(_lambda.ParameterNames, (x) => Expression.Constant(x)) ), Expression.Constant(Flags), Expression.Constant(_lambda.IndexSpan.Start), Expression.Constant(_lambda.IndexSpan.End), Expression.Constant(_lambda.Filename), GetGeneratorOrNormalLambda(), TupleToStringArray(co_freevars), TupleToStringArray(co_names), TupleToStringArray(co_cellvars), TupleToStringArray(co_varnames), Expression.Constant(_localCount) ); } private static Expression TupleToStringArray(PythonTuple tuple) { return tuple.Count > 0 ? (Expression)Expression.NewArrayInit( typeof(string), ArrayUtils.ConvertAll(tuple._data, (x) => Expression.Constant(x)) ) : (Expression)Expression.Constant(null, typeof(string[])); } #endregion /// <summary> /// Extremely light weight linked list of weak references used for tracking /// all of the FunctionCode objects which get created and need to be updated /// for purposes of recursion enforcement or tracing. /// </summary> internal class CodeList { public readonly WeakReference Code; public CodeList Next; public CodeList() { } public CodeList(WeakReference code, CodeList next) { Code = code; Next = next; } } } internal class PythonDebuggingPayload { public FunctionCode Code; private Dictionary<int, bool> _handlerLocations; private Dictionary<int, Dictionary<int, bool>> _loopAndFinallyLocations; public PythonDebuggingPayload(FunctionCode code) { Code = code; } public Dictionary<int, bool> HandlerLocations { get { if (_handlerLocations == null) { GatherLocations(); } return _handlerLocations; } } public Dictionary<int, Dictionary<int, bool>> LoopAndFinallyLocations { get { if (_loopAndFinallyLocations == null) { GatherLocations(); } return _loopAndFinallyLocations; } } private void GatherLocations() { var walker = new TracingWalker(); Code.PythonCode.Walk(walker); _loopAndFinallyLocations = walker.LoopAndFinallyLocations; _handlerLocations = walker.HandlerLocations; } class TracingWalker : Compiler.Ast.PythonWalker { private bool _inLoop, _inFinally; private int _loopId; public Dictionary<int, bool> HandlerLocations = new Dictionary<int, bool>(); public Dictionary<int, Dictionary<int, bool>> LoopAndFinallyLocations = new Dictionary<int, Dictionary<int, bool>>(); private Dictionary<int, bool> _loopIds = new Dictionary<int, bool>(); public override bool Walk(Compiler.Ast.ForStatement node) { UpdateLoops(node); WalkLoopBody(node.Body, false); if (node.Else != null) { node.Else.Walk(this); } return false; } private void WalkLoopBody(IronPython.Compiler.Ast.Statement body, bool isFinally) { bool inLoop = _inLoop; bool inFinally = _inFinally; int loopId = ++_loopId; _inFinally = false; _inLoop = true; _loopIds.Add(loopId, isFinally); body.Walk(this); _inLoop = inLoop; _inFinally = inFinally; LoopOrFinallyIds.Remove(loopId); } public override bool Walk(Compiler.Ast.WhileStatement node) { UpdateLoops(node); WalkLoopBody(node.Body, false); if (node.ElseStatement != null) { node.ElseStatement.Walk(this); } return false; } public override bool Walk(Compiler.Ast.TryStatement node) { UpdateLoops(node); node.Body.Walk(this); if (node.Handlers != null) { foreach (var handler in node.Handlers) { HandlerLocations[handler.Span.Start.Line] = false; handler.Body.Walk(this); } } if (node.Finally != null) { WalkLoopBody(node.Finally, true); } return false; } public override bool Walk(IronPython.Compiler.Ast.AssertStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.AssignmentStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.AugmentedAssignStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.BreakStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.ClassDefinition node) { UpdateLoops(node); return false; } public override bool Walk(IronPython.Compiler.Ast.ContinueStatement node) { UpdateLoops(node); return base.Walk(node); } public override void PostWalk(IronPython.Compiler.Ast.EmptyStatement node) { UpdateLoops(node); base.PostWalk(node); } public override bool Walk(IronPython.Compiler.Ast.DelStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.EmptyStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.GlobalStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.FromImportStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.ExpressionStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.FunctionDefinition node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.IfStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.ImportStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.RaiseStatement node) { UpdateLoops(node); return base.Walk(node); } public override bool Walk(IronPython.Compiler.Ast.WithStatement node) { UpdateLoops(node); return base.Walk(node); } private void UpdateLoops(Compiler.Ast.Statement stmt) { if (_inFinally || _inLoop) { if (!LoopAndFinallyLocations.ContainsKey(stmt.Span.Start.Line)) { LoopAndFinallyLocations.Add(stmt.Span.Start.Line, new Dictionary<int, bool>(LoopOrFinallyIds)); } } } public Dictionary<int, bool> LoopOrFinallyIds { get { if (_loopIds == null) { _loopIds = new Dictionary<int, bool>(); } return _loopIds; } } } } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using System.Threading.Tasks; using System.Xml; using ArcGIS.Desktop.Core.Events; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; using ArcGIS.Core.Data; using System.IO; namespace BackStage_PropertyPage { /// <summary> /// This sample illustrates how to /// 1. add a new backstage item /// 2. add property sheet items into the Options property pages /// 3. save and restore project settings /// </summary> /// <remarks> /// Backstage items can be either a tab or a button. As per other controls they have a reference in the config.daml file. However they are different from other controls /// in that they are not children of the module tag - they are children of the backstage tag. This sample shows how to add a new tab following the MVVM pattern. /// The tab can be positioned using the "insert" and "placeWith" attributes in the config.daml. The SampleBackstageTabView xaml file uses ArcGIS Pro styles to /// allow the custom tab to look those those in the existing application. /// <para> /// Property sheets are used to capture settings. They can be either project or application settings. You can insert your custom property sheets into the existing Options /// property sheets which are displayed from the backstage Options tab. This is achieved in the config.daml by using the updateSheet xml tag and specifying the /// esri_core_optionsPropertySheet id. Use the group attribute on the insertPage tag to specify whether your view/viewmodel represents project or application settings. /// This sample has an example of both project and application settings, including illustrating how these settings can be saved. /// </para> /// <para> /// Modules can write out their own set of properties when a project is saved. Correspondingly, modules can read their own settings when a project is opened. The module /// contains two methods OnReadStateAsync and OnWriteStateAsync which should be overriden to read and write module specific settings or properties. /// </para> /// 1. Open this solution in Visual Studio 2013. /// 1. Click the build menu and select Build Solution. /// 1. Click the Start button to open ArCGIS Pro. ArcGIS Pro will open. /// 1. Open any project - it can be an existing project containing data or a new empty project. /// 1. Click the project tab. See that there is a new Sample Tab item in the backstage. Select it and it will show the new backstage tab. /// 1. Click the project tab and select the Options backstage item. The options property page will display. /// 1. See that there is a Sample Project Settings under Project and a Sample App Settings under Application. /// 1. Change the project settings and application settings. /// 1. Save the project. /// 1. Open another project (or create new); return to the Project|Options|Sample Project Settings and see that the settings have been reset. /// 1. Open the project from step4; return to the Project|Options|Sample Project Settings and see that the settings have been restored. /// ![UI](Screenshots/Screen.png) /// </remarks> internal class Module1 : Module { private static Module1 _this = null; private static string ModuleID = "BackStage_PropertyPage_Module"; /// <summary> /// Retrieve the singleton instance to this module here /// </summary> public static Module1 Current { get { return _this ?? (_this = (Module1)FrameworkApplication.FindModule(Module1.ModuleID)); } } #region Overrides /// <summary> /// Called by Framework when ArcGIS Pro is closing /// </summary> /// <returns>False to prevent Pro from closing, otherwise True</returns> protected override bool CanUnload() { //TODO - add your business logic //return false to ~cancel~ Application close return true; } /// <summary> /// Generic implementation of ExecuteCommand to allow calls to /// <see cref="FrameworkApplication.ExecuteCommand"/> to execute commands in /// your Module. /// </summary> /// <param name="id"></param> /// <returns></returns> protected override Func<Task> ExecuteCommand(string id) { //TODO: replace generic implementation with custom logic //etc as needed for your Module var command = FrameworkApplication.GetPlugInWrapper(id) as ICommand; if (command == null) return () => Task.FromResult(0); if (!command.CanExecute(null)) return () => Task.FromResult(0); return () => { command.Execute(null); // if it is a tool, execute will set current tool return Task.FromResult(0); }; } #endregion Overrides private bool hasSettings = false; /// <summary> /// Module constructor. Subscribe to the ProjectOpened and ProjectClosed events. /// </summary> private Module1() { ProjectOpenedEvent.Subscribe(OnProjectOpen); ProjectClosedEvent.Subscribe(OnProjectClosed); } /// <summary> /// Uninitialize method. Make sure the module unsubscribes from the events. /// </summary> protected override void Uninitialize() { base.Uninitialize(); ProjectOpenedEvent.Unsubscribe(OnProjectOpen); ProjectClosedEvent.Unsubscribe(OnProjectClosed); } /// <summary> /// Reads the module settings from a project. This method is called when a project is opened if the project contains this module's settings. /// Use the <paramref name="settings"/> to obtain the module values. /// </summary> /// <param name="settings">Contains the module settings</param> /// <returns>A Task that represents the OnReadStateAsync method</returns> //protected override Task OnReadStateAsync(System.IO.Stream stream) protected override Task OnReadSettingsAsync(ModuleSettingsReader settings) { // set the flag hasSettings = true; // clear existing setting values _moduleSettings.Clear(); if (settings == null) return Task.FromResult(0); string[] keys = new string[] {"Setting1", "Setting2"}; foreach (string key in keys) { object value = settings.Get(key); if (value != null) { if (_moduleSettings.ContainsKey(key)) _moduleSettings[key] = value.ToString(); else _moduleSettings.Add(key, value.ToString()); } } return Task.FromResult(0); } /// <summary> /// Writes the module's settings. This method is called when a project is saved. Populate the modules settings into the ModuleSettingsWriter settings. /// </summary> /// <param name="settings">The settings which will be written out</param> /// <returns>A Task that represents the OnWriteStateAsync method</returns> protected override Task OnWriteSettingsAsync(ModuleSettingsWriter settings) { foreach (string key in _moduleSettings.Keys) { settings.Add(key, _moduleSettings[key]); } return Task.FromResult(0); } /// <summary> /// Project opened event. /// </summary> /// <remarks> /// This is necessary because OnReadStateAsync is NOT called if a project does not contain the module settings. This provides a way to restore the settings to /// default when a project not containing our settings is opened. /// </remarks> /// <param name="args">project opened event arguments</param> private void OnProjectOpen(ProjectEventArgs args) { // if flag has not been set then we didn't enter OnReadStateAsync - and we want to restore the module settings to default if (!hasSettings) _moduleSettings.Clear(); } /// <summary> /// Project closed event. Make sure we reset the settings flag. /// </summary> /// <param name="args">project closed event arguments</param> private void OnProjectClosed(ProjectEventArgs args) { // reset the flag hasSettings = false; } #region Project Module Settings /// <summary> /// the dictionary of project settings /// </summary> private Dictionary<string, string> _moduleSettings = new Dictionary<string, string>(); internal Dictionary<string, string> Settings { get { return _moduleSettings; } set { _moduleSettings = value; } } private string CreateXml(string attributeName, string value) { return String.Format("<{0}>{1}</{0}>", attributeName, value); } #endregion } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Linq; using System.Abstract; using Ninject; using Ninject.Modules; using System.Collections.Generic; using Ninject.Syntax; using Ninject.Infrastructure; namespace Contoso.Abstract { /// <summary> /// INinjectServiceRegistrar /// </summary> public interface INinjectServiceRegistrar : IServiceRegistrar { } /// <summary> /// NinjectServiceRegistrar /// </summary> public class NinjectServiceRegistrar : NinjectModule, INinjectServiceRegistrar, IDisposable, ICloneable, IServiceRegistrarBehaviorAccessor { private NinjectServiceLocator _parent; private IKernel _container; private Guid _moduleId; /// <summary> /// Initializes a new instance of the <see cref="NinjectServiceRegistrar"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="kernel">The kernel.</param> public NinjectServiceRegistrar(NinjectServiceLocator parent, IKernel kernel) { _parent = parent; _container = kernel; _container.Load(new INinjectModule[] { this }); LifetimeForRegisters = ServiceRegistrarLifetime.Transient; } object ICloneable.Clone() { return MemberwiseClone(); } // locator /// <summary> /// Gets the locator. /// </summary> public IServiceLocator Locator { get { return _parent; } } // enumerate /// <summary> /// Determines whether this instance has registered. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns> /// <c>true</c> if this instance has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered<TService>() { return Kernel.GetBindings(typeof(TService)).Any(); } /// <summary> /// Determines whether the specified service type has registered. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns> /// <c>true</c> if the specified service type has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered(Type serviceType) { return Kernel.GetBindings(serviceType).Any(); } /// <summary> /// Gets the registrations for. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns></returns> public IEnumerable<ServiceRegistration> GetRegistrationsFor(Type serviceType) { return Kernel.GetBindings(serviceType) .Select(x => new ServiceRegistration { ServiceType = x.Service }); } /// <summary> /// Gets the registrations. /// </summary> public IEnumerable<ServiceRegistration> Registrations { get { return Bindings .Select(x => new ServiceRegistration { ServiceType = x.Service }); } } // register type /// <summary> /// Gets the lifetime for registers. /// </summary> public ServiceRegistrarLifetime LifetimeForRegisters { get; private set; } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> public void Register(Type serviceType) { Bind(serviceType).ToSelf(); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, string name) { Bind(serviceType).ToSelf().Named(name); } // register implementation /// <summary> /// Registers this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> public void Register<TService, TImplementation>() where TService : class where TImplementation : class, TService { SetLifetime(Bind<TService>().To<TImplementation>()); } /// <summary> /// Registers the specified name. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="name">The name.</param> public void Register<TService, TImplementation>(string name) where TService : class where TImplementation : class, TService { SetLifetime(Bind<TService>().To(typeof(TImplementation))).Named(name); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> public void Register<TService>(Type implementationType) where TService : class { SetLifetime(Bind<TService>().To(implementationType)); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register<TService>(Type implementationType, string name) where TService : class { SetLifetime(Bind<TService>().To(implementationType)).Named(name); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> public void Register(Type serviceType, Type implementationType) { SetLifetime(Bind(serviceType).To(implementationType)); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Type implementationType, string name) { SetLifetime(Bind(serviceType).To(implementationType)).Named(name); } // register instance /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> public void RegisterInstance<TService>(TService instance) where TService : class { EnsureTransientLifestyle(); Bind<TService>().ToConstant(instance); } /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance<TService>(TService instance, string name) where TService : class { EnsureTransientLifestyle(); Bind<TService>().ToConstant(instance).Named(name); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> public void RegisterInstance(Type serviceType, object instance) { EnsureTransientLifestyle(); Bind(serviceType).ToConstant(instance); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance(Type serviceType, object instance, string name) { EnsureTransientLifestyle(); Bind(serviceType).ToConstant(instance).Named(name); } // register method /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod) where TService : class { SetLifetime(Bind<TService>().ToMethod(x => factoryMethod(_parent))); } /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod, string name) where TService : class { SetLifetime(Bind<TService>().ToMethod(x => factoryMethod(_parent))).Named(name); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod) { SetLifetime(Bind(serviceType).ToMethod(x => factoryMethod(_parent))); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod, string name) { SetLifetime(Bind(serviceType).ToMethod(x => factoryMethod(_parent))).Named(name); } // interceptor /// <summary> /// Registers the interceptor. /// </summary> /// <param name="interceptor">The interceptor.</param> public void RegisterInterceptor(IServiceLocatorInterceptor interceptor) { throw new NotSupportedException(); } #region Domain specific /// <summary> /// Loads the module into the kernel. /// </summary> public override void Load() { _moduleId = Guid.NewGuid(); } /// <summary> /// Gets the module's name. Only a single module with a given name can be loaded at one time. /// </summary> public override string Name { get { return _moduleId.ToString(); } } //private string MakeId(Type serviceType, Type implementationType) { return serviceType.Name + "->" + implementationType.FullName; } #endregion #region Behavior bool IServiceRegistrarBehaviorAccessor.RegisterInLocator { get { return true; } } ServiceRegistrarLifetime IServiceRegistrarBehaviorAccessor.Lifetime { get { return LifetimeForRegisters; } set { LifetimeForRegisters = value; } } #endregion private void EnsureTransientLifestyle() { if (LifetimeForRegisters != ServiceRegistrarLifetime.Transient) throw new NotSupportedException(); } private IBindingNamedWithOrOnSyntax<TService> SetLifetime<TService>(IBindingWhenInNamedWithOrOnSyntax<TService> bindingWhenInNamedWithOrOnSyntax) { switch (LifetimeForRegisters) { case ServiceRegistrarLifetime.Transient: return bindingWhenInNamedWithOrOnSyntax.InScope(StandardScopeCallbacks.Transient); case ServiceRegistrarLifetime.Singleton: return bindingWhenInNamedWithOrOnSyntax.InScope(StandardScopeCallbacks.Singleton); case ServiceRegistrarLifetime.Thread: return bindingWhenInNamedWithOrOnSyntax.InScope(StandardScopeCallbacks.Thread); default: throw new NotSupportedException(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Threading; using System.Security.Cryptography.X509Certificates; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; using Thrift.Test; using System.Security.Authentication; namespace Test { public class TestClient { private class TestParams { public int numIterations = 1; public string host = "localhost"; public int port = 9090; public string url; public string pipe; public bool buffered; public bool framed; public string protocol; public bool encrypted = false; protected bool _isFirstTransport = true; public TTransport CreateTransport() { if (url == null) { // endpoint transport TTransport trans = null; if (pipe != null) trans = new TNamedPipeClientTransport(pipe); else { if (encrypted) { string certPath = "../keys/client.p12"; X509Certificate cert = new X509Certificate2(certPath, "thrift"); trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls); } else { trans = new TSocket(host, port); } } // layered transport if (buffered) trans = new TBufferedTransport(trans); if (framed) trans = new TFramedTransport(trans); if (_isFirstTransport) { //ensure proper open/close of transport trans.Open(); trans.Close(); _isFirstTransport = false; } return trans; } else { return new THttpClient(new Uri(url)); } } public TProtocol CreateProtocol(TTransport transport) { if (protocol == "compact") return new TCompactProtocol(transport); else if (protocol == "json") return new TJSONProtocol(transport); else return new TBinaryProtocol(transport); } }; private const int ErrorBaseTypes = 1; private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; private const int ErrorUnknown = 64; private class ClientTest { private readonly TTransport transport; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } public ClientTest(TestParams param) { transport = param.CreateTransport(); client = new ThriftTest.Client(param.CreateProtocol(transport)); numIterations = param.numIterations; } public void Execute() { if (done) { Console.WriteLine("Execute called more than once"); throw new InvalidOperationException(); } for (int i = 0; i < numIterations; i++) { try { if (!transport.IsOpen) transport.Open(); } catch (TTransportException ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); continue; } try { ReturnCode |= ExecuteClientTest(client); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); ReturnCode |= ErrorUnknown; } } try { transport.Close(); } catch(Exception ex) { Console.WriteLine("Error while closing transport"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } done = true; } } public static int Execute(string[] args) { try { TestParams param = new TestParams(); int numThreads = 1; try { for (int i = 0; i < args.Length; i++) { if (args[i] == "-u") { param.url = args[++i]; } else if (args[i] == "-n") { param.numIterations = Convert.ToInt32(args[++i]); } else if (args[i] == "-pipe") // -pipe <name> { param.pipe = args[++i]; Console.WriteLine("Using named pipes transport"); } else if (args[i].Contains("--host=")) { param.host = args[i].Substring(args[i].IndexOf("=") + 1); } else if (args[i].Contains("--port=")) { param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { param.buffered = true; Console.WriteLine("Using buffered sockets"); } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { param.framed = true; Console.WriteLine("Using framed transport"); } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { param.protocol = "compact"; Console.WriteLine("Using compact protocol"); } else if (args[i] == "--json" || args[i] == "--protocol=json") { param.protocol = "json"; Console.WriteLine("Using JSON protocol"); } else if (args[i] == "--ssl") { param.encrypted = true; Console.WriteLine("Using encrypted transport"); } } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); return ErrorUnknown; } var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray(); //issue tests on separate threads simultaneously var threads = tests.Select(test => new Thread(test.Execute)).ToArray(); DateTime start = DateTime.Now; foreach (var t in threads) t.Start(); foreach (var t in threads) t.Join(); Console.WriteLine("Total time: " + (DateTime.Now - start)); Console.WriteLine(); return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); } catch (Exception outerEx) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Unexpected error"); Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); return ErrorUnknown; } } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public static byte[] PrepareTestData(bool randomDist) { byte[] retval = new byte[0x100]; int initLen = Math.Min(0x100,retval.Length); // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < initLen; ++i) { retval[i] = (byte)i; } return retval; } // random distribution for (var i = 0; i < initLen; ++i) { retval[i] = (byte)0; } var rnd = new Random(); for (var i = 1; i < initLen; ++i) { while( true) { int nextPos = rnd.Next() % initLen; if (retval[nextPos] == 0) { retval[nextPos] = (byte)i; break; } } } return retval; } public static int ExecuteClientTest(ThriftTest.Client client) { int returnCode = 0; Console.Write("testVoid()"); client.testVoid(); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); string s = client.testString("Test"); Console.WriteLine(" = \"" + s + "\""); if ("Test" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(true)"); bool t = client.testBool((bool)true); Console.WriteLine(" = " + t); if (!t) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(false)"); bool f = client.testBool((bool)false); Console.WriteLine(" = " + f); if (f) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testByte(1)"); sbyte i8 = client.testByte((sbyte)1); Console.WriteLine(" = " + i8); if (1 != i8) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI32(-1)"); int i32 = client.testI32(-1); Console.WriteLine(" = " + i32); if (-1 != i32) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI64(-34359738368)"); long i64 = client.testI64(-34359738368); Console.WriteLine(" = " + i64); if (-34359738368 != i64) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // TODO: Validate received message Console.Write("testDouble(5.325098235)"); double dub = client.testDouble(5.325098235); Console.WriteLine(" = " + dub); if (5.325098235 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testDouble(-0.000341012439638598279)"); dub = client.testDouble(-0.000341012439638598279); Console.WriteLine(" = " + dub); if (-0.000341012439638598279 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } byte[] binOut = PrepareTestData(true); Console.Write("testBinary(" + BytesToHex(binOut) + ")"); try { byte[] binIn = client.testBinary(binOut); Console.WriteLine(" = " + BytesToHex(binIn)); if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) if (binIn[ofs] != binOut[ofs]) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } } catch (Thrift.TApplicationException ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } // binary equals? only with hashcode option enabled ... Console.WriteLine("Test CrazyNesting"); if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting)) { CrazyNesting one = new CrazyNesting(); CrazyNesting two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (!one.Equals(two)) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorContainers; throw new Exception("CrazyNesting.Equals failed"); } } // TODO: Validate received message Console.Write("testStruct({\"Zero\", 1, -3, -5})"); Xtruct o = new Xtruct(); o.String_thing = "Zero"; o.Byte_thing = (sbyte)1; o.I32_thing = -3; o.I64_thing = -5; Xtruct i = client.testStruct(o); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); // TODO: Validate received message Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); Xtruct2 o2 = new Xtruct2(); o2.Byte_thing = (sbyte)1; o2.Struct_thing = o; o2.I32_thing = 5; Xtruct2 i2 = client.testNest(o2); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); Dictionary<int, int> mapout = new Dictionary<int, int>(); for (int j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); bool first = true; foreach (int key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); Dictionary<int, int> mapin = client.testMap(mapout); Console.Write(" = {"); first = true; foreach (int key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); // TODO: Validate received message List<int> listout = new List<int>(); for (int j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (int j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); List<int> listin = client.testList(listout); Console.Write(" = {"); first = true; foreach (int j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set // TODO: Validate received message THashSet<int> setout = new THashSet<int>(); for (int j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); THashSet<int> setin = client.testSet(setout); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); Numberz ret = client.testEnum(Numberz.ONE); Console.WriteLine(" = " + ret); if (Numberz.ONE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(TWO)"); ret = client.testEnum(Numberz.TWO); Console.WriteLine(" = " + ret); if (Numberz.TWO != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(THREE)"); ret = client.testEnum(Numberz.THREE); Console.WriteLine(" = " + ret); if (Numberz.THREE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(FIVE)"); ret = client.testEnum(Numberz.FIVE); Console.WriteLine(" = " + ret); if (Numberz.FIVE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(EIGHT)"); ret = client.testEnum(Numberz.EIGHT); Console.WriteLine(" = " + ret); if (Numberz.EIGHT != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testTypedef(309858235082523)"); long uid = client.testTypedef(309858235082523L); Console.WriteLine(" = " + uid); if (309858235082523L != uid) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } // TODO: Validate received message Console.Write("testMapMap(1)"); Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1); Console.Write(" = {"); foreach (int key in mm.Keys) { Console.Write(key + " => {"); Dictionary<int, int> m2 = mm[key]; foreach (int k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); // TODO: Validate received message Insanity insane = new Insanity(); insane.UserMap = new Dictionary<Numberz, long>(); insane.UserMap[Numberz.FIVE] = 5000L; Xtruct truck = new Xtruct(); truck.String_thing = "Truck"; truck.Byte_thing = (sbyte)8; truck.I32_thing = 8; truck.I64_thing = 8; insane.Xtructs = new List<Xtruct>(); insane.Xtructs.Add(truck); Console.Write("testInsanity()"); Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane); Console.Write(" = {"); foreach (long key in whoa.Keys) { Dictionary<Numberz, Insanity> val = whoa[key]; Console.Write(key + " => {"); foreach (Numberz k2 in val.Keys) { Insanity v2 = val[k2]; Console.Write(k2 + " => {"); Dictionary<Numberz, long> userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (Numberz k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); List<Xtruct> xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (Xtruct x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; int arg1 = 2; long arg2 = long.MaxValue; Dictionary<short, string> multiDict = new Dictionary<short, string>(); multiDict[1] = "one"; Numberz arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")"); Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); try { Console.WriteLine("testException(\"Xception\")"); client.testException("Xception"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"TException\")"); client.testException("TException"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Thrift.TException) { // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"ok\")"); client.testException("ok"); // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception\", ...)"); client.testMultiException("Xception", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception2\", ...)"); client.testMultiException("Xception2", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception2 ex) { if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"success\", \"OK\")"); if ("OK" != client.testMultiException("success", "OK").String_thing) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("Test Oneway(1)"); client.testOneway(1); sw.Stop(); if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("Test Calltime()"); var times = 50; sw.Reset(); sw.Start(); for (int k = 0; k < times; ++k) client.testVoid(); sw.Stop(); Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times); return returnCode; } } }
// // Source.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Banshee.Base; using Banshee.Collection; using Banshee.Configuration; using Banshee.ServiceStack; namespace Banshee.Sources { public abstract class Source : ISource { private Source parent; private PropertyStore properties = new PropertyStore (); protected SourceMessage status_message; private List<SourceMessage> messages = new List<SourceMessage> (); private List<Source> child_sources = new List<Source> (); private ReadOnlyCollection<Source> read_only_children; private SourceSortType child_sort; private bool sort_children = true; private SchemaEntry<string> child_sort_schema; private SchemaEntry<bool> separate_by_type_schema; public event EventHandler Updated; public event EventHandler UserNotifyUpdated; public event EventHandler MessageNotify; public event SourceEventHandler ChildSourceAdded; public event SourceEventHandler ChildSourceRemoved; public delegate void OpenPropertiesDelegate (); protected Source (string generic_name, string name, int order) : this (generic_name, name, order, null) { } protected Source (string generic_name, string name, int order, string type_unique_id) : this () { GenericName = generic_name; Name = name; Order = order; TypeUniqueId = type_unique_id; SourceInitialize (); } protected Source () { child_sort = DefaultChildSort; } // This method is chained to subclasses intialize methods, // allowing at any state for delayed intialization by using the empty ctor. protected virtual void Initialize () { SourceInitialize (); } private void SourceInitialize () { // If this source is not defined in Banshee.Services, set its // ResourceAssembly to the assembly where it is defined. Assembly asm = Assembly.GetAssembly (this.GetType ());//Assembly.GetCallingAssembly (); if (asm != Assembly.GetExecutingAssembly ()) { Properties.Set<Assembly> ("ResourceAssembly", asm); } properties.PropertyChanged += OnPropertyChanged; read_only_children = new ReadOnlyCollection<Source> (child_sources); if (ApplicationContext.Debugging && ApplicationContext.CommandLine.Contains ("test-source-messages")) { TestMessages (); } LoadSortSchema (); } protected void OnSetupComplete () { /*ITrackModelSource tm_source = this as ITrackModelSource; if (tm_source != null) { tm_source.TrackModel.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (tm_source.TrackModel); // TODO if/when browsable models can be added/removed on the fly, this would need to change to reflect that foreach (IListModel model in tm_source.FilterModels) { Banshee.Collection.ExportableModel exportable = model as Banshee.Collection.ExportableModel; if (exportable != null) { exportable.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (exportable); } } }*/ } protected void Remove () { if (prefs_page != null) { prefs_page.Dispose (); } if (ServiceManager.SourceManager.ContainsSource (this)) { if (this.Parent != null) { this.Parent.RemoveChildSource (this); } else { ServiceManager.SourceManager.RemoveSource (this); } } } protected void PauseSorting () { sort_children = false; } protected void ResumeSorting () { sort_children = true; } #region Public Methods public virtual void Activate () { } public virtual void Deactivate () { } public virtual void Rename (string newName) { properties.SetString ("Name", newName); } public virtual bool AcceptsInputFromSource (Source source) { return false; } public virtual bool AcceptsUserInputFromSource (Source source) { return AcceptsInputFromSource (source); } public virtual void MergeSourceInput (Source source, SourceMergeType mergeType) { Log.ErrorFormat ("MergeSourceInput not implemented by {0}", this); } public virtual SourceMergeType SupportedMergeTypes { get { return SourceMergeType.None; } } public virtual void SetParentSource (Source parent) { this.parent = parent; } public virtual bool ContainsChildSource (Source child) { lock (Children) { return child_sources.Contains (child); } } public virtual void AddChildSource (Source child) { lock (Children) { if (!child_sources.Contains (child)) { child.SetParentSource (this); child_sources.Add (child); OnChildSourceAdded (child); } } } public virtual void RemoveChildSource (Source child) { lock (Children) { if (child.Children.Count > 0) { child.ClearChildSources (); } child_sources.Remove (child); if (ServiceManager.SourceManager.ActiveSource == child) { if (CanActivate) { ServiceManager.SourceManager.SetActiveSource (this); } } OnChildSourceRemoved (child); } } public virtual void ClearChildSources () { lock (Children) { while (child_sources.Count > 0) { RemoveChildSource (child_sources[child_sources.Count - 1]); } } } private class SizeComparer : IComparer<Source> { public int Compare (Source a, Source b) { return a.Count.CompareTo (b.Count); } } public virtual void SortChildSources (SourceSortType sort_type) { child_sort = sort_type; child_sort_schema.Set (child_sort.Id); SortChildSources (); } public virtual void SortChildSources () { lock (this) { if (!sort_children) { return; } sort_children = false; } if (child_sort != null && child_sort.SortType != SortType.None) { lock (Children) { child_sort.Sort (child_sources, SeparateChildrenByType); int i = 0; foreach (Source child in child_sources) { // Leave children with negative orders alone, so they can be manually // placed at the top if (child.Order >= 0) { child.Order = i++; } } } } sort_children = true; } private void LoadSortSchema () { if (ChildSortTypes.Length == 0) { return; } if (unique_id == null && type_unique_id == null) { Hyena.Log.WarningFormat ("Trying to LoadSortSchema, but source's id not set! {0}", UniqueId); return; } child_sort_schema = CreateSchema<string> ("child_sort_id", DefaultChildSort.Id, "", ""); string child_sort_id = child_sort_schema.Get (); foreach (SourceSortType sort_type in ChildSortTypes) { if (sort_type.Id == child_sort_id) { child_sort = sort_type; break; } } separate_by_type_schema = CreateSchema<bool> ("separate_by_type", false, "", ""); SortChildSources (); } public T GetProperty<T> (string name, bool inherited) { return inherited ? GetInheritedProperty<T> (name) : Properties.Get<T> (name); } public T GetInheritedProperty<T> (string name) { return Properties.Contains (name) ? Properties.Get<T> (name) : Parent != null ? Parent.GetInheritedProperty<T> (name) : default (T); } #endregion #region Protected Methods public virtual void SetStatus (string message, bool error) { SetStatus (message, !error, !error, error ? "dialog-error" : null); } public virtual void SetStatus (string message, bool can_close, bool is_spinning, string icon_name) { lock (this) { if (status_message == null) { status_message = new SourceMessage (this); PushMessage (status_message); } string status_name = String.Format ("<i>{0}</i>", GLib.Markup.EscapeText (Name)); status_message.FreezeNotify (); status_message.Text = String.Format (GLib.Markup.EscapeText (message), status_name); status_message.CanClose = can_close; status_message.IsSpinning = is_spinning; status_message.SetIconName (icon_name); status_message.IsHidden = false; status_message.ClearActions (); } status_message.ThawNotify (); } public virtual void HideStatus () { lock (this) { if (status_message != null) { RemoveMessage (status_message); status_message = null; } } } public void PushMessage (SourceMessage message) { lock (this) { messages.Insert (0, message); message.Updated += HandleMessageUpdated; } OnMessageNotify (); } protected SourceMessage PopMessage () { try { lock (this) { if (messages.Count > 0) { SourceMessage message = messages[0]; message.Updated -= HandleMessageUpdated; messages.RemoveAt (0); return message; } return null; } } finally { OnMessageNotify (); } } protected void ClearMessages () { lock (this) { if (messages.Count > 0) { foreach (SourceMessage message in messages) { message.Updated -= HandleMessageUpdated; } messages.Clear (); OnMessageNotify (); } status_message = null; } } private void TestMessages () { int count = 0; SourceMessage message_3 = null; Application.RunTimeout (5000, delegate { if (count++ > 5) { if (count == 7) { RemoveMessage (message_3); } PopMessage (); return true; } else if (count > 10) { return false; } SourceMessage message = new SourceMessage (this); message.FreezeNotify (); message.Text = String.Format ("Testing message {0}", count); message.IsSpinning = count % 2 == 0; message.CanClose = count % 2 == 1; if (count % 3 == 0) { for (int i = 2; i < count; i++) { message.AddAction (new MessageAction (String.Format ("Button {0}", i))); } } message.ThawNotify (); PushMessage (message); if (count == 3) { message_3 = message; } return true; }); } public void RemoveMessage (SourceMessage message) { lock (this) { if (messages.Remove (message)) { message.Updated -= HandleMessageUpdated; OnMessageNotify (); } } } private void HandleMessageUpdated (object o, EventArgs args) { if (CurrentMessage == o && CurrentMessage.IsHidden) { PopMessage (); } OnMessageNotify (); } protected virtual void OnMessageNotify () { EventHandler handler = MessageNotify; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceAdded (Source source) { SortChildSources (); source.Updated += OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceAdded; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnChildSourceRemoved (Source source) { source.Updated -= OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceRemoved; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnUpdated () { EventHandler handler = Updated; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceUpdated (object o, EventArgs args) { SortChildSources (); } public void NotifyUser () { OnUserNotifyUpdated (); } protected void OnUserNotifyUpdated () { if (this != ServiceManager.SourceManager.ActiveSource) { EventHandler handler = UserNotifyUpdated; if (handler != null) { handler (this, EventArgs.Empty); } } } #endregion #region Private Methods private void OnPropertyChanged (object o, PropertyChangeEventArgs args) { OnUpdated (); } #endregion #region Public Properties public ReadOnlyCollection<Source> Children { get { return read_only_children; } } string [] ISource.Children { get { return null; } } public Source Parent { get { return parent; } } public virtual string TypeName { get { return GetType ().Name; } } private string unique_id; public string UniqueId { get { if (unique_id == null && type_unique_id == null) { Log.ErrorFormat ("Creating Source.UniqueId for {0} (type {1}), but TypeUniqueId is null; trace is {2}", this.Name, GetType ().Name, System.Environment.StackTrace); } return unique_id ?? (unique_id = String.Format ("{0}-{1}", this.GetType ().Name, TypeUniqueId)); } } private string type_unique_id; protected string TypeUniqueId { get { return type_unique_id; } set { type_unique_id = value; } } public virtual bool CanRename { get { return false; } } public virtual bool HasProperties { get { return false; } } public virtual bool HasViewableTrackProperties { get { return false; } } public virtual bool HasEditableTrackProperties { get { return false; } } public virtual string Name { get { return properties.Get<string> ("Name"); } set { properties.SetString ("Name", value); } } public virtual string GenericName { get { return properties.Get<string> ("GenericName"); } set { properties.SetString ("GenericName", value); } } public int Order { get { return properties.GetInteger ("Order"); } set { properties.SetInteger ("Order", value); } } public SourceMessage CurrentMessage { get { lock (this) { return messages.Count > 0 ? messages[0] : null; } } } public virtual bool ImplementsCustomSearch { get { return false; } } public virtual bool CanSearch { get { return false; } } public virtual string FilterQuery { get { return properties.Get<string> ("FilterQuery"); } set { properties.SetString ("FilterQuery", value); } } public TrackFilterType FilterType { get { return (TrackFilterType)properties.GetInteger ("FilterType"); } set { properties.SetInteger ("FilterType", (int)value); } } public virtual bool Expanded { get { return properties.GetBoolean ("Expanded"); } set { properties.SetBoolean ("Expanded", value); } } public virtual bool? AutoExpand { get { return true; } } public virtual PropertyStore Properties { get { return properties; } } public virtual bool CanActivate { get { return true; } } public virtual int Count { get { return 0; } } public virtual int EnabledCount { get { return Count; } } private string parent_conf_id; public string ParentConfigurationId { get { if (parent_conf_id == null) { parent_conf_id = (Parent ?? this).UniqueId.Replace ('.', '_'); } return parent_conf_id; } } private string conf_id; public string ConfigurationId { get { return conf_id ?? (conf_id = UniqueId.Replace ('.', '_')); } } public virtual int FilteredCount { get { return Count; } } public virtual string TrackModelPath { get { return null; } } public static readonly SourceSortType SortNameAscending = new SourceSortType ( "NameAsc", Catalog.GetString ("Name"), SortType.Ascending, null); // null comparer b/c we already fall back to sorting by name public static readonly SourceSortType SortSizeAscending = new SourceSortType ( "SizeAsc", Catalog.GetString ("Size Ascending"), SortType.Ascending, new SizeComparer ()); public static readonly SourceSortType SortSizeDescending = new SourceSortType ( "SizeDesc", Catalog.GetString ("Size Descending"), SortType.Descending, new SizeComparer ()); private static SourceSortType[] sort_types = new SourceSortType[] {}; public virtual SourceSortType[] ChildSortTypes { get { return sort_types; } } public SourceSortType ActiveChildSort { get { return child_sort; } } public virtual SourceSortType DefaultChildSort { get { return null; } } public bool SeparateChildrenByType { get { return separate_by_type_schema.Get (); } set { separate_by_type_schema.Set (value); SortChildSources (); } } #endregion #region Status Message Stuff private static DurationStatusFormatters duration_status_formatters = new DurationStatusFormatters (); public static DurationStatusFormatters DurationStatusFormatters { get { return duration_status_formatters; } } protected virtual int StatusFormatsCount { get { return duration_status_formatters.Count; } } public virtual int CurrentStatusFormat { get { return ConfigurationClient.Get<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", 0); } set { ConfigurationClient.Set<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", value); } } public SchemaEntry<T> CreateSchema<T> (string name) { return CreateSchema<T> (name, default(T), null, null); } public SchemaEntry<T> CreateSchema<T> (string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}", ParentConfigurationId), name, defaultValue, shortDescription, longDescription); } public SchemaEntry<T> CreateSchema<T> (string ns, string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}.{1}", ParentConfigurationId, ns), name, defaultValue, shortDescription, longDescription); } public virtual string PreferencesPageId { get { return null; } } private Banshee.Preferences.SourcePage prefs_page; public Banshee.Preferences.Page PreferencesPage { get { return prefs_page ?? (prefs_page = new Banshee.Preferences.SourcePage (this)); } } public void CycleStatusFormat () { int new_status_format = CurrentStatusFormat + 1; if (new_status_format >= StatusFormatsCount) { new_status_format = 0; } CurrentStatusFormat = new_status_format; } private const string STATUS_BAR_SEPARATOR = " \u2013 "; public virtual string GetStatusText () { StringBuilder builder = new StringBuilder (); int count = FilteredCount; if (count == 0) { return String.Empty; } var count_str = String.Format ("{0:N0}", count); builder.AppendFormat (GetPluralItemCountString (count), count_str); if (this is IDurationAggregator && StatusFormatsCount > 0) { var duration = ((IDurationAggregator)this).Duration; if (duration > TimeSpan.Zero) { builder.Append (STATUS_BAR_SEPARATOR); duration_status_formatters[CurrentStatusFormat] (builder, ((IDurationAggregator)this).Duration); } } if (this is IFileSizeAggregator) { long bytes = (this as IFileSizeAggregator).FileSize; if (bytes > 0) { builder.Append (STATUS_BAR_SEPARATOR); builder.AppendFormat (new FileSizeQueryValue (bytes).ToUserQuery ()); } } return builder.ToString (); } public virtual string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} item", "{0} items", count); } #endregion public override string ToString () { return Name; } /*string IService.ServiceName { get { return String.Format ("{0}{1}", DBusServiceManager.MakeDBusSafeString (Name), "Source"); } }*/ // FIXME: Replace ISource with IDBusExportable when it's enabled again ISource ISource.Parent { get { if (Parent != null) { return ((Source)this).Parent; } else { return null /*ServiceManager.SourceManager*/; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime.Scheduler; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.ReminderService { internal class LocalReminderService : GrainService, IReminderService { private const int InitialReadRetryCountBeforeFastFailForUpdates = 2; private static readonly TimeSpan InitialReadMaxWaitTimeForUpdates = TimeSpan.FromSeconds(20); private static readonly TimeSpan InitialReadRetryPeriod = TimeSpan.FromSeconds(30); private ILogger logger; private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders; private readonly IReminderTable reminderTable; private long localTableSequence; private IGrainTimer listRefreshTimer; // timer that refreshes our list of reminders to reflect global reminder table private readonly TaskCompletionSource<bool> startedTask; private uint initialReadCallCount = 0; private readonly ILogger timerLogger; private readonly ILoggerFactory loggerFactory; private readonly AverageTimeSpanStatistic tardinessStat; private readonly CounterStatistic ticksDeliveredStat; private readonly TimeSpan initTimeout; internal LocalReminderService( Silo silo, IReminderTable reminderTable, TimeSpan initTimeout, ILoggerFactory loggerFactory) : base(GetGrainId(), silo, loggerFactory) { this.timerLogger = loggerFactory.CreateLogger<GrainTimer>(); localReminders = new Dictionary<ReminderIdentity, LocalReminderData>(); this.reminderTable = reminderTable; this.initTimeout = initTimeout; localTableSequence = 0; this.loggerFactory = loggerFactory; tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS); IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count); ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED); startedTask = new TaskCompletionSource<bool>(); this.logger = this.loggerFactory.CreateLogger<LocalReminderService>(); } #region Public methods /// <summary> /// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance) /// </summary> /// <returns></returns> public override async Task Start() { // confirm that it can access the underlying store, as after this the ReminderService will load in the background, without the opportunity to prevent the Silo from starting await reminderTable.Init().WithTimeout(initTimeout, $"ReminderTable Initialization failed due to timeout {initTimeout}"); await base.Start(); } public async override Task Stop() { await base.Stop(); if (listRefreshTimer != null) { listRefreshTimer.Dispose(); listRefreshTimer = null; } foreach (LocalReminderData r in localReminders.Values) r.StopReminder(logger); // for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable // currently, this is taken care of by periodically reading the reminder table } public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period) { var entry = new ReminderEntry { GrainRef = grainRef, ReminderName = reminderName, StartAt = DateTime.UtcNow.Add(dueTime), Period = period, }; if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString()); await DoResponsibilitySanityCheck(grainRef, "RegisterReminder"); var newEtag = await reminderTable.UpsertRow(entry); if (newEtag != null) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence); entry.ETag = newEtag; StartAndAddTimer(entry); if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(); return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder; } var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry); logger.Error(ErrorCode.RS_Register_TableError, msg); throw new ReminderException(msg); } /// <summary> /// Stop the reminder locally, and remove it from the external storage system /// </summary> /// <param name="reminder"></param> /// <returns></returns> public async Task UnregisterReminder(IGrainReminder reminder) { var remData = (ReminderData)reminder; if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence); GrainReference grainRef = remData.GrainRef; string reminderName = remData.ReminderName; string eTag = remData.ETag; await DoResponsibilitySanityCheck(grainRef, "RemoveReminder"); // it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder // table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally // remove from persistent/memory store var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag); if (success) { bool removed = TryStopPreviousTimer(grainRef, reminderName); if (removed) { if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder); if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(string.Format("After removing {0}.", reminder)); } else { // no-op if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder); } } else { var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder); logger.Error(ErrorCode.RS_Unregister_TableError, msg); throw new ReminderException(msg); } } public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName) { if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToDetailedString(), reminderName); var entry = await reminderTable.ReadRow(grainRef, reminderName); return entry == null ? null : entry.ToIGrainReminder(); } public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToDetailedString()); var tableData = await reminderTable.ReadRows(grainRef); return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList(); } #endregion /// <summary> /// Attempt to retrieve reminders from the global reminder table /// </summary> private async Task ReadAndUpdateReminders() { if (StoppedCancellationTokenSource.IsCancellationRequested) return; RemoveOutOfRangeReminders(); // try to retrieve reminders from all my subranges var rangeSerialNumberCopy = RangeSerialNumber; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"My range= {RingRange}, RangeSerialNumber {RangeSerialNumber}. Local reminders count {localReminders.Count}"); var acks = new List<Task>(); foreach (var range in RangeFactory.GetSubRanges(RingRange)) { acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy)); } await Task.WhenAll(acks); if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(); } private void RemoveOutOfRangeReminders() { var remindersOutOfRange = localReminders.Where(r => !RingRange.InRange(r.Key.GrainRef)).Select(r => r.Value).ToArray(); foreach (var reminder in remindersOutOfRange) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in my range anymore, so removing. {0}", reminder); // remove locally reminder.StopReminder(logger); localReminders.Remove(reminder.Identity); } if (logger.IsEnabled(LogLevel.Information) && remindersOutOfRange.Length > 0) logger.Info($"Removed {remindersOutOfRange.Length} local reminders that are now out of my range."); } #region Change in membership, e.g., failure of predecessor public override async Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased) { await base.OnRangeChange(oldRange, newRange, increased); if (Status == GrainServiceStatus.Started) await ReadAndUpdateReminders(); else if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Ignoring range change until ReminderService is Started -- Current status = {0}", Status); } #endregion #region Internal implementation methods protected override async Task StartInBackground() { await DoInitialReadAndUpdateReminders(); if (Status == GrainServiceStatus.Booting) { var random = new SafeRandom(); listRefreshTimer = GrainTimer.FromTaskCallback( this.RuntimeClient.Scheduler, this.timerLogger, _ => DoInitialReadAndUpdateReminders(), null, random.NextTimeSpan(InitialReadRetryPeriod), InitialReadRetryPeriod, name: "ReminderService.ReminderListInitialRead"); listRefreshTimer.Start(); } } private void PromoteToStarted() { if (StoppedCancellationTokenSource.IsCancellationRequested) return; // Logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", this.Silo, this.Silo.GetConsistentHashCode(), this.myRange); var random = new SafeRandom(); var dueTime = random.NextTimeSpan(Constants.RefreshReminderList); if (listRefreshTimer != null) listRefreshTimer.Dispose(); listRefreshTimer = GrainTimer.FromTaskCallback( this.RuntimeClient.Scheduler, this.timerLogger, _ => ReadAndUpdateReminders(), null, dueTime, Constants.RefreshReminderList, name: "ReminderService.ReminderListRefresher"); listRefreshTimer.Start(); Status = GrainServiceStatus.Started; startedTask.TrySetResult(true); } private async Task DoInitialReadAndUpdateReminders() { try { if (StoppedCancellationTokenSource.IsCancellationRequested) return; initialReadCallCount++; await this.ReadAndUpdateReminders(); PromoteToStarted(); } catch (Exception ex) { if (StoppedCancellationTokenSource.IsCancellationRequested) return; if (initialReadCallCount <= InitialReadRetryCountBeforeFastFailForUpdates) { logger.Warn( ErrorCode.RS_ServiceInitialLoadFailing, string.Format("ReminderService failed initial load of reminders and will retry. Attempt #{0}", this.initialReadCallCount), ex); } else { const string baseErrorMsg = "ReminderService failed initial load of reminders and cannot guarantee that the service will be eventually start without manual intervention or restarting the silo."; var logErrorMessage = string.Format(baseErrorMsg + " Attempt #{0}", this.initialReadCallCount); logger.Error(ErrorCode.RS_ServiceInitialLoadFailed, logErrorMessage, ex); startedTask.TrySetException(new OrleansException(baseErrorMsg, ex)); } } } private async Task ReadTableAndStartTimers(IRingRange range, int rangeSerialNumberCopy) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Reading rows from {0}", range.ToString()); localTableSequence++; long cachedSequence = localTableSequence; try { var srange = range as ISingleRange; if (srange == null) throw new InvalidOperationException("LocalReminderService must be dealing with SingleRange"); ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have if (rangeSerialNumberCopy < RangeSerialNumber) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"My range changed while reading from the table, ignoring the results. Another read has been started. RangeSerialNumber {RangeSerialNumber}, RangeSerialNumberCopy {rangeSerialNumberCopy}."); return; } if (StoppedCancellationTokenSource.IsCancellationRequested) return; // if null is a valid value, it means that there's nothing to do. if (null == table && reminderTable is MockReminderTable) return; var remindersNotInTable = localReminders.Where(r => range.InRange(r.Key.GrainRef)).ToDictionary(r => r.Key, r => r.Value); // shallow copy if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence); foreach (ReminderEntry entry in table.Reminders) { var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData localRem; if (localReminders.TryGetValue(key, out localRem)) { if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info { if (localRem.Timer != null) // if ticking { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Ticking {0}", localRem); // it might happen that our local reminder is different than the one in the table, i.e., eTag is different // if so, stop the local timer for the old reminder, and start again with new info if (!localRem.ETag.Equals(entry.ETag)) // this reminder needs a restart { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("{0} Needs a restart", localRem); localRem.StopReminder(logger); localReminders.Remove(localRem.Identity); StartAndAddTimer(entry); } } else // if not ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Not Ticking {0}", localRem); } } else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info { if (localRem.Timer != null) // if ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Ticking {0}", localRem); } else // if not ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Not Ticking {0}", localRem); } } } else // exists in table, but not locally { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, Not in local, {0}", entry); // create and start the reminder StartAndAddTimer(entry); } // keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list remindersNotInTable.Remove(key); } // foreach reminder read from table int remindersCountBeforeRemove = localReminders.Count; // foreach reminder that is not in global table, but exists locally foreach (var reminder in remindersNotInTable.Values) { if (cachedSequence < reminder.LocalSequenceNumber) { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Newer, {0}", reminder); } else // cachedSequence > reminder.LocalSequenceNumber { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Old, so removing. {0}", reminder); // remove locally reminder.StopReminder(logger); localReminders.Remove(reminder.Identity); } } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"Removed {localReminders.Count - remindersCountBeforeRemove} reminders from local table"); } catch (Exception exc) { logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc); throw; } } private void StartAndAddTimer(ReminderEntry entry) { // it might happen that we already have a local reminder with a different eTag // if so, stop the local timer for the old reminder, and start again with new info // Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData prevReminder; if (localReminders.TryGetValue(key, out prevReminder)) // if found locally { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_LocalStop, "Localy stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry); prevReminder.StopReminder(logger); localReminders.Remove(prevReminder.Identity); } var newReminder = new LocalReminderData(entry, this.loggerFactory); localTableSequence++; newReminder.LocalSequenceNumber = localTableSequence; localReminders.Add(newReminder.Identity, newReminder); newReminder.StartTimer(this.RuntimeClient.Scheduler, AsyncTimerCallback, logger); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString()); } // stop without removing it. will remove later. private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName) { // we stop the locally running timer for this reminder var key = new ReminderIdentity(grainRef, reminderName); LocalReminderData localRem; if (!localReminders.TryGetValue(key, out localRem)) return false; // if we have it locally localTableSequence++; // move to next sequence localRem.LocalSequenceNumber = localTableSequence; localRem.StopReminder(logger); return true; } #endregion /// <summary> /// Local timer expired ... notify it as a 'tick' to the grain who registered this reminder /// </summary> /// <param name="rem">Reminder that this timeout represents</param> private async Task AsyncTimerCallback(object rem) { var reminder = (LocalReminderData)rem; if (!localReminders.ContainsKey(reminder.Identity) // we have already stopped this timer || reminder.Timer == null) // this timer was unregistered, and is waiting to be gc-ied return; ticksDeliveredStat.Increment(); await reminder.OnTimerTick(tardinessStat, logger); } #region Utility (less useful) methods private async Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo) { switch (Status) { case GrainServiceStatus.Booting: // if service didn't finish the initial load, it could still be loading normally or it might have already // failed a few attempts and callers should not be hold waiting for it to complete var task = this.startedTask.Task; if (task.IsCompleted) { // task at this point is already Faulted await task; } else { try { // wait for the initial load task to complete (with a timeout) await task.WithTimeout(InitialReadMaxWaitTimeForUpdates); } catch (TimeoutException ex) { throw new OrleansException("Reminder Service is still initializing and it is taking a long time. Please retry again later.", ex); } } break; case GrainServiceStatus.Started: break; case GrainServiceStatus.Stopped: throw new OperationCanceledException("ReminderService has been stopped."); default: throw new InvalidOperationException("status"); } if (!RingRange.InRange(grainRef)) { logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}", debugInfo, grainRef.ToDetailedString(), RingRange); // For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo // otherwise, we can either reject the request, or re-route the request } } // Note: The list of reminders can be huge in production! private void PrintReminders(string msg = null) { if (!logger.IsEnabled(LogLevel.Trace)) return; var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine, Utils.EnumerableToString(localReminders, null, Environment.NewLine)); logger.Trace(str); } #endregion private static GrainId GetGrainId() { var typeCode = GrainInterfaceUtils.GetGrainClassTypeCode(typeof(IReminderService)); return GrainId.GetGrainServiceGrainId(0, typeCode); } private class LocalReminderData { private readonly IRemindable remindable; private Stopwatch stopwatch; private readonly DateTime firstTickTime; // time for the first tick of this reminder private readonly TimeSpan period; private GrainReference GrainRef { get { return Identity.GrainRef; } } private string ReminderName { get { return Identity.ReminderName; } } private readonly ILogger timerLogger; internal ReminderIdentity Identity { get; private set; } internal string ETag; internal IGrainTimer Timer; internal long LocalSequenceNumber; // locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests internal LocalReminderData(ReminderEntry entry, ILoggerFactory loggerFactory) { Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName); firstTickTime = entry.StartAt; period = entry.Period; remindable = entry.GrainRef.Cast<IRemindable>(); ETag = entry.ETag; LocalSequenceNumber = -1; this.timerLogger = loggerFactory.CreateLogger<GrainTimer>(); } public void StartTimer(OrleansTaskScheduler scheduler, Func<object, Task> asyncCallback, ILogger Logger) { StopReminder(Logger); // just to make sure. var dueTimeSpan = CalculateDueTime(); Timer = GrainTimer.FromTaskCallback(scheduler, this.timerLogger, asyncCallback, this, dueTimeSpan, period, name: ReminderName); if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Reminder {0}, Due time{1}", this, dueTimeSpan); Timer.Start(); } public void StopReminder(ILogger Logger) { if (Timer != null) Timer.Dispose(); Timer = null; } private TimeSpan CalculateDueTime() { TimeSpan dueTimeSpan; var now = DateTime.UtcNow; if (now < firstTickTime) // if the time for first tick hasn't passed yet { dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time } else // the first tick happened in the past ... compute duetime based on the first tick time, and period { // formula used: // due = period - 'time passed since last tick (==sinceLast)' // due = period - ((Now - FirstTickTime) % period) // explanation of formula: // (Now - FirstTickTime) => gives amount of time since first tick happened // (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered var sinceFirstTick = now.Subtract(firstTickTime); var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks); dueTimeSpan = period.Subtract(sinceLastTick); // in corner cases, dueTime can be equal to period ... so, take another mod dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks); } return dueTimeSpan; } public async Task OnTimerTick(AverageTimeSpanStatistic tardinessStat, ILogger Logger) { var before = DateTime.UtcNow; var status = TickStatus.NewStruct(firstTickTime, period, before); if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before); try { if (null != stopwatch) { stopwatch.Stop(); var tardiness = stopwatch.Elapsed - period; tardinessStat.AddSample(Math.Max(0, tardiness.Ticks)); } await remindable.ReceiveReminder(ReminderName, status); if (null == stopwatch) stopwatch = new Stopwatch(); stopwatch.Restart(); var after = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds, // the next tick isn't actually scheduled until we return control to // AsyncSafeTimer but we can approximate it by adding the period of the reminder // to the after time. after + period); } catch (Exception exc) { var after = DateTime.UtcNow; Logger.Error( ErrorCode.RS_Tick_Delivery_Error, String.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + period), exc); // What to do with repeated failures to deliver a reminder's ticks? } } public override string ToString() { return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]", ReminderName, GrainRef.ToDetailedString(), period, LogFormatter.PrintDate(firstTickTime), ETag, LocalSequenceNumber, Timer == null ? "Not_ticking" : "Ticking"); } } private struct ReminderIdentity : IEquatable<ReminderIdentity> { private readonly GrainReference grainRef; private readonly string reminderName; public GrainReference GrainRef { get { return grainRef; } } public string ReminderName { get { return reminderName; } } public ReminderIdentity(GrainReference grainRef, string reminderName) { if (grainRef == null) throw new ArgumentNullException("grainRef"); if (string.IsNullOrWhiteSpace(reminderName)) throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName"); this.grainRef = grainRef; this.reminderName = reminderName; } public bool Equals(ReminderIdentity other) { return grainRef.Equals(other.grainRef) && reminderName.Equals(other.reminderName); } public override bool Equals(object other) { return (other is ReminderIdentity) && Equals((ReminderIdentity)other); } public override int GetHashCode() { return unchecked((int)((uint)grainRef.GetHashCode() + (uint)reminderName.GetHashCode())); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Events; using Marten.Linq; using Marten.Patching; using Marten.Schema; using Marten.Services; using Remotion.Linq.Parsing.Structure; namespace Marten { public class DocumentSession : QuerySession, IDocumentSession { private readonly IManagedConnection _connection; private readonly StoreOptions _options; private readonly IDocumentSchema _schema; private readonly ISerializer _serializer; private readonly UnitOfWork _unitOfWork; public DocumentSession(IDocumentStore store, StoreOptions options, IDocumentSchema schema, ISerializer serializer, IManagedConnection connection, IQueryParser parser, IIdentityMap identityMap) : base(store, schema, serializer, connection, parser, identityMap) { _options = options; _schema = schema; _serializer = serializer; _connection = connection; IdentityMap = identityMap; _unitOfWork = new UnitOfWork(_schema); if (IdentityMap is IDocumentTracker) { _unitOfWork.AddTracker(IdentityMap.As<IDocumentTracker>()); } Events = new EventStore(this, schema, _serializer, _connection, _unitOfWork); } // This is here for testing purposes, not part of IDocumentSession public IIdentityMap IdentityMap { get; } public void Delete<T>(T entity) { assertNotDisposed(); if (entity == null) throw new ArgumentNullException(nameof(entity)); var storage = _schema.StorageFor(typeof(T)); var deletion = storage.DeletionForEntity(entity); _unitOfWork.Add(deletion); storage.Remove(IdentityMap, entity); } public void Delete<T>(int id) { delete<T>(id); } private void delete<T>(object id) { assertNotDisposed(); var storage = _schema.StorageFor(typeof(T)); var deletion = storage.DeletionForId(id); _unitOfWork.Add(deletion); storage.Delete(IdentityMap, id); } public void Delete<T>(long id) { delete<T>(id); } public void Delete<T>(Guid id) { delete<T>(id); } public void Delete<T>(string id) { delete<T>(id); } public void DeleteWhere<T>(Expression<Func<T, bool>> expression) { assertNotDisposed(); var model = Query<T>().Where(expression).As<MartenQueryable<T>>().ToQueryModel(); var where = _schema.BuildWhereFragment(model); var deletion = _schema.StorageFor(typeof(T)).DeletionForWhere(where); _unitOfWork.Add(deletion); } public void Store<T>(params T[] entities) { assertNotDisposed(); if (entities == null) throw new ArgumentNullException(nameof(entities)); if (typeof(T).IsGenericEnumerable()) { throw new ArgumentOutOfRangeException(typeof(T).Name, "Do not use IEnumerable<T> here as the document type. You may need to cast entities to an array instead."); } if (typeof(T) == typeof(object)) { StoreObjects(entities.OfType<object>()); } else { var storage = _schema.StorageFor(typeof(T)); var idAssignment = _schema.IdAssignmentFor<T>(); foreach (var entity in entities) { var assigned = false; var id = idAssignment.Assign(entity, out assigned); storage.Store(IdentityMap, id, entity); if (assigned) { _unitOfWork.StoreInserts(entity); } else { _unitOfWork.StoreUpdates(entity); } } } } public void Store<T>(T entity, Guid version) { assertNotDisposed(); var storage = _schema.StorageFor(typeof(T)); var id = storage.Identity(entity); IdentityMap.Versions.Store<T>(id, version); Store(entity); } public IUnitOfWork PendingChanges => _unitOfWork; public void StoreObjects(IEnumerable<object> documents) { assertNotDisposed(); documents.Where(x => x != null).GroupBy(x => x.GetType()).Each(group => { var handler = typeof(Handler<>).CloseAndBuildAs<IHandler>(group.Key); handler.Store(this, group); }); } public IEventStore Events { get; } public void SaveChanges() { if (!_unitOfWork.HasAnyUpdates()) return; assertNotDisposed(); _connection.BeginTransaction(); applyProjections(); _options.Listeners.Each(x => x.BeforeSaveChanges(this)); var batch = new UpdateBatch(_options, _serializer, _connection, IdentityMap.Versions); var changes = _unitOfWork.ApplyChanges(batch); try { _connection.Commit(); } catch (Exception) { // This code has a try/catch in it to stop // any errors from propogating from the rollback _connection.Rollback(); throw; } Logger.RecordSavedChanges(this, changes); _options.Listeners.Each(x => x.AfterCommit(this, changes)); } public async Task SaveChangesAsync(CancellationToken token) { if (!_unitOfWork.HasAnyUpdates()) return; assertNotDisposed(); await _connection.BeginTransactionAsync(token).ConfigureAwait(false); await applyProjectionsAsync(token).ConfigureAwait(false); foreach (var listener in _options.Listeners) { await listener.BeforeSaveChangesAsync(this, token).ConfigureAwait(false); } var batch = new UpdateBatch(_options, _serializer, _connection, IdentityMap.Versions); var changes = await _unitOfWork.ApplyChangesAsync(batch, token).ConfigureAwait(false); try { await _connection.CommitAsync(token).ConfigureAwait(false); } catch (Exception) { // This code has a try/catch in it to stop // any errors from propogating from the rollback await _connection.RollbackAsync(token).ConfigureAwait(false); throw; } Logger.RecordSavedChanges(this, changes); foreach (var listener in _options.Listeners) { await listener.AfterCommitAsync(this, changes, token).ConfigureAwait(false); } } public IPatchExpression<T> Patch<T>(int id) { return patchById<T>(id); } public IPatchExpression<T> Patch<T>(long id) { return patchById<T>(id); } public IPatchExpression<T> Patch<T>(string id) { return patchById<T>(id); } public IPatchExpression<T> Patch<T>(Guid id) { return patchById<T>(id); } private IPatchExpression<T> patchById<T>(object id) { assertNotDisposed(); var @where = new WhereFragment("where d.id = ?", id); return new PatchExpression<T>(@where, _schema, _unitOfWork); } public IPatchExpression<T> Patch<T>(Expression<Func<T, bool>> @where) { assertNotDisposed(); var model = Query<T>().Where(@where).As<MartenQueryable<T>>().ToQueryModel(); var fragment = _schema.BuildWhereFragment(model); return new PatchExpression<T>(fragment, _schema, _unitOfWork); } public IPatchExpression<T> Patch<T>(IWhereFragment fragment) { assertNotDisposed(); return new PatchExpression<T>(fragment, _schema, _unitOfWork); } public void QueueOperation(IStorageOperation storageOperation) { assertNotDisposed(); _unitOfWork.Add(storageOperation); } private void applyProjections() { var streams = PendingChanges.Streams().ToArray(); foreach (var projection in _schema.Events.InlineProjections) { projection.Apply(this, streams); } } private async Task applyProjectionsAsync(CancellationToken token) { var streams = PendingChanges.Streams().ToArray(); foreach (var projection in _schema.Events.InlineProjections) { await projection.ApplyAsync(this, streams, token); } } internal interface IHandler { void Store(IDocumentSession session, IEnumerable<object> objects); } internal class Handler<T> : IHandler { public void Store(IDocumentSession session, IEnumerable<object> objects) { session.Store(objects.OfType<T>().ToArray()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogical128BitLaneUInt161() { var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161 { private struct TestStruct { public Vector256<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161 testClass) { var result = Avx2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector256<UInt16> _clsVar; private Vector256<UInt16> _fld; private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable; static ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical128BitLane( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical128BitLane( Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical128BitLane( Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt161(); var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 2048) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 7 || i == 15 ? result[i] != 0 : result[i] != 2048)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<UInt16>(Vector256<UInt16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareOrderedSingle() { var test = new SimpleBinaryOpTest__CompareOrderedSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareOrderedSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareOrderedSingle testClass) { var result = Sse.CompareOrdered(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareOrderedSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareOrderedSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareOrderedSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareOrdered( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareOrdered( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareOrdered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareOrdered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareOrdered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareOrdered( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareOrderedSingle(); var result = Sse.CompareOrdered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareOrderedSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareOrdered(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareOrdered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareOrdered( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != ((!float.IsNaN(left[0]) && !float.IsNaN(right[0])) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != ((!float.IsNaN(left[i]) && !float.IsNaN(right[i])) ? -1 : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareOrdered)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.GenerateDefaultConstructors { public class GenerateDefaultConstructorsTests : AbstractCSharpCodeActionTest { protected override object CreateCodeRefactoringProvider(Workspace workspace) { return new GenerateDefaultConstructorsCodeRefactoringProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestProtectedBase() { await TestAsync( @"class C : [||]B { } class B { protected B(int x) { } }", @"class C : B { protected C(int x) : base(x) { } } class B { protected B(int x) { } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPublicBase() { await TestAsync( @"class C : [||]B { } class B { public B(int x) { } }", @"class C : B { public C(int x) : base(x) { } } class B { public B(int x) { } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestInternalBase() { await TestAsync( @"class C : [||]B { } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestPrivateBase() { await TestMissingAsync( @"class C : [||]B { } class B { private B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefOutParams() { await TestAsync( @"class C : [||]B { } class B { internal B(ref int x, out string s, params bool[] b) { } }", @"class C : B { internal C(ref int x, out string s, params bool[] b) : base(ref x, out s, b) { } } class B { internal B(ref int x, out string s, params bool[] b) { } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix1() { await TestAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFix2() { await TestAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { protected C(string x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestRefactoring1() { await TestAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll1() { await TestAsync( @"class C : [||]B { } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) : base(x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixAll2() { await TestAsync( @"class C : [||]B { public C(bool x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", @"class C : B { public C(bool x) { } protected C(string x) : base(x) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } protected B(string x) { } public B(bool x) { } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestMissing1() { await TestMissingAsync( @"class C : [||]B { public C(int x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_1() { await TestAsync( @"class C : [||]B { public C(int y) { } } class B { internal B(int x) { } }", @"class C : B { public C(int y) { } internal C(int x) : base(x) { } } class B { internal B(int x) { } }"); } [WorkItem(889349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/889349")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestDefaultConstructorGeneration_2() { await TestAsync( @"class C : [||]B { private C(int y) { } } class B { internal B(int x) { } }", @"class C : B { internal C(int x) : base(x) { } private C(int y) { } } class B { internal B(int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestFixCount1() { await TestActionCountAsync( @"class C : [||]B { } class B { public B(int x) { } }", count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] [WorkItem(544070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544070")] public async Task TestException1() { await TestAsync( @"using System; class Program : Excep[||]tion { }", @"using System; using System.Runtime.Serialization; class Program : Exception { public Program() { } public Program(string message) : base(message) { } public Program(string message, Exception innerException) : base(message, innerException) { } protected Program(SerializationInfo info, StreamingContext context) : base(info, context) { } }", index: 3, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException2() { await TestAsync( @"using System ; using System . Collections . Generic ; using System . Linq ; class Program : [||]Exception { public Program ( ) { } static void Main ( string [ ] args ) { } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; using System . Runtime . Serialization; class Program : Exception { public Program ( ) { } public Program ( string message ) : base ( message ) { } public Program ( string message , Exception innerException ) : base ( message , innerException ) { } protected Program (SerializationInfo info , StreamingContext context ) : base ( info , context ) { } static void Main ( string [ ] args ) { } } ", index: 3); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException3() { await TestAsync( @"using System ; using System . Collections . Generic ; using System . Linq ; class Program : [||]Exception { public Program ( string message ) : base ( message ) { } public Program ( string message , Exception innerException ) : base ( message , innerException ) { } protected Program ( System . Runtime . Serialization . SerializationInfo info , System . Runtime . Serialization . StreamingContext context ) : base ( info , context ) { } static void Main ( string [ ] args ) { } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program : Exception { public Program ( ) { } public Program ( string message ) : base ( message ) { } public Program ( string message , Exception innerException ) : base ( message , innerException ) { } protected Program ( System . Runtime . Serialization . SerializationInfo info , System . Runtime . Serialization . StreamingContext context ) : base ( info , context ) { } static void Main ( string [ ] args ) { } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateDefaultConstructors)] public async Task TestException4() { await TestAsync( @"using System ; using System . Collections . Generic ; using System . Linq ; class Program : [||]Exception { public Program ( string message , Exception innerException ) : base ( message , innerException ) { } protected Program ( System . Runtime . Serialization . SerializationInfo info , System . Runtime . Serialization . StreamingContext context ) : base ( info , context ) { } static void Main ( string [ ] args ) { } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program : Exception { public Program ( ) { } public Program ( ) { } public Program ( string message ) : base ( message ) { } public Program ( string message , Exception innerException ) : base ( message , innerException ) { } protected Program ( System . Runtime . Serialization . SerializationInfo info , System . Runtime . Serialization . StreamingContext context ) : base ( info , context ) { } static void Main ( string [ ] args ) { } } ", index: 2); } } }
using Coalesce.Web.Models; using IntelliTect.Coalesce; using IntelliTect.Coalesce.Api; using IntelliTect.Coalesce.Api.Controllers; using IntelliTect.Coalesce.Api.DataSources; using IntelliTect.Coalesce.Mapping; using IntelliTect.Coalesce.Mapping.IncludeTrees; using IntelliTect.Coalesce.Models; using IntelliTect.Coalesce.TypeDefinition; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Coalesce.Web.Api { [Route("api/Case")] [Authorize] [ServiceFilter(typeof(IApiActionFilter))] public partial class CaseController : BaseApiController<Coalesce.Domain.Case, CaseDtoGen, Coalesce.Domain.AppDbContext> { public CaseController(Coalesce.Domain.AppDbContext db) : base(db) { GeneratedForClassViewModel = ReflectionRepository.Global.GetClassViewModel<Coalesce.Domain.Case>(); } [HttpGet("get/{id}")] [AllowAnonymous] public virtual Task<ItemResult<CaseDtoGen>> Get( int id, DataSourceParameters parameters, IDataSource<Coalesce.Domain.Case> dataSource) => GetImplementation(id, parameters, dataSource); [HttpGet("list")] [AllowAnonymous] public virtual Task<ListResult<CaseDtoGen>> List( ListParameters parameters, IDataSource<Coalesce.Domain.Case> dataSource) => ListImplementation(parameters, dataSource); [HttpGet("count")] [AllowAnonymous] public virtual Task<ItemResult<int>> Count( FilterParameters parameters, IDataSource<Coalesce.Domain.Case> dataSource) => CountImplementation(parameters, dataSource); [HttpPost("save")] [AllowAnonymous] public virtual Task<ItemResult<CaseDtoGen>> Save( CaseDtoGen dto, [FromQuery] DataSourceParameters parameters, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) => SaveImplementation(dto, parameters, dataSource, behaviors); [HttpPost("delete/{id}")] [Authorize] public virtual Task<ItemResult<CaseDtoGen>> Delete( int id, IBehaviors<Coalesce.Domain.Case> behaviors, IDataSource<Coalesce.Domain.Case> dataSource) => DeleteImplementation(id, new DataSourceParameters(), dataSource, behaviors); // Methods from data class exposed through API Controller. /// <summary> /// Method: GetSomeCases /// </summary> [HttpPost("GetSomeCases")] [Authorize] public virtual ItemResult<System.Collections.Generic.ICollection<CaseDtoGen>> GetSomeCases() { IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = Coalesce.Domain.Case.GetSomeCases(Db); var _result = new ItemResult<System.Collections.Generic.ICollection<CaseDtoGen>>(); _result.Object = _methodResult?.ToList().Select(o => Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(o, _mappingContext, includeTree)).ToList(); return _result; } /// <summary> /// Method: GetAllOpenCasesCount /// </summary> [HttpPost("GetAllOpenCasesCount")] [Authorize] public virtual ItemResult<int> GetAllOpenCasesCount() { var _methodResult = Coalesce.Domain.Case.GetAllOpenCasesCount(Db); var _result = new ItemResult<int>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: RandomizeDatesAndStatus /// </summary> [HttpPost("RandomizeDatesAndStatus")] [Authorize] public virtual ItemResult RandomizeDatesAndStatus() { Coalesce.Domain.Case.RandomizeDatesAndStatus(Db); var _result = new ItemResult(); return _result; } /// <summary> /// Method: UploadAttachment /// </summary> [HttpPost("UploadAttachment")] [Authorize] public virtual async Task<ItemResult> UploadAttachment([FromServices] IDataSourceFactory dataSourceFactory, int id, Microsoft.AspNetCore.Http.IFormFile file) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Case, Coalesce.Domain.Case>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult(itemResult); } var item = itemResult.Object; await item.UploadAttachment(file == null ? null : new File { Name = file.FileName, ContentType = file.ContentType, Length = file.Length, Content = file.OpenReadStream() }); await Db.SaveChangesAsync(); var _result = new ItemResult(); return _result; } /// <summary> /// Method: UploadByteArray /// </summary> [HttpPost("UploadByteArray")] [Authorize] public virtual async Task<ItemResult> UploadByteArray([FromServices] IDataSourceFactory dataSourceFactory, int id, byte[] file) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Case, Coalesce.Domain.Case>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult(itemResult); } var item = itemResult.Object; item.UploadByteArray(file ?? await ((await Request.ReadFormAsync()).Files[nameof(file)]?.OpenReadStream().ReadAllBytesAsync(true) ?? Task.FromResult<byte[]>(null))); await Db.SaveChangesAsync(); var _result = new ItemResult(); return _result; } /// <summary> /// Method: GetCaseSummary /// </summary> [HttpPost("GetCaseSummary")] [Authorize] public virtual ItemResult<CaseSummaryDtoGen> GetCaseSummary() { IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = Coalesce.Domain.Case.GetCaseSummary(Db); var _result = new ItemResult<CaseSummaryDtoGen>(); _result.Object = Mapper.MapToDto<Coalesce.Domain.CaseSummary, CaseSummaryDtoGen>(_methodResult, _mappingContext, includeTree); return _result; } /// <summary> /// File Download: Image /// </summary> [Authorize] [HttpGet("Image")] public virtual async Task<IActionResult> ImageGet(int id, IDataSource<Coalesce.Domain.Case> dataSource) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (itemResult.Object?.Image == null) return NotFound(); string contentType = "image/jpeg"; if (!(new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider().TryGetContentType(itemResult.Object.ImageName, out contentType))) { contentType = "image/jpeg"; } return File(itemResult.Object.Image, contentType, itemResult.Object.ImageName); } /// <summary> /// File Upload: Image /// </summary> [Authorize] [HttpPut("Image")] public virtual async Task<ItemResult<CaseDtoGen>> ImagePut(int id, IFormFile file, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return new ItemResult<CaseDtoGen>(itemResult); using (var stream = new System.IO.MemoryStream()) { await file.CopyToAsync(stream); itemResult.Object.Image = stream.ToArray(); using (var sha256Hash = System.Security.Cryptography.SHA256.Create()) { var hash = sha256Hash.ComputeHash(itemResult.Object.Image); itemResult.Object.ImageHash = Convert.ToBase64String(hash); } itemResult.Object.ImageSize = file.Length; await Db.SaveChangesAsync(); } var result = new ItemResult<CaseDtoGen>(); var mappingContext = new MappingContext(User); result.Object = Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(itemResult.Object, mappingContext, null); return result; } /// <summary> /// File Delete: Image /// </summary> [Authorize] [HttpDelete("Image")] public virtual async Task<IActionResult> ImageDelete(int id, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return NotFound(); itemResult.Object.ImageHash = null; itemResult.Object.ImageSize = 0; itemResult.Object.Image = null; await Db.SaveChangesAsync(); return Ok(); } /// <summary> /// File Download: PlainAttachment /// </summary> [AllowAnonymous] [HttpGet("PlainAttachment")] public virtual async Task<IActionResult> PlainAttachmentGet(int id, IDataSource<Coalesce.Domain.Case> dataSource) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (itemResult.Object?.PlainAttachment == null) return NotFound(); string contentType = "text/plain"; return File(itemResult.Object.PlainAttachment, contentType); } /// <summary> /// File Upload: PlainAttachment /// </summary> [Authorize] [HttpPut("PlainAttachment")] public virtual async Task<ItemResult<CaseDtoGen>> PlainAttachmentPut(int id, IFormFile file, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return new ItemResult<CaseDtoGen>(itemResult); using (var stream = new System.IO.MemoryStream()) { await file.CopyToAsync(stream); itemResult.Object.PlainAttachment = stream.ToArray(); await Db.SaveChangesAsync(); } var result = new ItemResult<CaseDtoGen>(); var mappingContext = new MappingContext(User); result.Object = Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(itemResult.Object, mappingContext, null); return result; } /// <summary> /// File Delete: PlainAttachment /// </summary> [Authorize] [HttpDelete("PlainAttachment")] public virtual async Task<IActionResult> PlainAttachmentDelete(int id, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return NotFound(); itemResult.Object.PlainAttachment = null; await Db.SaveChangesAsync(); return Ok(); } /// <summary> /// File Download: RestrictedUploadAttachment /// </summary> [Authorize] [HttpGet("RestrictedUploadAttachment")] public virtual async Task<IActionResult> RestrictedUploadAttachmentGet(int id, IDataSource<Coalesce.Domain.Case> dataSource) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (itemResult.Object?.RestrictedUploadAttachment == null) return NotFound(); string contentType = "application/octet-stream"; return File(itemResult.Object.RestrictedUploadAttachment, contentType); } /// <summary> /// File Upload: RestrictedUploadAttachment /// </summary> [Authorize(Roles = "Admin,SuperUser")] [HttpPut("RestrictedUploadAttachment")] public virtual async Task<ItemResult<CaseDtoGen>> RestrictedUploadAttachmentPut(int id, IFormFile file, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return new ItemResult<CaseDtoGen>(itemResult); using (var stream = new System.IO.MemoryStream()) { await file.CopyToAsync(stream); itemResult.Object.RestrictedUploadAttachment = stream.ToArray(); await Db.SaveChangesAsync(); } var result = new ItemResult<CaseDtoGen>(); var mappingContext = new MappingContext(User); result.Object = Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(itemResult.Object, mappingContext, null); return result; } /// <summary> /// File Delete: RestrictedUploadAttachment /// </summary> [Authorize] [HttpDelete("RestrictedUploadAttachment")] public virtual async Task<IActionResult> RestrictedUploadAttachmentDelete(int id, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return NotFound(); itemResult.Object.RestrictedUploadAttachment = null; await Db.SaveChangesAsync(); return Ok(); } /// <summary> /// File Download: RestrictedDownloadAttachment /// </summary> [Authorize(Roles = "Admin,OtherRole")] [HttpGet("RestrictedDownloadAttachment")] public virtual async Task<IActionResult> RestrictedDownloadAttachmentGet(int id, IDataSource<Coalesce.Domain.Case> dataSource) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (itemResult.Object?.RestrictedDownloadAttachment == null) return NotFound(); string contentType = "application/octet-stream"; return File(itemResult.Object.RestrictedDownloadAttachment, contentType); } /// <summary> /// File Upload: RestrictedDownloadAttachment /// </summary> [Authorize] [HttpPut("RestrictedDownloadAttachment")] public virtual async Task<ItemResult<CaseDtoGen>> RestrictedDownloadAttachmentPut(int id, IFormFile file, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return new ItemResult<CaseDtoGen>(itemResult); using (var stream = new System.IO.MemoryStream()) { await file.CopyToAsync(stream); itemResult.Object.RestrictedDownloadAttachment = stream.ToArray(); await Db.SaveChangesAsync(); } var result = new ItemResult<CaseDtoGen>(); var mappingContext = new MappingContext(User); result.Object = Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(itemResult.Object, mappingContext, null); return result; } /// <summary> /// File Delete: RestrictedDownloadAttachment /// </summary> [Authorize] [HttpDelete("RestrictedDownloadAttachment")] public virtual async Task<IActionResult> RestrictedDownloadAttachmentDelete(int id, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return NotFound(); itemResult.Object.RestrictedDownloadAttachment = null; await Db.SaveChangesAsync(); return Ok(); } /// <summary> /// File Download: RestrictedMetaAttachment /// </summary> [Authorize] [HttpGet("RestrictedMetaAttachment")] public virtual async Task<IActionResult> RestrictedMetaAttachmentGet(int id, IDataSource<Coalesce.Domain.Case> dataSource) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (itemResult.Object?.RestrictedMetaAttachment == null) return NotFound(); string contentType = "application/octet-stream"; if (!(new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider().TryGetContentType(itemResult.Object.InternalUseFileName, out contentType))) { contentType = "application/octet-stream"; } return File(itemResult.Object.RestrictedMetaAttachment, contentType, itemResult.Object.InternalUseFileName); } /// <summary> /// File Upload: RestrictedMetaAttachment /// </summary> [Authorize] [HttpPut("RestrictedMetaAttachment")] public virtual async Task<ItemResult<CaseDtoGen>> RestrictedMetaAttachmentPut(int id, IFormFile file, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return new ItemResult<CaseDtoGen>(itemResult); using (var stream = new System.IO.MemoryStream()) { await file.CopyToAsync(stream); itemResult.Object.RestrictedMetaAttachment = stream.ToArray(); itemResult.Object.InternalUseFileName = file.FileName; itemResult.Object.InternalUseFileSize = file.Length; await Db.SaveChangesAsync(); } var result = new ItemResult<CaseDtoGen>(); var mappingContext = new MappingContext(User); result.Object = Mapper.MapToDto<Coalesce.Domain.Case, CaseDtoGen>(itemResult.Object, mappingContext, null); return result; } /// <summary> /// File Delete: RestrictedMetaAttachment /// </summary> [Authorize] [HttpDelete("RestrictedMetaAttachment")] public virtual async Task<IActionResult> RestrictedMetaAttachmentDelete(int id, IDataSource<Coalesce.Domain.Case> dataSource, IBehaviors<Coalesce.Domain.Case> behaviors) { var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) return NotFound(); itemResult.Object.InternalUseFileName = null; itemResult.Object.InternalUseFileSize = 0; itemResult.Object.RestrictedMetaAttachment = null; await Db.SaveChangesAsync(); return Ok(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundCurrentDirectionScalarSingle() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle testClass) { var result = Sse41.RoundCurrentDirectionScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundCurrentDirectionScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirectionScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundCurrentDirectionScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.RoundCurrentDirectionScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundCurrentDirectionScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundCurrentDirectionScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle(); var result = Sse41.RoundCurrentDirectionScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundCurrentDirectionScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundCurrentDirectionScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundCurrentDirectionScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundCurrentDirectionScalar( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirectionScalar)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Management.RADIUSServerBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementRADIUSServerRADIUSServerDefinition))] public partial class ManagementRADIUSServer : iControlInterface { public ManagementRADIUSServer() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void create( ManagementRADIUSServerRADIUSServerDefinition [] servers ) { this.Invoke("create", new object [] { servers}); } public System.IAsyncResult Begincreate(ManagementRADIUSServerRADIUSServerDefinition [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { servers}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_servers //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void delete_all_servers( ) { this.Invoke("delete_all_servers", new object [0]); } public System.IAsyncResult Begindelete_all_servers(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_servers", new object[0], callback, asyncState); } public void Enddelete_all_servers(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void delete_server( string [] servers ) { this.Invoke("delete_server", new object [] { servers}); } public System.IAsyncResult Begindelete_server(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_server", new object[] { servers}, callback, asyncState); } public void Enddelete_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] servers ) { object [] results = this.Invoke("get_description", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { servers}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_ip_or_hostname //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_ip_or_hostname( string [] servers ) { object [] results = this.Invoke("get_ip_or_hostname", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_ip_or_hostname(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ip_or_hostname", new object[] { servers}, callback, asyncState); } public string [] Endget_ip_or_hostname(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_port( string [] servers ) { object [] results = this.Invoke("get_port", new object [] { servers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_port(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_port", new object[] { servers}, callback, asyncState); } public long [] Endget_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_secret //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_secret( string [] servers ) { object [] results = this.Invoke("get_secret", new object [] { servers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_secret(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_secret", new object[] { servers}, callback, asyncState); } public string [] Endget_secret(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_timeout( string [] servers ) { object [] results = this.Invoke("get_timeout", new object [] { servers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_timeout(string [] servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_timeout", new object[] { servers}, callback, asyncState); } public long [] Endget_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void set_description( string [] servers, string [] descriptions ) { this.Invoke("set_description", new object [] { servers, descriptions}); } public System.IAsyncResult Beginset_description(string [] servers,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { servers, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ip_or_hostname //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void set_ip_or_hostname( string [] servers, string [] ip_or_hostnames ) { this.Invoke("set_ip_or_hostname", new object [] { servers, ip_or_hostnames}); } public System.IAsyncResult Beginset_ip_or_hostname(string [] servers,string [] ip_or_hostnames, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ip_or_hostname", new object[] { servers, ip_or_hostnames}, callback, asyncState); } public void Endset_ip_or_hostname(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_port //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void set_port( string [] servers, long [] ports ) { this.Invoke("set_port", new object [] { servers, ports}); } public System.IAsyncResult Beginset_port(string [] servers,long [] ports, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_port", new object[] { servers, ports}, callback, asyncState); } public void Endset_port(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_secret //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void set_secret( string [] servers, string [] secrets ) { this.Invoke("set_secret", new object [] { servers, secrets}); } public System.IAsyncResult Beginset_secret(string [] servers,string [] secrets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_secret", new object[] { servers, secrets}, callback, asyncState); } public void Endset_secret(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSServer", RequestNamespace="urn:iControl:Management/RADIUSServer", ResponseNamespace="urn:iControl:Management/RADIUSServer")] public void set_timeout( string [] servers, long [] timeouts ) { this.Invoke("set_timeout", new object [] { servers, timeouts}); } public System.IAsyncResult Beginset_timeout(string [] servers,long [] timeouts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_timeout", new object[] { servers, timeouts}, callback, asyncState); } public void Endset_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.RADIUSServer.RADIUSServerDefinition", Namespace = "urn:iControl")] public partial class ManagementRADIUSServerRADIUSServerDefinition { private string nameField; public string name { get { return this.nameField; } set { this.nameField = value; } } private string ip_or_hostnameField; public string ip_or_hostname { get { return this.ip_or_hostnameField; } set { this.ip_or_hostnameField = value; } } private long serviceField; public long service { get { return this.serviceField; } set { this.serviceField = value; } } private string secretField; public string secret { get { return this.secretField; } set { this.secretField = value; } } }; }
using System; using System.Collections.Concurrent; using System.Linq.Expressions; using System.Threading.Tasks; using Moq; using Xunit; using WireMock.Models; using WireMock.Owin; using WireMock.Owin.Mappers; using WireMock.Util; using WireMock.Logging; using WireMock.Matchers; using System.Collections.Generic; using WireMock.Admin.Mappings; using WireMock.Admin.Requests; using WireMock.Settings; using FluentAssertions; using WireMock.Handlers; using WireMock.ResponseBuilders; using WireMock.RequestBuilders; #if NET452 using Microsoft.Owin; using IContext = Microsoft.Owin.IOwinContext; using IRequest = Microsoft.Owin.IOwinRequest; using IResponse = Microsoft.Owin.IOwinResponse; #else using Microsoft.AspNetCore.Http; using IContext = Microsoft.AspNetCore.Http.HttpContext; using IRequest = Microsoft.AspNetCore.Http.HttpRequest; using IResponse = Microsoft.AspNetCore.Http.HttpResponse; #endif namespace WireMock.Net.Tests.Owin { public class WireMockMiddlewareTests { private readonly WireMockMiddleware _sut; private readonly Mock<IWireMockMiddlewareOptions> _optionsMock; private readonly Mock<IOwinRequestMapper> _requestMapperMock; private readonly Mock<IOwinResponseMapper> _responseMapperMock; private readonly Mock<IMappingMatcher> _matcherMock; private readonly Mock<IMapping> _mappingMock; private readonly Mock<IContext> _contextMock; private readonly ConcurrentDictionary<Guid, IMapping> _mappings = new ConcurrentDictionary<Guid, IMapping>(); public WireMockMiddlewareTests() { _optionsMock = new Mock<IWireMockMiddlewareOptions>(); _optionsMock.SetupAllProperties(); _optionsMock.Setup(o => o.Mappings).Returns(_mappings); _optionsMock.Setup(o => o.LogEntries).Returns(new ConcurrentObservableCollection<LogEntry>()); _optionsMock.Setup(o => o.Scenarios).Returns(new ConcurrentDictionary<string, ScenarioState>()); _optionsMock.Setup(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>())); _optionsMock.Setup(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>())); _optionsMock.Setup(o => o.Logger.DebugRequestResponse(It.IsAny<LogEntryModel>(), It.IsAny<bool>())); _requestMapperMock = new Mock<IOwinRequestMapper>(); _requestMapperMock.SetupAllProperties(); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1"); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request); _responseMapperMock = new Mock<IOwinResponseMapper>(); _responseMapperMock.SetupAllProperties(); _responseMapperMock.Setup(m => m.MapAsync(It.IsAny<ResponseMessage>(), It.IsAny<IResponse>())).Returns(Task.FromResult(true)); _matcherMock = new Mock<IMappingMatcher>(); _matcherMock.SetupAllProperties(); _matcherMock.Setup(m => m.FindBestMatch(It.IsAny<RequestMessage>())).Returns((new MappingMatcherResult(), new MappingMatcherResult())); _contextMock = new Mock<IContext>(); _mappingMock = new Mock<IMapping>(); _sut = new WireMockMiddleware(null, _optionsMock.Object, _requestMapperMock.Object, _responseMapperMock.Object, _matcherMock.Object); } [Fact] public async Task WireMockMiddleware_Invoke_NoMatch() { // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); // Assert and Verify _optionsMock.Verify(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once); Expression<Func<ResponseMessage, bool>> match = r => (int)r.StatusCode == 404 && ((StatusModel)r.BodyData.BodyAsJson).Status == "No matching mapping found"; _responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once); } [Fact] public async Task WireMockMiddleware_Invoke_IsAdminInterface_EmptyHeaders_401() { // Assign var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]>()); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request); _optionsMock.SetupGet(o => o.AuthenticationMatcher).Returns(new ExactMatcher()); _mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true); var result = new MappingMatcherResult { Mapping = _mappingMock.Object }; _matcherMock.Setup(m => m.FindBestMatch(It.IsAny<RequestMessage>())).Returns((result, result)); // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); // Assert and Verify _optionsMock.Verify(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once); Expression<Func<ResponseMessage, bool>> match = r => (int)r.StatusCode == 401; _responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once); } [Fact] public async Task WireMockMiddleware_Invoke_IsAdminInterface_MissingHeader_401() { // Assign var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]> { { "h", new[] { "x" } } }); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request); _optionsMock.SetupGet(o => o.AuthenticationMatcher).Returns(new ExactMatcher()); _mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true); var result = new MappingMatcherResult { Mapping = _mappingMock.Object }; _matcherMock.Setup(m => m.FindBestMatch(It.IsAny<RequestMessage>())).Returns((result, result)); // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); // Assert and Verify _optionsMock.Verify(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once); Expression<Func<ResponseMessage, bool>> match = r => (int)r.StatusCode == 401; _responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once); } [Fact] public async Task WireMockMiddleware_Invoke_RequestLogExpirationDurationIsDefined() { // Assign _optionsMock.SetupGet(o => o.RequestLogExpirationDuration).Returns(1); // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); } [Fact] public async Task WireMockMiddleware_Invoke_Mapping_Has_ProxyAndRecordSettings_And_SaveMapping_Is_True() { // Assign var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]>()); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request); _optionsMock.SetupGet(o => o.AuthenticationMatcher).Returns(new ExactMatcher()); var fileSystemHandlerMock = new Mock<IFileSystemHandler>(); fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m"); var logger = new Mock<IWireMockLogger>(); var proxyAndRecordSettings = new ProxyAndRecordSettings { SaveMapping = true, SaveMappingToFile = true }; var settings = new WireMockServerSettings { FileSystemHandler = fileSystemHandlerMock.Object, Logger = logger.Object }; var responseBuilder = Response.Create().WithProxy(proxyAndRecordSettings); _mappingMock.SetupGet(m => m.Provider).Returns(responseBuilder); _mappingMock.SetupGet(m => m.Settings).Returns(settings); var newMappingFromProxy = new Mapping(Guid.NewGuid(), "", null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, null); _mappingMock.Setup(m => m.ProvideResponseAsync(It.IsAny<RequestMessage>())).ReturnsAsync((new ResponseMessage(), newMappingFromProxy)); var requestBuilder = Request.Create().UsingAnyMethod(); _mappingMock.SetupGet(m => m.RequestMatcher).Returns(requestBuilder); var result = new MappingMatcherResult { Mapping = _mappingMock.Object }; _matcherMock.Setup(m => m.FindBestMatch(It.IsAny<RequestMessage>())).Returns((result, result)); // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); // Assert and Verify fileSystemHandlerMock.Verify(f => f.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Once); _mappings.Count.Should().Be(1); } [Fact] public async Task WireMockMiddleware_Invoke_Mapping_Has_ProxyAndRecordSettings_And_SaveMapping_Is_False_But_WireMockServerSettings_SaveMapping_Is_True() { // Assign var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]>()); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request); _optionsMock.SetupGet(o => o.AuthenticationMatcher).Returns(new ExactMatcher()); var fileSystemHandlerMock = new Mock<IFileSystemHandler>(); fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m"); var logger = new Mock<IWireMockLogger>(); var proxyAndRecordSettings = new ProxyAndRecordSettings { SaveMapping = false, SaveMappingToFile = false }; var settings = new WireMockServerSettings { FileSystemHandler = fileSystemHandlerMock.Object, Logger = logger.Object, ProxyAndRecordSettings = new ProxyAndRecordSettings { SaveMapping = true, SaveMappingToFile = true } }; var responseBuilder = Response.Create().WithProxy(proxyAndRecordSettings); _mappingMock.SetupGet(m => m.Provider).Returns(responseBuilder); _mappingMock.SetupGet(m => m.Settings).Returns(settings); var newMappingFromProxy = new Mapping(Guid.NewGuid(), "", null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, null); _mappingMock.Setup(m => m.ProvideResponseAsync(It.IsAny<RequestMessage>())).ReturnsAsync((new ResponseMessage(), newMappingFromProxy)); var requestBuilder = Request.Create().UsingAnyMethod(); _mappingMock.SetupGet(m => m.RequestMatcher).Returns(requestBuilder); var result = new MappingMatcherResult { Mapping = _mappingMock.Object }; _matcherMock.Setup(m => m.FindBestMatch(It.IsAny<RequestMessage>())).Returns((result, result)); // Act await _sut.Invoke(_contextMock.Object).ConfigureAwait(false); // Assert and Verify fileSystemHandlerMock.Verify(f => f.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Once); _mappings.Count.Should().Be(1); } } }
// // Copyright (c) 2017 Lee P. Richardson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using Android.Content; using Android.Util; using Android.Views; using Android.Widget; using Android.OS; namespace EasyLayout.Droid { public static class EasyLayout { private enum Position { Top, Right, Left, Bottom, CenterX, CenterY, Center, Constant, Width, Height, Baseline } private struct LeftExpression { public View View { get; set; } public Position Position { get; set; } public string Name { get; set; } } private struct RightExpression { public bool IsParent { get; set; } public int? Id { get; set; } public string Name { get; set; } public Position Position { get; set; } public int? Constant { get; set; } public bool IsConstant => !IsParent && Id == null && Constant != null; } private struct Margin { public int? Right { get; set; } public int? Left { get; set; } public int? Top { get; set; } public int? Bottom { get; set; } } private class Rule { public Rule(View view) { View = view; } public View View { get; } public LayoutRules? LayoutRule { get; private set; } public int? RelativeToViewId { get; private set; } public Margin Margin { get; private set; } public int? Width { get; private set; } public int? Height { get; private set; } private void SetMargin(LeftExpression leftExpression, RightExpression rightExpression) { Margin = GetMargin(leftExpression, rightExpression); } private Margin GetMargin(LeftExpression leftExpression, RightExpression rightExpression) { if (rightExpression.Constant == null) return new Margin(); // assumes all constants are in Dp var constantPx = DpToPx(leftExpression.View.Context, rightExpression.Constant.Value); switch (leftExpression.Position) { case Position.Top: return new Margin { Top = constantPx }; case Position.Baseline: return new Margin { Top = constantPx }; case Position.Right: return new Margin { Right = -constantPx }; case Position.Bottom: return new Margin { Bottom = -constantPx }; case Position.Left: return new Margin { Left = constantPx }; case Position.Width: return new Margin(); case Position.Height: return new Margin(); case Position.CenterX: return constantPx > 0 ? new Margin {Left = constantPx} : new Margin() {Right = -constantPx}; default: throw new ArgumentException($"Constant expressions with {rightExpression.Position} are currently unsupported."); } } private void SetLayoutRule(LeftExpression leftExpression, RightExpression rightExpression) { LayoutRule = GetLayoutRule(leftExpression, rightExpression); } private static LayoutRules? GetLayoutRule(LeftExpression leftExpression, RightExpression rightExpression) { if (rightExpression.IsConstant) { return null; } if (rightExpression.IsParent) { return GetLayoutRuleForParent(leftExpression.Position, rightExpression.Position, leftExpression.Name); } return GetLayoutRuleForSibling(leftExpression.Position, rightExpression.Position, leftExpression.Name, rightExpression.Name); } private static LayoutRules GetLayoutRuleForSibling(Position leftPosition, Position rightPosition, string leftExpressionName, string rightExpressionName) { if (leftPosition == Position.Bottom && rightPosition == Position.Bottom) return LayoutRules.AlignBottom; if (leftPosition == Position.Top && rightPosition == Position.Top) return LayoutRules.AlignTop; if (leftPosition == Position.Right && rightPosition == Position.Right) return LayoutRules.AlignRight; if (leftPosition == Position.Left && rightPosition == Position.Left) return LayoutRules.AlignLeft; if (leftPosition == Position.Top && rightPosition == Position.Bottom) return LayoutRules.Below; if (leftPosition == Position.Bottom && rightPosition == Position.Top) return LayoutRules.Above; if (leftPosition == Position.Left && rightPosition == Position.Right) return LayoutRules.RightOf; if (leftPosition == Position.Right && rightPosition == Position.Left) return LayoutRules.LeftOf; if (leftPosition == Position.Baseline && rightPosition == Position.Baseline) return LayoutRules.AlignBaseline; if (leftPosition == Position.Width && rightPosition == Position.Width) throw new ArgumentException("Unfortunately Android's relative layout isn't sophisticated enough to allow constraining the width of one view to the width of another. Maybe try extracting several widths into a shared constant."); if (leftPosition == Position.Height && rightPosition == Position.Height) throw new ArgumentException("Unfortunately Android's relative layout isn't sophisticated enough to allow constraining the height of one view to the height of another. Maybe try extracting several heights into a shared constant."); throw new ArgumentException($"Unsupported relative positioning combination: {leftExpressionName}.{leftPosition} with {rightExpressionName}.{rightPosition}"); } private static int DpToPx(Context ctx, float dp) { var displayMetrics = ctx.Resources.DisplayMetrics; return (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dp, displayMetrics); } private static LayoutRules? GetLayoutRuleForParent(Position childPosition, Position parentPosition, string childName) { if (childPosition == Position.Top && parentPosition == Position.Top) return LayoutRules.AlignParentTop; if (childPosition == Position.Right && parentPosition == Position.Right) return LayoutRules.AlignParentRight; if (childPosition == Position.Bottom && parentPosition == Position.Bottom) return LayoutRules.AlignParentBottom; if (childPosition == Position.Left && parentPosition == Position.Left) return LayoutRules.AlignParentLeft; if (childPosition == Position.CenterX && parentPosition == Position.CenterX) return LayoutRules.CenterHorizontal; if (childPosition == Position.CenterY && parentPosition == Position.CenterY) return LayoutRules.CenterVertical; if (childPosition == Position.Center && parentPosition == Position.Center) return LayoutRules.CenterInParent; if (childPosition == Position.Width && parentPosition == Position.Width) return null; if (childPosition == Position.Height && parentPosition == Position.Height) return null; throw new Exception($"Unsupported parent positioning combination: {childName}.{childPosition} with parent.{parentPosition}"); } private void SetHeightWidth(LeftExpression leftExpression, RightExpression rightExpression) { if (leftExpression.Position == Position.Width && rightExpression.IsConstant && rightExpression.Constant.HasValue) Width = DpToPx(leftExpression.View.Context, rightExpression.Constant.Value); if (leftExpression.Position == Position.Height && rightExpression.IsConstant && rightExpression.Constant.HasValue) Height = DpToPx(leftExpression.View.Context, rightExpression.Constant.Value); if (leftExpression.Position == Position.Width && rightExpression.IsParent && rightExpression.Constant == null) Width = ViewGroup.LayoutParams.MatchParent; if (leftExpression.Position == Position.Height && rightExpression.IsParent && rightExpression.Constant == null) Height = ViewGroup.LayoutParams.MatchParent; } public void Initialize(LeftExpression leftExpression, RightExpression rightExpression) { if (!rightExpression.IsParent) { RelativeToViewId = rightExpression.Id; } SetMargin(leftExpression, rightExpression); SetLayoutRule(leftExpression, rightExpression); SetHeightWidth(leftExpression, rightExpression); } } private static int _idCounter = 1; public static int GetCenterX(this View view) { return 0; } public static int GetCenterY(this View view) { return 0; } public static int GetCenter(this View view) { return 0; } public static int ToConst(this int i) { return i; } public static int ToConst(this float i) { return (int)i; } public static void ConstrainLayout(this RelativeLayout relativeLayout, Expression<Func<bool>> constraints) { _idCounter = 1; var constraintExpressions = FindConstraints(constraints.Body); var viewAndRule = ConvertConstraintsToRules(relativeLayout, constraintExpressions); UpdateLayoutParamsWithRules(viewAndRule); } private static void UpdateLayoutParamsWithRules(IEnumerable<Rule> viewAndRule) { var viewsGroupedByRule = viewAndRule.GroupBy(i => i.View); foreach (var viewAndRules in viewsGroupedByRule) { var view = viewAndRules.Key; var layoutParams = GetLayoutParamsOrAddDefault(view); foreach (var rule in viewAndRules) { AddHeightWidthToLayoutParams(layoutParams, rule); AddRuleToLayoutParams(layoutParams, rule); AddMarginToLayoutParams(layoutParams, rule.Margin); } } } private static void AddHeightWidthToLayoutParams(RelativeLayout.LayoutParams layoutParams, Rule rule) { if (rule.Height != null) layoutParams.Height = rule.Height.Value; if (rule.Width != null) layoutParams.Width = rule.Width.Value; } private static IEnumerable<Rule> ConvertConstraintsToRules(RelativeLayout relativeLayout, List<BinaryExpression> constraintExpressions) { return constraintExpressions.Select(i => GetViewAndRule(i, relativeLayout)); } private static void AddMarginToLayoutParams(RelativeLayout.LayoutParams layoutParams, Margin margin) { if (margin.Right.HasValue) layoutParams.RightMargin = margin.Right.Value; if (margin.Left.HasValue) layoutParams.LeftMargin = margin.Left.Value; if (margin.Top.HasValue) layoutParams.TopMargin = margin.Top.Value; if (margin.Bottom.HasValue) layoutParams.BottomMargin = margin.Bottom.Value; } private static void AddRuleToLayoutParams(RelativeLayout.LayoutParams layoutParams, Rule rule) { if (rule.LayoutRule == null) return; if (rule.RelativeToViewId.HasValue) layoutParams.AddRule(rule.LayoutRule.Value, rule.RelativeToViewId.Value); else layoutParams.AddRule(rule.LayoutRule.Value); } private static RelativeLayout.LayoutParams GetLayoutParamsOrAddDefault(View view) { if (view.LayoutParameters == null) { view.LayoutParameters = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); } else { if (!(view.LayoutParameters is RelativeLayout.LayoutParams)) { throw new ArgumentException($"View #{view.Id} must have LayoutParameters set to either null or RelativeLayout.LayoutParams."); } } return (RelativeLayout.LayoutParams)view.LayoutParameters; } private static Rule GetViewAndRule(BinaryExpression expr, RelativeLayout relativeLayout) { var leftExpression = ParseLeftExpression(expr.Left); var rightExpression = ParseRightExpression(expr.Right, relativeLayout); return GetRule(leftExpression, rightExpression); } private static Rule GetRule(LeftExpression leftExpression, RightExpression rightExpression) { var rule = new Rule(leftExpression.View); rule.Initialize(leftExpression, rightExpression); return rule; } private static RightExpression ParseRightExpression(Expression expr, RelativeLayout relativeLayout) { Position? position = null; Expression memberExpression = null; int? constant = null; if (expr.NodeType == ExpressionType.Add || expr.NodeType == ExpressionType.Subtract) { var rb = (BinaryExpression)expr; if (IsConstant(rb.Left)) { throw new ArgumentException("Addition and substraction are only supported when there is a view on the left and a constant on the right"); } if (IsConstant(rb.Right)) { constant = ConstantValue(rb.Right); if (expr.NodeType == ExpressionType.Subtract) { constant = -constant; } expr = rb.Left; } else { throw new NotSupportedException("Addition only supports constants: " + rb.Right.NodeType); } } if (IsConstant(expr)) { position = Position.Constant; constant = ConstantValue(expr); } else { var fExpr = expr as MethodCallExpression; if (fExpr != null) { position = GetPosition(fExpr); memberExpression = fExpr.Arguments.FirstOrDefault() as MemberExpression; } } if (position == null) { var memExpr = expr as MemberExpression; if (memExpr == null) { throw new NotSupportedException("Right hand side of a relation must be a member expression, instead it is " + expr); } position = GetPosition(memExpr); memberExpression = memExpr.Expression; if (memExpr.Expression == null) { throw new NotSupportedException("Constraints should use views's Top, Bottom, etc properties, or extension methods like GetCenter()."); } } View view = GetView(memberExpression); var memberName = GetName(memberExpression); var isParent = view == relativeLayout; if (view != null && !isParent && view.Id == -1) { view.Id = GenerateViewId(); } return new RightExpression { IsParent = isParent, Id = view?.Id, Position = position.Value, Name = memberName, Constant = constant }; } private static string GetName(Expression expression) { var memberExpression = expression as MemberExpression; if (memberExpression != null) return memberExpression.Member.Name; return expression?.ToString(); } private static View GetView(Expression viewExpr) { if (viewExpr == null) return null; var eval = Eval(viewExpr); var view = eval as View; if (view == null) { throw new NotSupportedException("Constraints only apply to views."); } return view; } private static int GenerateViewId() { // API level 17+ if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1) { return View.GenerateViewId(); } return _idCounter++; } private static int ConstantValue(Expression expr) { return Convert.ToInt32(Eval(expr)); } private static bool IsConstant(Expression expr) { if (expr.NodeType == ExpressionType.Constant) { return true; } if (expr.NodeType == ExpressionType.MemberAccess) { var mexpr = (MemberExpression)expr; var m = mexpr.Member; if (m.MemberType == MemberTypes.Field) { return true; } return false; } if (expr.NodeType == ExpressionType.Convert) { var cexpr = (UnaryExpression)expr; return IsConstant(cexpr.Operand); } var methodCall = expr as MethodCallExpression; if (methodCall != null) { return methodCall.Method.Name == nameof(ToConst); } return false; } private static LeftExpression ParseLeftExpression(Expression expr) { Position? position = null; MemberExpression viewExpr = null; var fExpr = expr as MethodCallExpression; if (fExpr != null) { position = GetPosition(fExpr); viewExpr = fExpr.Arguments.FirstOrDefault() as MemberExpression; } if (position == null) { var memExpr = expr as MemberExpression; if (memExpr == null) { throw new NotSupportedException("Left hand side of a relation must be a member expression, instead it is " + expr); } position = GetPosition(memExpr); viewExpr = memExpr.Expression as MemberExpression; } if (viewExpr == null) { throw new NotSupportedException("Constraints should use views's Top, Bottom, etc properties, or extension methods like GetCenter()."); } var eval = Eval(viewExpr); var view = eval as View; if (view == null) { throw new NotSupportedException("Constraints only apply to views."); } return new LeftExpression { View = view, Position = position.Value, Name = viewExpr.Member.Name }; } private static Position GetPosition(MemberExpression memExpr) { switch (memExpr.Member.Name) { case nameof(View.Left): return Position.Left; case nameof(View.Top): return Position.Top; case nameof(View.Right): return Position.Right; case nameof(View.Bottom): return Position.Bottom; case nameof(View.Width): return Position.Width; case nameof(View.Height): return Position.Height; case nameof(View.Baseline): return Position.Baseline; default: throw new NotSupportedException("Property " + memExpr.Member.Name + " is not recognized."); } } private static Position GetPosition(MethodCallExpression fExpr) { switch (fExpr.Method.Name) { case nameof(GetCenterX): return Position.CenterX; case nameof(GetCenterY): return Position.CenterY; case nameof(GetCenter): return Position.Center; default: throw new NotSupportedException("Method " + fExpr.Method.Name + " is not recognized."); } } private static object Eval(Expression expr) { if (expr.NodeType == ExpressionType.Constant) { return ((ConstantExpression)expr).Value; } if (expr.NodeType == ExpressionType.MemberAccess) { var mexpr = (MemberExpression)expr; var m = mexpr.Member; if (m.MemberType == MemberTypes.Field) { var f = (FieldInfo)m; var v = f.GetValue(Eval(mexpr.Expression)); return v; } } if (expr.NodeType == ExpressionType.Convert) { var cexpr = (UnaryExpression)expr; var op = Eval(cexpr.Operand); if (cexpr.Method != null) { return cexpr.Method.Invoke(null, new[] { op }); } else { return Convert.ChangeType(op, cexpr.Type); } } return Expression.Lambda(expr).Compile().DynamicInvoke(); } private static List<BinaryExpression> FindConstraints(Expression expr) { var binaryExpressions = new List<BinaryExpression>(); FindConstraints(expr, binaryExpressions); return binaryExpressions; } private static void FindConstraints(Expression expr, List<BinaryExpression> constraintExprs) { var b = expr as BinaryExpression; if (b == null) { return; } if (b.NodeType == ExpressionType.AndAlso) { FindConstraints(b.Left, constraintExprs); FindConstraints(b.Right, constraintExprs); } else { constraintExprs.Add(b); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System; namespace Stratus.Gameplay { public partial class TriggerSystemEditor : StratusBehaviourEditor<StratusTriggerSystem> { //------------------------------------------------------------------------/ // Methods: Drawing //------------------------------------------------------------------------/ private void DrawConnections(Rect rect) { // First draw the options DrawOptions(rect); //if (showMessages) // DrawMessages(); // Now display the connections GUILayout.BeginVertical(EditorStyles.helpBox); { columnWidth = GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.45f); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("TRIGGERS", StratusGUIStyles.header); GUILayout.Label("TRIGGERABLES", StratusGUIStyles.header); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); { GUILayout.BeginVertical(); { //EditorGUILayout.LabelField("Triggers", EditorStyles.label); DrawTriggers(); } GUILayout.EndVertical(); //gridDrawer.Draw(GUILayoutUtility.GetLastRect(), Vector2.zero); GUILayout.BeginVertical(); { //EditorGUILayout.LabelField("Triggerables", EditorStyles.la); DrawTriggerables(); } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } //private void DrawMessages() //{ // EditorGUILayout.HelpBox("Boop", MessageType.Warning); //} private void DrawTriggers() { foreach (var trigger in target.triggers) DrawTrigger(trigger); // If any swap operations... if (!triggerSwapOperations.Empty()) { foreach (var tuple in triggerSwapOperations) triggers.Swap(tuple.Item1, tuple.Item2); triggerSwapOperations.Clear(); } } private void DrawTriggerables() { foreach (var triggerable in target.triggerables) DrawTriggerable(triggerable); // If any swap operations... if (!triggerableSwapOperations.Empty()) { foreach (var tuple in triggerableSwapOperations) triggerables.Swap(tuple.Item1, tuple.Item2); triggerableSwapOperations.Clear(); } } void DrawSelected(Rect rect) { if (selectedEditor == null) return; DrawEditor(this.selectedEditor, this.selectedName); } private void DrawOptions(Rect rect) { EditorGUILayout.BeginHorizontal(); // Add Menu if (GUILayout.Button(StratusGUIStyles.addIcon, StratusGUIStyles.smallLayout)) { var menu = new GenericMenu(); menu.AddPopup("Add Trigger", triggerTypes.displayedOptions, (int index) => { target.gameObject.AddComponent(triggerTypes.AtIndex(index)); UpdateConnections(); }); menu.AddPopup("Add Triggerable", triggerableTypes.displayedOptions, (int index) => { target.gameObject.AddComponent(triggerableTypes.AtIndex(index)); UpdateConnections(); }); menu.ShowAsContext(); } //if (GUILayout.Button(new GUIContent($"{messages.Count}", StratusGUIStyles.messageTexture), StratusGUIStyles.smallLayout)) //{ //} // Validation if (GUILayout.Button(StratusGUIStyles.validateIcon, StratusGUIStyles.smallLayout)) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Validate All"), false, ()=> Validate(ValidateAll)); menu.AddItem(new GUIContent("Validate Trigger Persistence"), false, ()=>Validate(ValidatePersistence)); menu.AddItem(new GUIContent("Validate Connections"), false, ()=>Validate(ValidateConnections)); menu.AddItem(new GUIContent("Validate Null"), false, () => Validate(ValidateNull)); menu.ShowAsContext(); } // Options Menu if (GUILayout.Button(StratusGUIStyles.optionsIcon, StratusGUIStyles.smallLayout)) { var menu = new GenericMenu(); menu.AddEnumToggle<StratusTriggerSystem.ConnectionDisplay>(propertyMap[nameof(StratusTriggerSystem.connectionDisplay)]); menu.AddBooleanToggle(propertyMap[nameof(StratusTriggerSystem.showDescriptions)]); menu.AddBooleanToggle(propertyMap[nameof(StratusTriggerSystem.outlines)]); menu.ShowAsContext(); } EditorGUILayout.EndHorizontal(); } private void DrawTrigger(StratusTriggerBehaviour trigger) { StratusTriggerSystem.ConnectionStatus status = StratusTriggerSystem.ConnectionStatus.Disconnected; if (selected) { if (selected == trigger) status = StratusTriggerSystem.ConnectionStatus.Selected; else if (selectedTriggerable && connectedTriggers.ContainsKey(trigger) && connectedTriggers[trigger]) status = StratusTriggerSystem.ConnectionStatus.Connected; } if (!IsConnected(trigger) && selected != trigger) status = StratusTriggerSystem.ConnectionStatus.Disjoint; Color color = GetColor(trigger, status); Draw(trigger, color, SelectTrigger, RemoveTrigger, SetTriggerContextMenu); } private void DrawTriggerable(StratusTriggerable triggerable) { StratusTriggerSystem.ConnectionStatus status = StratusTriggerSystem.ConnectionStatus.Disconnected; if (selected) { if (selected == triggerable) status = StratusTriggerSystem.ConnectionStatus.Selected; else if (selectedTrigger && connectedTriggerables.ContainsKey(triggerable) && connectedTriggerables[triggerable]) status = StratusTriggerSystem.ConnectionStatus.Connected; } if (!IsConnected(triggerable) && selected != triggerable) status = StratusTriggerSystem.ConnectionStatus.Disjoint; Color color = GetColor(triggerable, status); Draw(triggerable, color, SelectTriggerable, RemoveTriggerable, SetTriggerableContextMenu); } private void Draw<T>(T baseTrigger, Color backgroundColor, System.Action<T> selectFunction, System.Action<T> removeFunction, System.Action<T, GenericMenu> contextMenuSetter) where T : StratusTriggerBase { string name = baseTrigger.GetType().Name; System.Action onLeftClick = () => { selectedName = name; selected = baseTrigger; selectFunction(baseTrigger); GUI.FocusControl(string.Empty); UpdateConnections(); }; System.Action onRightClick = () => { var menu = new GenericMenu(); contextMenuSetter(baseTrigger, menu); menu.AddSeparator(""); // Enable menu.AddItem(new GUIContent(baseTrigger.enabled ? "Disable" : "Enable"), false, () => { baseTrigger.enabled = !baseTrigger.enabled; }); // Duplicate menu.AddItem(new GUIContent("Duplicate/New"), false, () => { target.gameObject.DuplicateComponent(baseTrigger, false); }); menu.AddItem(new GUIContent("Duplicate/Copy"), false, () => { target.gameObject.DuplicateComponent(baseTrigger, true); UpdateConnections(); }); //// Reset //menu.AddItem(new GUIContent("Reset"), false, () => { baseTrigger.Invoke("Reset", 0f); }); // Remove menu.AddItem(new GUIContent("Remove"), false, () => { removeFunction(baseTrigger); UpdateConnections(); }); menu.ShowAsContext(); }; System.Action onDrag = () => { }; System.Action<object> onDrop = (object other) => { if (baseTrigger is StratusTriggerBehaviour) { if (other is StratusTriggerBehaviour) triggerSwapOperations.Add(new Tuple<StratusTriggerBehaviour, StratusTriggerBehaviour>(baseTrigger as StratusTriggerBehaviour, other as StratusTriggerBehaviour)); else if (other is StratusTriggerable) Connect(baseTrigger as StratusTriggerBehaviour, other as StratusTriggerable); } else if (baseTrigger is StratusTriggerable) { if (other is StratusTriggerable) triggerableSwapOperations.Add(new Tuple<StratusTriggerable, StratusTriggerable>(baseTrigger as StratusTriggerable, other as StratusTriggerable)); else if (other is StratusTriggerBehaviour) Connect(other as StratusTriggerBehaviour, baseTrigger as StratusTriggerable); } }; Func<object, bool> onValidateDrag = (object other) => { if (other is StratusTriggerBehaviour || other is StratusTriggerable) return true; return false; }; var button = new StratusGUIObject(); button.label = baseTrigger.enabled ? name : $"<color=grey>{name}</color>"; button.description = $"<i><size={descriptionSize}>{baseTrigger.description}</size></i>"; button.showDescription = showDescriptions; button.descriptionsWithLabel = target.descriptionsWithLabel; button.tooltip = baseTrigger.description; button.onLeftClickUp = onLeftClick; button.onRightClickDown = onRightClick; button.onDrag = onDrag; button.onDrop = onDrop; button.dragDataIdentifier = "Stratus Trigger System Button"; button.dragData = baseTrigger; button.onValidateDrag = onValidateDrag; button.AddKey(KeyCode.Delete, () => { removeFunction(baseTrigger); UpdateConnections(); }); button.isSelected = selected == baseTrigger; //button.outlineColor = backgroundColor; if (target.outlines) { button.backgroundColor = Color.white; button.Draw(buttonStyle, columnWidth); StratusGUIStyles.DrawOutline(button.rect, backgroundColor, baseTrigger is StratusTriggerBehaviour ? StratusGUIStyles.Border.Right : StratusGUIStyles.Border.Left); } else { button.backgroundColor = backgroundColor; button.outlineColor = Color.black; button.Draw(buttonStyle, columnWidth); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; namespace Microsoft.Msagl.Routing.Visibility { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] internal class InteractiveTangentVisibilityGraphCalculator : AlgorithmBase { /// <summary> /// the list of obstacles /// </summary> ICollection<Polygon> polygons; /// <summary> /// From these polygons we calculate visibility edges to all other polygons /// </summary> IEnumerable<Polygon> addedPolygons; VisibilityGraph visibilityGraph; List<Diagonal> diagonals; List<Tangent> tangents; RbTree<Diagonal> activeDiagonalTree; Polygon currentPolygon; ActiveDiagonalComparerWithRay activeDiagonalComparer = new ActiveDiagonalComparerWithRay(); bool useLeftPTangents; /// <summary> /// we calculate tangents between activePolygons and between activePolygons and existingObsacles /// </summary> protected override void RunInternal() { useLeftPTangents = true; CalculateAndAddEdges(); //use another family of tangents useLeftPTangents = false; CalculateAndAddEdges(); } void CalculateAndAddEdges() { foreach (Polygon p in this.addedPolygons) { CalculateVisibleTangentsFromPolygon(p); ProgressStep(); } } private void CalculateVisibleTangentsFromPolygon(Polygon polygon) { this.currentPolygon = polygon; AllocateDataStructures(); OrganizeTangents(); InitActiveDiagonals(); Sweep(); } private void AllocateDataStructures() { tangents = new List<Tangent>(); diagonals = new List<Diagonal>(); activeDiagonalTree = new RbTree<Diagonal>(this.activeDiagonalComparer); } private void Sweep() { if (tangents.Count < 2) return; for (int i = 1; i < tangents.Count; i++) { //we processed the first element already Tangent t = tangents[i]; if (t.Diagonal != null) { if (t.Diagonal.RbNode == activeDiagonalTree.TreeMinimum()) AddVisibleEdge(t); if (t.IsHigh) RemoveDiagonalFromActiveNodes(t.Diagonal); } else { if (t.IsLow) { this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal = t.End.Point; this.InsertActiveDiagonal(new Diagonal(t, t.Comp)); if (t.Diagonal.RbNode == activeDiagonalTree.TreeMinimum()) AddVisibleEdge(t); } } #if TEST_MSAGL //List<ICurve> cs = new List<ICurve>(); //foreach (Diagonal d in this.activeDiagonalTree) { // cs.Add(new LineSegment(d.Start, d.End)); //} //foreach (Polygon p in this.polygons) // cs.Add(p.Polyline); //cs.Add(new LineSegment(t.Start.Point, t.End.Point)); //SugiyamaLayoutSettings.Show(cs.ToArray); #endif } } private void AddVisibleEdge(Tangent t) { VisibilityGraph.AddEdge(visibilityGraph.GetVertex(t.Start), visibilityGraph.GetVertex(t.End)); } /// <summary> /// this function will also add the first tangent to the visible edges if needed /// </summary> private void InitActiveDiagonals() { if (tangents.Count == 0) return; Tangent firstTangent = this.tangents[0]; Point firstTangentStart = firstTangent.Start.Point; Point firstTangentEnd = firstTangent.End.Point; foreach (Diagonal diagonal in diagonals) { if (RayIntersectDiagonal(firstTangentStart, firstTangentEnd, diagonal)) { this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal = ActiveDiagonalComparerWithRay.IntersectDiagonalWithRay(firstTangentStart, firstTangentEnd, diagonal); InsertActiveDiagonal(diagonal); } } if (firstTangent.Diagonal.RbNode == this.activeDiagonalTree.TreeMinimum()) AddVisibleEdge(firstTangent); if (firstTangent.IsLow == false) { //remove the diagonal of the top tangent from active edges Diagonal diag = firstTangent.Diagonal; RemoveDiagonalFromActiveNodes(diag); } } #if DEBUG && TEST_MSAGL [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void AddPolylinesForShow(List<ICurve> curves) { foreach (Polygon p in this.AllObstacles) curves.Add(p.Polyline); } #endif private void RemoveDiagonalFromActiveNodes(Diagonal diag) { RBNode<Diagonal> changedNode = activeDiagonalTree.DeleteSubtree(diag.RbNode); if (changedNode != null) if (changedNode.Item != null) changedNode.Item.RbNode = changedNode; diag.LeftTangent.Diagonal = null; diag.RightTangent.Diagonal = null; } private void InsertActiveDiagonal(Diagonal diagonal) { diagonal.RbNode = activeDiagonalTree.Insert(diagonal); MarkDiagonalAsActiveInTangents(diagonal); } private static void MarkDiagonalAsActiveInTangents(Diagonal diagonal) { diagonal.LeftTangent.Diagonal = diagonal; diagonal.RightTangent.Diagonal = diagonal; } static bool RayIntersectDiagonal(Point pivot, Point pointOnRay, Diagonal diagonal) { Point a = diagonal.Start; Point b = diagonal.End; return Point.GetTriangleOrientation(pivot, a, b) == TriangleOrientation.Counterclockwise && Point.GetTriangleOrientation(pivot, pointOnRay, a) != TriangleOrientation.Counterclockwise && Point.GetTriangleOrientation(pivot, pointOnRay, b) != TriangleOrientation.Clockwise; } /// <summary> /// compare tangents by measuring the counterclockwise angle between the tangent and the edge /// </summary> /// <param name="e0"></param> /// <param name="e1"></param> /// <returns></returns> int TangentComparison(Tangent e0, Tangent e1) { return StemStartPointComparer.CompareVectorsByAngleToXAxis(e0.End.Point - e0.Start.Point, e1.End.Point - e1.Start.Point); } IEnumerable<Polygon> AllObstacles { get { foreach (Polygon p in addedPolygons) yield return p; foreach (Polygon p in polygons) yield return p; } } private void OrganizeTangents() { foreach (Polygon q in AllObstacles) if (q != this.currentPolygon) ProcessPolygonQ(q); this.tangents.Sort(new Comparison<Tangent>(TangentComparison)); } private void ProcessPolygonQ(Polygon q) { TangentPair tangentPair = new TangentPair(currentPolygon, q); if (this.useLeftPTangents) tangentPair.CalculateLeftTangents(); else tangentPair.CalculateRightTangents(); Tuple<int, int> couple = useLeftPTangents ? tangentPair.leftPLeftQ : tangentPair.rightPLeftQ; Tangent t0 = new Tangent(currentPolygon[couple.Item1], q[couple.Item2]); t0.IsLow = true; t0.SeparatingPolygons = !this.useLeftPTangents; couple = useLeftPTangents ? tangentPair.leftPRightQ : tangentPair.rightPRightQ; Tangent t1 = new Tangent(currentPolygon[couple.Item1], q[couple.Item2]); t1.IsLow = false; t1.SeparatingPolygons = this.useLeftPTangents; t0.Comp = t1; t1.Comp = t0; this.tangents.Add(t0); this.tangents.Add(t1); this.diagonals.Add(new Diagonal(t0, t1)); } public InteractiveTangentVisibilityGraphCalculator(ICollection<Polygon> holes, IEnumerable<Polygon> addedPolygons, VisibilityGraph visibilityGraph) { this.polygons = holes; this.visibilityGraph = visibilityGraph; this.addedPolygons = addedPolygons; } internal delegate bool FilterVisibleEdgesDelegate(Point a, Point b); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace help.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Data.SqlClient; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swcommands; namespace ArchivePDF.csproj { class PDFArchiver { private SldWorks swApp; private ModelDoc2 swModel; private Frame swFrame; private DrawingDoc swDraw; private View swView; private CustomPropertyManager swCustPropMgr; private swDocumentTypes_e modelType = swDocumentTypes_e.swDocNONE; private String sourcePath = String.Empty; private String drawingPath = String.Empty; private int drwKey = 0; public bool IsTarget = false; public string savedFile = string.Empty; private bool metal; //private Boolean shouldCheck = true; /// <summary> /// Constructor /// </summary> /// <param name="sw">Requires a <see cref="SolidWorks.Interop.sldworks.SldWorks"/> type.</param> /// <param name="ps">Requires a <see cref="ArchivePDF.csproj.PathSet"/></param> public PDFArchiver(ref SldWorks sw, ArchivePDF.csproj.PathSet ps) { swApp = sw; APathSet = ps; swModel = (ModelDoc2)swApp.ActiveDoc; ModelDocExtension ex = (ModelDocExtension)swModel.Extension; string lvl = GetRev(ex); if (DocCheck()) { if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING) { throw new ExportPDFException("You must have a Drawing Document open."); } swDraw = (DrawingDoc)swModel; swFrame = (Frame)swApp.Frame(); swView = GetFirstView(swApp); metal = IsMetal(swView); sourcePath = swView.GetReferencedModelName().ToUpper().Trim(); drawingPath = swModel.GetPathName().ToUpper().Trim(); if (sourcePath.Contains("SLDASM")) { modelType = swDocumentTypes_e.swDocASSEMBLY; } else if (sourcePath.Contains("SLDPRT")) { modelType = swDocumentTypes_e.swDocPART; } else { modelType = swDocumentTypes_e.swDocNONE; } } else { MustSaveException e = new MustSaveException("The drawing has to be saved."); throw e; } } public View GetFirstView(SldWorks sw) { ModelDoc2 swModel = (ModelDoc2)sw.ActiveDoc; DrawingDoc d = (DrawingDoc)swModel; View v; string[] shtNames = (String[])swDraw.GetSheetNames(); string message = string.Empty; //This should find the first page with something on it. IsTarget = IsTargetDrawing((sw.ActiveDoc as DrawingDoc).Sheet[shtNames[0]]); int x = 0; do { try { d.ActivateSheet(shtNames[x]); } catch (IndexOutOfRangeException e) { throw new IndexOutOfRangeException("Went beyond the number of sheets.", e); } catch (Exception e) { throw e; } v = (View)d.GetFirstView(); v = (View)v.GetNextView(); x++; } while ((v == null) && (x < d.GetSheetCount())); message = (string)v.GetName2() + ":\n"; if (v == null) { throw new Exception("I couldn't find a model anywhere in this document."); } return v; } public void CorrectLayers(string rev, selectLayer f) { Sheet curSht = (Sheet)swDraw.GetCurrentSheet(); string[] shts = (string[])swDraw.GetSheetNames(); foreach (string s in shts) { swFrame.SetStatusBarText("Showing correct revs on " + s + "..."); swDraw.ActivateSheet(s); f(rev); } swDraw.ActivateSheet(curSht.GetName()); } public delegate void selectLayer(string rev); /// <summary> /// Selects the correct layer. /// </summary> public void chooseLayer(string rev) { char c = (char)rev[2]; int revcount = (int)c - 64; LayerMgr lm = (LayerMgr)(swApp.ActiveDoc as ModelDoc2).GetLayerManager(); string head = getLayerNameHeader(lm); for (int i = 0; i < Properties.Settings.Default.LayerTails.Count; i++) { string currentTail = Properties.Settings.Default.LayerTails[i]; try { Layer l = (Layer)lm.GetLayer(string.Format("{0}{1}", head, currentTail)); if (l != null) { l.Visible = false; if (Math.Floor((double)((revcount - 1) / 5)) == i) { l.Visible = true; } } } catch (Exception) { // Sometimes the layer doesn't exist. } } } private string getLayerNameHeader(LayerMgr lm) { foreach (string h in Properties.Settings.Default.LayerHeads) { foreach (string t in Properties.Settings.Default.LayerTails) { Layer l = (Layer)lm.GetLayer(string.Format("{0}{1}", h, t)); if (l != null && l.Visible) return h; } } return "AMS"; } private bool IsTargetDrawing(Sheet sheet) { if (sheet.GetTemplateName().ToUpper().Contains(@"TARGET_ASS")) { return true; } return false; } public bool IsMetal(View v) { ModelDoc2 md = (ModelDoc2)v.ReferencedDocument; ConfigurationManager cfMgr = md.ConfigurationManager; Configuration cf = cfMgr.ActiveConfiguration; CustomPropertyManager gcpm = md.Extension.get_CustomPropertyManager(string.Empty); CustomPropertyManager scpm; string _value = "WOOD"; string _resValue = string.Empty; bool wasResolved; bool useCached = false; if (cf != null) { scpm = cf.CustomPropertyManager; } else { scpm = gcpm; } int res; res = gcpm.Get5("DEPARTMENT", useCached, out _value, out _resValue, out wasResolved); if (_value == string.Empty) { res = gcpm.Get5("DEPTID", useCached, out _value, out _resValue, out wasResolved); if (_value == string.Empty) { res = scpm.Get5("DEPARTMENT", useCached, out _value, out _resValue, out wasResolved); } } if (_value == "2" || _value.ToUpper() == "METAL") { return true; } return false; } /// <summary> /// Exports current drawing to PDFs. /// </summary> /// <returns>Returns a <see cref="System.Boolean"/>, should you need one.</returns> public Boolean ExportPdfs() { String pdfSourceName = Path.GetFileNameWithoutExtension(drawingPath); String pdfAltPath = Path.GetDirectoryName(drawingPath).Substring(3); String fFormat = String.Empty; ModelDocExtension swModExt = swModel.Extension; String Rev = GetRev(swModExt); if (Rev.Length > 2) { //CorrectLayers(Rev, chooseLayer); chooseLayer(Rev); } List<String> pdfTarget = new List<string>(); if (!drawingPath.StartsWith(Properties.Settings.Default.SMapped.ToUpper())) { pdfTarget.Add(String.Format("{0}{1}\\{2}.PDF", APathSet.KPath, pdfAltPath, pdfSourceName)); pdfTarget.Add(String.Format("{0}{1}\\{2}{3}.PDF", APathSet.GPath, pdfAltPath, pdfSourceName, Rev)); Boolean success = SaveFiles(pdfTarget); if (metal && APathSet.WriteToDb && !_metalDrawing && find_pdf(pdfSourceName)) AlertSomeone(pdfTarget[0]); return success; } else { Boolean success = ExportMetalPdfs(); return success; } } private bool find_pdf(string doc) { string searchterm_ = string.Format(@"{0}.PDF", doc); using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connectionString)) { string sql_ = @"SELECT FileID, FName, FPath, DateCreated FROM GEN_DRAWINGS_MTL WHERE(FName = @fname)"; using (SqlCommand comm = new SqlCommand(sql_, conn)) { comm.Parameters.AddWithValue(@"@fname", searchterm_); try { if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } using (SqlDataReader reader_ = comm.ExecuteReader()) { return reader_.HasRows; } } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"I just didn't want to open the connection."); } } } } public Boolean ExportMetalPdfs() { String pdfSourceName = Path.GetFileNameWithoutExtension(drawingPath); String pdfAltPath = Path.GetDirectoryName(drawingPath).Substring(44); //String pdfAltPath = ".\\"; String fFormat = String.Empty; ModelDocExtension swModExt = swModel.Extension; List<String> pdfTarget = new List<string>(); pdfTarget.Add(String.Format("{0}{1}\\{2}.PDF", APathSet.MetalPath, pdfAltPath, pdfSourceName)); Boolean success = SaveFiles(pdfTarget); return success; } /// <summary> /// Opens and saves models referenced in the open drawing. /// </summary> /// <returns>Returns a <see cref="System.Boolean"/>, should you need one.</returns> public Boolean ExportEDrawings() { ModelDoc2 currentDoc = swModel; string docName = currentDoc.GetPathName(); String sourceName = Path.GetFileNameWithoutExtension(docName); String altPath = Path.GetDirectoryName(docName).Substring(3); ModelDocExtension swModExt = swModel.Extension; String Rev = GetRev(swModExt); String fFormat = String.Empty; List<string> ml = get_list_of_open_docs(); List<String> EdrwTarget = new List<string>(); List<String> STEPTarget = new List<string>(); Boolean measurable = true; Int32 options = 0; Int32 errors = 0; switch (modelType) { case swDocumentTypes_e.swDocASSEMBLY: fFormat = ".EASM"; break; case swDocumentTypes_e.swDocPART: fFormat = ".EPRT"; break; default: ExportPDFException e = new ExportPDFException("Document type error."); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); throw e; } swApp.ActivateDoc3(sourcePath, true, options, ref errors); swModel = (ModelDoc2)swApp.ActiveDoc; Configuration swConfig = (Configuration)swModel.GetActiveConfiguration(); swFrame.SetStatusBarText("Positioning model."); swModel.ShowNamedView2("*Dimetric", 9); swModel.ViewZoomtofit2(); if (!swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swEDrawingsOkayToMeasure)) { swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swEDrawingsOkayToMeasure, true); measurable = false; } else { measurable = true; } EdrwTarget.Add(String.Format("{0}{1}\\{2}{3}", APathSet.KPath, altPath, sourceName, fFormat)); EdrwTarget.Add(String.Format("{0}{1}\\{2}{3}{4}", APathSet.GPath, altPath, sourceName, Rev, fFormat)); if (APathSet.ExportSTEP) { STEPTarget.Add(String.Format("{0}{1}\\{2}{3}", APathSet.KPath, altPath, sourceName, @".STEP")); STEPTarget.Add(String.Format("{0}{1}\\{2}{3}{4}", APathSet.GPath, altPath, sourceName, Rev, @".STEP")); } Boolean success = SaveSTEPorEDrw(EdrwTarget); if (STEPTarget.Count > 0) { success = SaveSTEPorEDrw(STEPTarget); } if (!measurable) swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swEDrawingsOkayToMeasure, false); if (!ml.Contains(swModel.GetPathName())) { swFrame.SetStatusBarText("Closing model."); swApp.CloseDoc(sourcePath); } else if (APathSet.SaveFirst) { swModel.SaveSilent(); } int err = 0; swApp.ActivateDoc3(currentDoc.GetTitle(), true, (int)swRebuildOnActivation_e.swDontRebuildActiveDoc, ref err); return success; } private bool SaveSTEPorEDrw(List<string> fl) { if (fl.Count < 1) { return false; } int saveVersion = (int)swSaveAsVersion_e.swSaveAsCurrentVersion; int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent; int refErrors = 0; int refWarnings = 0; bool success = true; string tmpPath = Path.GetTempPath(); ModelDocExtension swModExt = default(ModelDocExtension); ExportPdfData swExportPDFData = default(ExportPdfData); string fileName = fl[0]; FileInfo fi = new FileInfo(fileName); string tmpFile = tmpPath + "\\" + fi.Name; swModExt = swModel.Extension; bool stepconf = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData); bool stepedgeprop = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps); bool stepsplit = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic); bool stepcurve = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures); int stepAP = swApp.GetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures, false); swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 203); swFrame.SetStatusBarText(String.Format("Exporting '{0}'", fileName)); success = swModExt.SaveAs(tmpFile, saveVersion, saveOptions, swExportPDFData, ref refErrors, ref refWarnings); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData, stepconf); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps, stepedgeprop); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic, stepsplit); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures, stepcurve); swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, stepAP); foreach (string fn in fl) { CopyFile(tmpFile, fn); } if (fl[0].EndsWith(@"EPRT") || fl[0].EndsWith(@"EASM")) { InsertIntoDb(fl[0], Properties.Settings.Default.eDrawingTable); } return success; } private bool CopyFile(string tmpFile, string fileName) { try { File.Copy(tmpFile, fileName, true); } catch (UnauthorizedAccessException uae) { throw new ExportPDFException( String.Format("You don't have the reqired permission to access '{0}'.", fileName), uae); } catch (ArgumentException ae) { throw new ExportPDFException( String.Format("Either '{0}' or '{1}' is not a proper file name.", tmpFile, fileName), ae); } catch (PathTooLongException ptle) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is too long.", tmpFile, fileName), ptle); } catch (DirectoryNotFoundException dnfe) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is invalid.", tmpFile, fileName), dnfe); } catch (FileNotFoundException fnfe) { throw new ExportPDFException( String.Format("Crap! I lost '{0}'!", tmpFile), fnfe); } catch (IOException) { System.Windows.Forms.MessageBox.Show( String.Format("If you have the file, '{0}', selected in an Explorer window, " + "you may have to close it.", fileName), "This file is open somewhere.", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return false; } catch (NotSupportedException nse) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is an invalid format.", tmpFile, fileName), nse); } return true; } /// <summary> /// This thing does the saving. /// </summary> /// <param name="fl">A <see cref="System.Collections.Generic.List<>"/> of destination paths.</param> /// <returns>Returns a <see cref="System.Boolean"/>, indicating success.</returns> private Boolean SaveFiles(List<String> fl) { Int32 saveVersion = (Int32)swSaveAsVersion_e.swSaveAsCurrentVersion; Int32 saveOptions = (Int32)swSaveAsOptions_e.swSaveAsOptions_Silent; Int32 refErrors = 0; Int32 refWarnings = 0; Boolean success = true; string tmpPath = Path.GetTempPath(); ModelDocExtension swModExt = default(ModelDocExtension); ExportPdfData swExportPDFData = default(ExportPdfData); foreach (String fileName in fl) { FileInfo fi = new FileInfo(fileName); string tmpFile = tmpPath + "\\" + fi.Name; if (drawingPath != String.Empty) { swFrame.SetStatusBarText(String.Format("Checking path: '{0}'", fileName)); if (!CreatePath(fileName)) { ExportPDFException e = new ExportPDFException("Unable to save file, folder could not be created."); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); throw e; } String[] obj = (string[])swDraw.GetSheetNames(); object[] objs = new object[obj.Length - 1]; DispatchWrapper[] dr = new DispatchWrapper[obj.Length - 1]; for (int i = 0; i < obj.Length - 1; i++) { swDraw.ActivateSheet(obj[i]); Sheet s = (Sheet)swDraw.GetCurrentSheet(); objs[i] = s; dr[i] = new DispatchWrapper(objs[i]); } swFrame.SetStatusBarText(String.Format("Exporting '{0}'", fileName)); bool layerPrint = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, true); swExportPDFData = swApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData); swModExt = swModel.Extension; success = swExportPDFData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, (dr)); success = swModExt.SaveAs(tmpFile, saveVersion, saveOptions, swExportPDFData, ref refErrors, ref refWarnings); //success = swModel.SaveAs4(tmpFile, saveVersion, saveOptions, ref refErrors, ref refWarnings); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, layerPrint); try { File.Copy(tmpFile, fileName, true); } catch (UnauthorizedAccessException uae) { throw new ExportPDFException( String.Format("You don't have the reqired permission to access '{0}'.", fileName), uae); } catch (ArgumentException ae) { throw new ExportPDFException( String.Format("Either '{0}' or '{1}' is not a proper file name.", tmpFile, fileName), ae); } catch (PathTooLongException ptle) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is too long.", tmpFile, fileName), ptle); } catch (DirectoryNotFoundException dnfe) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is invalid.", tmpFile, fileName), dnfe); } catch (FileNotFoundException fnfe) { throw new ExportPDFException( String.Format("Crap! I lost '{0}'!", tmpFile), fnfe); } catch (IOException) { System.Windows.Forms.MessageBox.Show( String.Format("If you have the file, '{0}', selected in an Explorer window, " + "you may have to close it.", fileName), "This file is open somewhere.", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return false; } catch (NotSupportedException nse) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is an invalid format.", tmpFile, fileName), nse); } if (!File.Exists(fileName)) success = false; if (success) { swFrame.SetStatusBarText(String.Format("Exported '{0}'", fileName)); if (fileName.StartsWith(Properties.Settings.Default.KPath) && APathSet.WriteToDb) { savedFile = fileName; if (fileName.EndsWith("PDF")) { InsertIntoDb(fileName, Properties.Settings.Default.PDFTable); drwKey = GetKeyCol(fi.Name); } if (fileName.EndsWith(@"EPRT") || fileName.EndsWith("EASM")) { InsertIntoDb(fileName, Properties.Settings.Default.eDrawingTable); } } if ((fileName.StartsWith(Properties.Settings.Default.MetalPath) && fileName.EndsWith("PDF")) && APathSet.WriteToDb) { _metalDrawing = true; InsertIntoDb(fileName, Properties.Settings.Default.metalTable); drwKey = GetKeyCol(fi.Name); } } else { ExportPDFException e = new ExportPDFException(String.Format("Failed to save '{0}'", fileName)); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); throw e; } } } if (success) return true; else return false; } private String GetRev(ModelDocExtension swModExt) { swCustPropMgr = (CustomPropertyManager)swModExt.get_CustomPropertyManager(""); String[] propNames = (String[])swCustPropMgr.GetNames(); String ValOut = String.Empty; String ResolvedValOut = String.Empty; Boolean WasResolved = false; String result = String.Empty; foreach (String name in propNames) { swCustPropMgr.Get5(name, false, out ValOut, out ResolvedValOut, out WasResolved); if (name.Contains("REVISION") && !name.Contains(@"LEVEL") && ValOut != String.Empty) result = "-" + ValOut; } if (result.Length != 3) { MustHaveRevException e = new MustHaveRevException("Check to make sure drawing is at least revision AA or later."); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); //e.Data.Add("result", result); throw e; } //System.Diagnostics.Debug.Print(result); return result; } private Boolean DocCheck() { if (swModel == null) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return false; } else if ((Int32)swModel.GetType() != (Int32)swDocumentTypes_e.swDocDRAWING) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return false; } else if (swModel.GetPathName() == String.Empty) { swModel.Extension.RunCommand((int)swCommands_e.swCommands_SaveAs, swModel.GetTitle()); if (swModel.GetPathName() == string.Empty) return false; return true; } else return true; } private Boolean CreatePath(String pathCheck) { pathCheck = Path.GetDirectoryName(pathCheck); String targetpath = String.Empty; if (!Directory.Exists(pathCheck)) { String msg = String.Format("'{0}' does not exist. Do you wish to create this folder?", pathCheck); System.Windows.Forms.MessageBoxButtons mbb = System.Windows.Forms.MessageBoxButtons.YesNo; System.Windows.Forms.MessageBoxIcon mbi = System.Windows.Forms.MessageBoxIcon.Question; System.Windows.Forms.DialogResult dr = System.Windows.Forms.MessageBox.Show(msg, "New folder", mbb, mbi); if (dr == System.Windows.Forms.DialogResult.Yes) { DirectoryInfo di = Directory.CreateDirectory(pathCheck); return di.Exists; } else return false; } return true; } private ArchivePDF.csproj.PathSet _ps; public ArchivePDF.csproj.PathSet APathSet { get { return _ps; } set { _ps = value; } } public bool drawing_is_open(string m) { return get_list_of_open_docs().Contains(m); } public List<string> get_list_of_open_docs() { ModelDoc2 temp = (ModelDoc2)swApp.GetFirstDocument(); List<string> ml = new List<string>(); temp.GetNext(); while (temp != null) { string temp_string = temp.GetPathName(); if (temp.Visible == true && !ml.Contains(temp_string)) { ml.Add(temp.GetPathName()); } temp = (ModelDoc2)temp.GetNext(); } return ml; } public static void _sendErrMessage(Exception e, SldWorks sw) { String msg = String.Empty; msg = String.Format("{0} threw error:\n{1}", e.TargetSite, e.Message); msg += String.Format("\n\nStack trace:\n{0}", e.StackTrace); if (e.Data.Count > 0) { msg += "\n\nData:\n"; foreach (System.Collections.DictionaryEntry de in e.Data) { msg += String.Format("{0}: {1}\n", de.Key, de.Value); } } sw.SendMsgToUser2(msg, (Int32)swMessageBoxIcon_e.swMbInformation, (Int32)swMessageBoxBtn_e.swMbOk); } protected virtual bool FileIsInUse(string fileName) { FileInfo file = new FileInfo(fileName); FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } return false; } private bool DoInsert(string fileName, string table) { FileInfo fi = new FileInfo(fileName); SqlConnection connection = new SqlConnection(Properties.Settings.Default.connectionString); int insRes = 0; try { connection.Open(); } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"The connection is already open, or information is missing from the connection string: '" + Properties.Settings.Default.connectionString + "'.", ioe); } catch (SqlException se) { throw new ExportPDFException(@"A connection-level error occurred while opening the connection, whatever that means.", se); } catch (Exception e) { throw new ExportPDFException(@"Whoops. There's a problem", e); } try { string sql = String.Format(@"UPDATE {0} SET {1} = @fpath, DateCreated = @fdate WHERE ((({0}.{2}) = @filename))", table, Properties.Settings.Default.fullpath, Properties.Settings.Default.basename, fi.Name); swFrame.SetStatusBarText(sql.Replace(@"@filename", "\"" + fi.Name + "\"")); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@fpath", fi.DirectoryName .Replace(Properties.Settings.Default.KPath, Properties.Settings.Default.KMapped) .Replace(Properties.Settings.Default.MetalPath, Properties.Settings.Default.SMapped) + @"\"); command.Parameters.AddWithValue("@fdate", DateTime.Now); command.Parameters.AddWithValue("@filename", fi.Name.ToUpper()); int aff = command.ExecuteNonQuery(); if (aff > 0) { return true; } else { sql = String.Format(@"INSERT INTO {0} ({1}, {2}, {3}) VALUES (@fname, @pname, @date);", table, Properties.Settings.Default.basename, Properties.Settings.Default.fullpath, Properties.Settings.Default.datecreated); swFrame.SetStatusBarText(sql); command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@fname", fi.Name); command.Parameters.AddWithValue("@pname", fi.DirectoryName .Replace(Properties.Settings.Default.KPath, Properties.Settings.Default.KMapped) .Replace(Properties.Settings.Default.MetalPath, Properties.Settings.Default.SMapped) + @"\"); command.Parameters.AddWithValue("@date", DateTime.Now); insRes = command.ExecuteNonQuery(); } } catch (InvalidCastException ice) { throw new ExportPDFException("Invalid cast exception.", ice); } catch (SqlException se) { throw new ExportPDFException(String.Format("Couldn't execute query: {0}", se)); } catch (IOException ie) { throw new ExportPDFException("IO exception", ie); } catch (InvalidOperationException ioe) { throw new ExportPDFException("The SqlConnection closed or dropped during a streaming operation.", ioe); } catch (Exception e) { throw new ExportPDFException("I looked for the connection, but it was gone.", e); } finally { connection.Close(); } if (insRes > 0) return true; else return false; } private void InsertIntoDb(string fileName, string table) { FileInfo fi = new FileInfo(fileName); string oldPath = ExistingPath(fi.FullName, table); string newPath = fi.DirectoryName .Replace(Properties.Settings.Default.KPath, Properties.Settings.Default.KMapped) .Replace(Properties.Settings.Default.MetalPath, Properties.Settings.Default.SMapped) + @"\"; if (oldPath != string.Empty && oldPath != newPath) { string message = string.Format("Original path was '{0}'\n\nUpdate to '{1}\\'?", oldPath, fi.DirectoryName .Replace(Properties.Settings.Default.KPath, Properties.Settings.Default.KMapped) .Replace(Properties.Settings.Default.MetalPath, Properties.Settings.Default.SMapped)); swMessageBoxResult_e mbRes = (swMessageBoxResult_e)swApp.SendMsgToUser2(message, (int)swMessageBoxIcon_e.swMbQuestion, (int)swMessageBoxBtn_e.swMbOkCancel); if (mbRes == swMessageBoxResult_e.swMbHitOk) { DoInsert(fileName, table); } } else { DoInsert(fileName, table); } } private int GetKeyCol(string pathlessFilename) { SqlConnection connection = new SqlConnection(Properties.Settings.Default.connectionString); int alertKeyCol = 0; try { connection.Open(); } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"The connection is already open, or information is missing from the connection string: '" + Properties.Settings.Default.connectionString + "'.", ioe); } catch (SqlException se) { throw new ExportPDFException(@"A connection-level error occurred while opening the connection, whatever that means.", se); } catch (Exception e) { throw new ExportPDFException(@"Whoops. There's a problem", e); } try { SqlCommand comm = new SqlCommand("SELECT FileID " + string.Format("FROM {0} ", Properties.Settings.Default.PDFTable) + "WHERE FName COLLATE Latin1_General_CI_AI LIKE @fname " + "ORDER BY DateCreated DESC", connection); comm.Parameters.AddWithValue("@fname", pathlessFilename); SqlDataReader dr = comm.ExecuteReader(System.Data.CommandBehavior.SingleResult); if (dr.Read()) { alertKeyCol = dr.GetInt32(0); } } catch (Exception e) { throw e; } finally { connection.Close(); } return alertKeyCol; } private string ExistingPath(string path, string table) { string res = string.Empty; FileInfo fi = new FileInfo(path); SqlConnection connection = new SqlConnection(Properties.Settings.Default.connectionString); try { connection.Open(); } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"The connection is already open, or information is missing from the connection string: '" + Properties.Settings.Default.connectionString + "'.", ioe); } catch (SqlException se) { throw new ExportPDFException(@"A connection-level error occurred while opening the connection, whatever that means.", se); } catch (Exception e) { throw new ExportPDFException(@"Whoops. There's a problem", e); } try { string sql = string.Format("SELECT * FROM {0} WHERE FName = @fname", table); SqlCommand command = new SqlCommand(sql, connection); command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@fname", new FileInfo(path).Name); using (SqlDataReader dr = command.ExecuteReader()) { if (dr.Read()) { res = dr.GetString(2); } } } catch (InvalidCastException ice) { throw new ExportPDFException("Invalid cast exception.", ice); } catch (SqlException se) { throw new ExportPDFException(String.Format("Couldn't execute query: {0}", se)); } catch (IOException ie) { throw new ExportPDFException("IO exception", ie); } catch (InvalidOperationException ioe) { throw new ExportPDFException("The SqlConnection closed or dropped during a streaming operation.", ioe); } catch (Exception e) { throw new ExportPDFException("I looked for the connection, but it was gone.", e); } finally { connection.Close(); } return res; } private bool UncheckedAlertExists(string path) { bool res = false; FileInfo fi = new FileInfo(path); SqlConnection connection = new SqlConnection(Properties.Settings.Default.connectionString); try { connection.Open(); } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"The connection is already open, or information is missing from the connection string: '" + Properties.Settings.Default.connectionString + "'.", ioe); } catch (SqlException se) { throw new ExportPDFException(@"A connection-level error occurred while opening the connection, whatever that means.", se); } catch (Exception e) { throw new ExportPDFException(@"Whoops. There's a problem", e); } try { string sql = "SELECT * FROM dbo.GEN_ALERTS WHERE ALERTDESC = @fname AND ALERTCHK = 0"; SqlCommand command = new SqlCommand(sql, connection); command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@fname", new FileInfo(path).Name); using (SqlDataReader dr = command.ExecuteReader()) { if (dr.Read()) { res = true; } } } catch (InvalidCastException ice) { throw new ExportPDFException("Invalid cast exception.", ice); } catch (SqlException se) { throw new ExportPDFException(String.Format("Couldn't execute query: {0}", se)); } catch (IOException ie) { throw new ExportPDFException("IO exception", ie); } catch (InvalidOperationException ioe) { throw new ExportPDFException("The SqlConnection closed or dropped during a streaming operation.", ioe); } catch (Exception e) { throw new ExportPDFException("I looked for the connection, but it was gone.", e); } finally { connection.Close(); } return res; } private void AlertSomeone(string path) { FileInfo fi = new FileInfo(path); SqlConnection connection = new SqlConnection(Properties.Settings.Default.connectionString); int insRes; bool uncheckedExists = UncheckedAlertExists(path); if (uncheckedExists) { return; } if (drwKey == 0) return; try { connection.Open(); } catch (InvalidOperationException ioe) { throw new ExportPDFException(@"The connection is already open, or information is missing from the connection string: '" + Properties.Settings.Default.connectionString + "'.", ioe); } catch (SqlException se) { throw new ExportPDFException(@"A connection-level error occurred while opening the connection, whatever that means.", se); } catch (Exception e) { throw new ExportPDFException(@"Whoops. There's a problem", e); } try { string sql = string.Empty; SqlCommand command = new SqlCommand(); sql = @"INSERT INTO dbo.GEN_ALERTS (ALERTTYPE, ALERTDESC, ALERTMSG, ALERTKEYCOL) VALUES (@atype, @adesc, @amsg, @akc);"; command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@atype", 1); command.Parameters.AddWithValue("@adesc", fi.Name); command.Parameters.AddWithValue("@amsg", string.Format("Updated by {0}.", System.Environment.UserName)); command.Parameters.AddWithValue("@akc", drwKey); insRes = command.ExecuteNonQuery(); //else { // sql = @"UPDATE dbo.GEN_ALERTS SET ALERTDATE = @aDate, ALERTMSG = @amsg WHERE ALERTDESC = @fname;"; // command = new SqlCommand(sql, connection); // command.Parameters.AddWithValue("@aDate", DateTime.Now); // command.Parameters.AddWithValue("@amsg", string.Format("Updated by {0}.", System.Environment.UserName)); // command.Parameters.AddWithValue("@fname", fi.Name); // insRes = command.ExecuteNonQuery(); //} } catch (InvalidCastException ice) { throw new ExportPDFException("Invalid cast exception.", ice); } catch (SqlException se) { throw new ExportPDFException(String.Format("Couldn't execute query: {0}", se)); } catch (IOException ie) { throw new ExportPDFException("IO exception", ie); } catch (InvalidOperationException ioe) { throw new ExportPDFException("The SqlConnection closed or dropped during a streaming operation.", ioe); } catch (Exception e) { throw new ExportPDFException("I looked for the connection, but it was gone.", e); } finally { connection.Close(); } } private bool _metalDrawing = false; /// <summary> /// Is this a metal drawing? This will be figured out after a pdf is archived. /// </summary> public bool MetalDrawing { get { return _metalDrawing; } set { _metalDrawing = value; } } } }
// // System.Web.UI.TemplateControl.cs // // Authors: // Duncan Mak ([email protected]) // Gonzalo Paniagua Javier ([email protected]) // Andreas Nahr ([email protected]) // // (C) 2002 Ximian, Inc. (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Web; using System.Web.Compilation; using System.Web.Util; namespace System.Web.UI { public abstract class TemplateControl : Control, INamingContainer { static object abortTransaction = new object (); static object commitTransaction = new object (); static object error = new object (); static string [] methodNames = { "Page_Init", "Page_Load", "Page_DataBind", "Page_PreRender", "Page_Disposed", "Page_Error", "Page_Unload", "Page_AbortTransaction", "Page_CommitTransaction" }; const BindingFlags bflags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; #region Constructor protected TemplateControl () { Construct (); } #endregion #region Properties [EditorBrowsable (EditorBrowsableState.Never)] protected virtual int AutoHandlers { get { return 0; } set { } } [EditorBrowsable (EditorBrowsableState.Never)] protected virtual bool SupportAutoEvents { get { return true; } } #endregion #region Methods protected virtual void Construct () { } [MonoTODO] protected LiteralControl CreateResourceBasedLiteralControl (int offset, int size, bool fAsciiOnly) { return null; } internal void WireupAutomaticEvents () { if (!SupportAutoEvents || !AutoEventWireup) return; Type type = GetType (); foreach (string methodName in methodNames) { MethodInfo method = type.GetMethod (methodName, bflags); if (method == null) continue; if (method.DeclaringType != type) { if (!method.IsPublic && !method.IsFamilyOrAssembly && !method.IsFamilyAndAssembly && !method.IsFamily) continue; } if (method.ReturnType != typeof (void)) continue; ParameterInfo [] parms = method.GetParameters (); int length = parms.Length; bool noParams = (length == 0); if (!noParams && (length != 2 || parms [0].ParameterType != typeof (object) || parms [1].ParameterType != typeof (EventArgs))) continue; int pos = methodName.IndexOf ("_"); string eventName = methodName.Substring (pos + 1); EventInfo evt = type.GetEvent (eventName); if (evt == null) { /* This should never happen */ continue; } if (noParams) { NoParamsInvoker npi = new NoParamsInvoker (this, methodName); evt.AddEventHandler (this, npi.FakeDelegate); } else { evt.AddEventHandler (this, Delegate.CreateDelegate ( typeof (EventHandler), this, methodName)); } } } [EditorBrowsable (EditorBrowsableState.Never)] protected virtual void FrameworkInitialize () { } Type GetTypeFromControlPath (string virtualPath) { if (virtualPath == null) throw new ArgumentNullException ("virtualPath"); string vpath = UrlUtils.Combine (TemplateSourceDirectory, virtualPath); string realpath = Context.Request.MapPath (vpath); return UserControlParser.GetCompiledType (vpath, realpath, Context); } public Control LoadControl (string virtualPath) { object control = Activator.CreateInstance (GetTypeFromControlPath (virtualPath)); if (control is UserControl) ((UserControl) control).InitializeAsUserControl (Page); return (Control) control; } public ITemplate LoadTemplate (string virtualPath) { Type t = GetTypeFromControlPath (virtualPath); return new SimpleTemplate (t); } protected virtual void OnAbortTransaction (EventArgs e) { EventHandler eh = Events [abortTransaction] as EventHandler; if (eh != null) eh (this, e); } protected virtual void OnCommitTransaction (EventArgs e) { EventHandler eh = Events [commitTransaction] as EventHandler; if (eh != null) eh (this, e); } protected virtual void OnError (EventArgs e) { EventHandler eh = Events [error] as EventHandler; if (eh != null) eh (this, e); } [MonoTODO] public Control ParseControl (string content) { return null; } [MonoTODO] [EditorBrowsable (EditorBrowsableState.Never)] public static object ReadStringResource (Type t) { return null; } [MonoTODO] [EditorBrowsable (EditorBrowsableState.Never)] protected void SetStringResourcePointer (object stringResourcePointer, int maxResourceOffset) { } [MonoTODO] [EditorBrowsable (EditorBrowsableState.Never)] protected void WriteUTF8ResourceString (HtmlTextWriter output, int offset, int size, bool fAsciiOnly) { } #endregion #region Events [WebSysDescription ("Raised when the user aborts a transaction.")] public event EventHandler AbortTransaction { add { Events.AddHandler (abortTransaction, value); } remove { Events.RemoveHandler (abortTransaction, value); } } [WebSysDescription ("Raised when the user initiates a transaction.")] public event EventHandler CommitTransaction { add { Events.AddHandler (commitTransaction, value); } remove { Events.RemoveHandler (commitTransaction, value); } } [WebSysDescription ("Raised when an exception occurs that cannot be handled.")] public event EventHandler Error { add { Events.AddHandler (error, value); } remove { Events.RemoveHandler (error, value); } } #endregion class SimpleTemplate : ITemplate { Type type; public SimpleTemplate (Type type) { this.type = type; } public void InstantiateIn (Control control) { Control template = Activator.CreateInstance (type) as Control; template.SetBindingContainer (false); control.Controls.Add (template); } } #if NET_2_0 Stack dataItemCtx; internal void PushDataItemContext (object o) { if (dataItemCtx == null) dataItemCtx = new Stack (); dataItemCtx.Push (o); } internal void PopDataItemContext () { if (dataItemCtx == null) throw new InvalidOperationException (); dataItemCtx.Pop (); } internal object CurrentDataItem { get { if (dataItemCtx == null || dataItemCtx.Count == 0) throw new InvalidOperationException ("No data item"); return dataItemCtx.Peek (); } } protected object Eval (string expression) { return DataBinder.Eval (CurrentDataItem, expression); } protected object Eval (string expression, string format) { return DataBinder.Eval (CurrentDataItem, expression, format); } protected object XPath (string xpathexpression) { return XPathBinder.Eval (CurrentDataItem, xpathexpression); } protected object XPath (string xpathexpression, string format) { return XPathBinder.Eval (CurrentDataItem, xpathexpression, format); } protected IEnumerable XPathSelect (string xpathexpression) { return XPathBinder.Select (CurrentDataItem, xpathexpression); } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using Moq; using NuGet.Test.Mocks; using Xunit; using Xunit.Extensions; namespace NuGet.Test { public class PackageSourceProviderTest { [Fact] public void LoadPackageSourcesWhereAMigratedSourceIsAlsoADefaultSource() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("AOld", "urlA", false), new SettingValue("userDefinedSource", "userDefinedSourceUrl", false) }); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var defaultPackageSourceA = new PackageSource("urlA", "ANew"); var defaultPackageSourceB = new PackageSource("urlB", "B"); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new[] { defaultPackageSourceA, defaultPackageSourceB }, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("urlA", "AOld"), defaultPackageSourceA }, }); // Act var values = provider.LoadPackageSources().ToList(); // Assert // Package Source AOld will be migrated to ANew. B will simply get added // Since default source B got added when there are other package sources it will be disabled // However, package source ANew must stay enabled // PackageSource userDefinedSource is a user package source and is untouched Assert.Equal(3, values.Count); Assert.Equal("urlA", values[0].Source); Assert.Equal("ANew", values[0].Name); Assert.True(values[0].IsEnabled); Assert.Equal("userDefinedSourceUrl", values[1].Source); Assert.Equal("userDefinedSource", values[1].Name); Assert.True(values[1].IsEnabled); Assert.Equal("urlB", values[2].Source); Assert.Equal("B", values[2].Name); Assert.False(values[2].IsEnabled); // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); } [Fact] public void TestNoPackageSourcesAreReturnedIfUserSettingsIsEmpty() { // Arrange var provider = CreatePackageSourceProvider(); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(0, values.Count); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsNull() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new PackageSource[] { }); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsDefaultSourcesIfSpecified() { // Arrange var settings = new Mock<ISettings>().Object; var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("A"), new PackageSource("B") }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("A", values.First().Source); Assert.Equal("B", values.Last().Source); } [Fact] public void LoadPackageSourcesPerformMigrationIfSpecified() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)).Returns( new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false), } ); // disable package "three" settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("three", "true" ) }); IList<KeyValuePair<string, string>> savedSettingValues = null; settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback<string, IList<KeyValuePair<string, string>>>((_, savedVals) => { savedSettingValues = savedVals; }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, null, new Dictionary<PackageSource, PackageSource> { { new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") }, { new PackageSource("foo", "bar"), new PackageSource("foo", "bar") }, { new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") } } ); // Act var values = provider.LoadPackageSources().ToList(); savedSettingValues = savedSettingValues.ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "good", "goodsource", true); AssertPackageSource(values[1], "two", "twosource", true); AssertPackageSource(values[2], "awesome", "awesomesource", false); Assert.Equal(3, savedSettingValues.Count); Assert.Equal("good", savedSettingValues[0].Key); Assert.Equal("goodsource", savedSettingValues[0].Value); Assert.Equal("two", savedSettingValues[1].Key); Assert.Equal("twosource", savedSettingValues[1].Value); Assert.Equal("awesome", savedSettingValues[2].Key); Assert.Equal("awesomesource", savedSettingValues[2].Value); } [Fact] public void CallSaveMethodAndLoadMethodShouldReturnTheSamePackageSet() { // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); provider.SavePackageSources(sources); // Assert settings.Verify(); Assert.Equal(3, sources.Count); for (int i = 0; i < sources.Count; i++) { AssertPackageSource(expectedSources[i], sources[i].Name, sources[i].Source, true); } } [Fact] public void WithMachineWideSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", true), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that only sources "two" and "three" are passed. // the machine wide source "one" is not. Assert.Equal(2, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("two", values[0].Value); Assert.Equal("three", values[1].Key); Assert.Equal("three", values[1].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that the machine wide source "one" is passed here // since it is disabled. Assert.Equal(1, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("true", values[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); // disable the machine wide source "one", and save the result in provider. Assert.Equal("one", sources[2].Name); sources[2].IsEnabled = false; provider.SavePackageSources(sources); // Assert // all assertions are done inside Callback()'s } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", true), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "three", "threesource", true); AssertPackageSource(values[2], "one", "onesource", true, true); } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettingsWhenSomePackageSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("two", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "one", "onesource", true); AssertPackageSource(values[1], "two", "twosource", false); AssertPackageSource(values[2], "three", "threesource", true); } /// <summary> /// The following test tests case 1 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 1. Default Package Source is already present matching both feed source and the feed name /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameAndSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false)}); // Disable package source one settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("one", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='one' value='onesource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'one' represents case 1. No real change takes place. IsOfficial will become true though. IsEnabled remains false as it is ISettings AssertPackageSource(values.First(), "one", "onesource", false, false, true); } /// <summary> /// The following test tests case 2 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 2. Default Package Source is already present matching feed source but with a different feed name. DO NOTHING /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInSourceButNotInName() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("two", "twosource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='twodefault' value='twosource' /> </packageSources> <disabledPackageSources> <add key='twodefault' value='true' /> </disabledPackageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'two' represents case 2. No Change effected. The existing feed will not be official AssertPackageSource(values.First(), "two", "twosource", true, false, false); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 3. Default Package Source is not present, but there is another feed source with the same feed name. Override that feed entirely /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameButNotInSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='three' value='threedefaultsource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'three' represents case 3. Completely overwritten. Noticeably, Feed Source will match Configuration Default settings AssertPackageSource(values.First(), "three", "threedefaultsource", true, false, true); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 4. Default Package Source is not present, simply, add it /// </summary> [Fact] public void LoadPackageSourcesWhereNoLoadedSourceMatchesADefaultSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>()); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='four' value='foursource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'four' represents case 4. Simply Added to the list increasing the count by 1. ISettings only has 3 package sources. But, LoadPackageSources returns 4 AssertPackageSource(values.First(), "four", "foursource", true, false, true); } [Fact] public void LoadPackageSourcesDoesNotReturnProviderDefaultsWhenConfigurationDefaultPackageSourcesIsNotEmpty() { // Arrange var settings = new Mock<ISettings>().Object; string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='configurationDefaultOne' value='configurationDefaultOneSource' /> <add key='configurationDefaultTwo' value='configurationDefaultTwoSource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("providerDefaultA"), new PackageSource("providerDefaultB") }, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(2, values.Count()); Assert.Equal("configurationDefaultOneSource", values.First().Source); Assert.Equal("configurationDefaultTwoSource", values.Last().Source); } [Fact] public void LoadPackageSourcesAddsAConfigurationDefaultBackEvenAfterMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='NuGet official package source' value='https://nuget.org/api/v2' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); Assert.Equal("NuGet official package source", values[1].Name); Assert.Equal("https://nuget.org/api/v2", values[1].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigrationAndSavesIt() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> valuePairs) => { Assert.Equal(1, valuePairs.Count); Assert.Equal("nuget.org", valuePairs[0].Key); Assert.Equal("https://www.nuget.org/api/v2", valuePairs[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); settings.Verify(); } [Fact] public void DisablePackageSourceAddEntryToSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.SetValue("disabledPackageSources", "A", "true")).Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.DisablePackageSource(new PackageSource("source", "A")); // Assert settings.Verify(); } [Fact] public void IsPackageSourceEnabledReturnsFalseIfTheSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns("sdfds"); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.False(isEnabled); } [Theory] [InlineData((string)null)] [InlineData("")] public void IsPackageSourceEnabledReturnsTrueIfTheSourceIsNotDisabled(string returnValue) { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns(returnValue); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.True(isEnabled); } [Theory] [InlineData(new object[] { null, "abcd" })] [InlineData(new object[] { "", "abcd" })] [InlineData(new object[] { "abcd", null })] [InlineData(new object[] { "abcd", "" })] public void LoadPackageSourcesIgnoresInvalidCredentialPairsFromSettings(string userName, string password) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new [] { new KeyValuePair<string, string>("Username", userName), new KeyValuePair<string, string>("Password", password) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesReadsCredentialPairsFromSettings() { // Arrange string encryptedPassword = EncryptionUtility.EncryptString("topsecret"); var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("Password", encryptedPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.Equal("topsecret", values[1].Password); Assert.False(values[1].IsPasswordClearText); } [Fact] public void LoadPackageSourcesReadsClearTextCredentialPairsFromSettings() { // Arrange const string clearTextPassword = "topsecret"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("ClearTextPassword", clearTextPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.True(values[1].IsPasswordClearText); Assert.Equal("topsecret", values[1].Password); } [Theory] [InlineData("Username=john;Password=johnspassword")] [InlineData("uSerName=john;PASSWOrD=johnspassword")] [InlineData(" Username=john; Password=johnspassword ")] public void LoadPackageSourcesLoadsCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange const string userName = "john"; const string password = "johnspassword"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment:environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal(userName, values[1].UserName); Assert.Equal(password, values[1].Password); } [Theory] [InlineData("uername=john;Password=johnspassword")] [InlineData(".Username=john;Password=johnspasswordf")] [InlineData("What is this I don't even")] public void LoadPackageSourcesIgnoresMalformedCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesEnvironmentCredentialsTakePrecedenceOverSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("Username=envirouser;Password=enviropassword"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("envirouser", values[1].UserName); Assert.Equal("enviropassword", values[1].Password); } [Fact] public void LoadPackageSourcesWhenEnvironmentCredentialsAreMalformedFallsbackToSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("I for one don't understand environment variables"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("settinguser", values[1].UserName); Assert.Equal("settingpassword", values[1].Password); } // Test that when there are duplicate sources, i.e. sources with the same name, // then the source specified in one Settings with the highest priority is used. [Fact] public void DuplicatePackageSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("one", "threesource", false) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "one", "threesource", true); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettings() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two"), new PackageSource("three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettingsWhenSomePackageSourceIsDisabled() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two", "two", isEnabled: false), new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(1, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("true", values[0].Value, StringComparer.OrdinalIgnoreCase); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesCredentials() { // Arrange var entropyBytes = Encoding.UTF8.GetBytes("NuGet"); var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password" }, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); Assert.Equal("Password", values[1].Key); string decryptedPassword = Encoding.UTF8.GetString( ProtectedData.Unprotect(Convert.FromBase64String(values[1].Value), entropyBytes, DataProtectionScope.CurrentUser)); Assert.Equal("Password", values[1].Key); Assert.Equal("password", decryptedPassword); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesClearTextCredentials() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password", IsPasswordClearText = true}, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); AssertKVP(new KeyValuePair<string, string>("ClearTextPassword", "password"), values[1]); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void GetAggregateReturnsAggregateRepositoryForAllSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryB.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsInvalidSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: true); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryC.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsDisabledSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Throws(new Exception()); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B", "B", isEnabled: false), new PackageSource("C", "C", isEnabled: false) }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(1, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); } [Fact] public void GetAggregateHandlesInvalidUriSources() { // Arrange var factory = PackageRepositoryFactory.Default; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("Bad 1"), new PackageSource(@"x:sjdkfjhsdjhfgjdsgjglhjk"), new PackageSource(@"http:\\//") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory, ignoreFailingRepositories: true); // Assert Assert.False(repo.Repositories.Any()); } [Fact] public void GetAggregateSetsIgnoreInvalidRepositoryProperty() { // Arrange var factory = new Mock<IPackageRepositoryFactory>(); bool ignoreRepository = true; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(Enumerable.Empty<PackageSource>()); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: ignoreRepository); // Assert Assert.True(repo.IgnoreFailingRepositories); } [Fact] public void GetAggregateWithInvalidSourcesThrows() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>(() => sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false)); } [Fact] public void ResolveSourceLooksUpNameAndSource() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal(source2.Source, result1); Assert.Equal(source2.Source, result2); Assert.Equal(source1.Source, result3); } [Fact] public void ResolveSourceIgnoreDisabledSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"); PackageSource source2 = new PackageSource("http://www.test.com", "Baz", isEnabled: false); PackageSource source3 = new PackageSource("http://www.bing.com", "Foo", isEnabled: false); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2, source3 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("Foo"); var result4 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal("http://www.test.com", result1); Assert.Equal("Baz", result2); Assert.Equal("Foo", result3); Assert.Equal("Source", result4); } [Fact] public void ResolveSourceReturnsOriginalValueIfNotFoundInSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); var source = "http://www.does-not-exist.com"; // Act var result = sources.Object.ResolveSource(source); // Assert Assert.Equal(source, result); } private void AssertPackageSource(PackageSource ps, string name, string source, bool isEnabled, bool isMachineWide = false, bool isOfficial = false) { Assert.Equal(name, ps.Name); Assert.Equal(source, ps.Source); Assert.True(ps.IsEnabled == isEnabled); Assert.True(ps.IsMachineWide == isMachineWide); Assert.True(ps.IsOfficial == isOfficial); } private IPackageSourceProvider CreatePackageSourceProvider( ISettings settings = null, IEnumerable<PackageSource> providerDefaultSources = null, IDictionary<PackageSource, PackageSource> migratePackageSources = null, IEnumerable<PackageSource> configurationDefaultSources = null, IEnvironmentVariableReader environment = null) { settings = settings ?? new Mock<ISettings>().Object; environment = environment ?? new Mock<IEnvironmentVariableReader>().Object; return new PackageSourceProvider(settings, providerDefaultSources, migratePackageSources, configurationDefaultSources, environment); } private static void AssertKVP(KeyValuePair<string, string> expected, KeyValuePair<string, string> actual) { Assert.Equal(expected.Key, actual.Key); Assert.Equal(expected.Value, actual.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeDom.Compiler; namespace Microsoft.Tools.ServiceModel.Svcutil { internal partial class CommandProcessorOptions : SvcutilOptions { #region Options-related properties public const string UpdateServiceReferenceKey = "update"; public string UpdateServiceReferenceFolder { get { return GetValue<string>(UpdateServiceReferenceKey); } set { SetValue(UpdateServiceReferenceKey, value); } } public override string Json { get { return Serialize<CommandProcessorOptions, OptionsSerializer<CommandProcessorOptions>>(); } } /// <summary> /// Wrapper around TypeReuseMode. /// A flag makes more sense on the command line: 'true/false' map to 'None/All' and /// if any reference specified in the command line maps to 'Specified'. /// </summary> public bool NoTypeReuse { get { return this.TypeReuseMode == Svcutil.TypeReuseMode.None; } set { SetValue(TypeReuseModeKey, ParseNoTypeReuseOptionValue(value)); } } #endregion #region Properties public static CommandSwitches Switches = new CommandSwitches(); public List<Type> ReferencedTypes { get; private set; } public List<Assembly> ReferencedAssemblies { get; private set; } public List<Type> ReferencedCollectionTypes { get; private set; } public ILogger Logger { get; private set; } public CodeDomProvider CodeProvider { get; private set; } public bool OwnsBootstrapDir { get; private set; } public bool KeepBootstrapDir { get { return this.Verbosity == Svcutil.Verbosity.Debug || DebugUtils.KeepTemporaryDirs; } } // See Update option processing. public bool IsUpdateOperation { get { return this.UpdateServiceReferenceFolder != null; } } // See NoBootstrapping option processing. public bool RequiresBoostrapping { get; private set; } #endregion #region Constants internal const string SvcutilParamsFileName = "dotnet-svcutil.params.json"; internal const string WCFCSParamsFileName = "ConnectedService.json"; internal const string BaseServiceReferenceName = "ServiceReference"; private static readonly List<string> s_cmdLineOverwriteSwitches = new List<string> { Switches.NoLogo.Name, Switches.Verbosity.Name, Switches.ToolContext.Name }; internal class CommandSwitches { public readonly CommandSwitch BootstrapDir = new CommandSwitch(BootstrapPathKey, "bd", SwitchType.SingletonValue, OperationalContext.Infrastructure); public readonly CommandSwitch CollectionType = new CommandSwitch(CollectionTypesKey, "ct", SwitchType.ValueList); public readonly CommandSwitch CultureName = new CommandSwitch(CultureInfoKey, "cn", SwitchType.SingletonValue, OperationalContext.Infrastructure); public readonly CommandSwitch EnableDataBinding = new CommandSwitch(EnableDataBindingKey, "edb", SwitchType.Flag); public readonly CommandSwitch EnableLoggingMarkup = new CommandSwitch(EnableLoggingMarkupKey, "elm", SwitchType.Flag, OperationalContext.Infrastructure); public readonly CommandSwitch ExcludeType = new CommandSwitch(ExcludeTypesKey, "et", SwitchType.ValueList); public readonly CommandSwitch Help = new CommandSwitch(HelpKey, "h", SwitchType.Flag); public readonly CommandSwitch Internal = new CommandSwitch(InternalTypeAccessKey, "i", SwitchType.Flag); public readonly CommandSwitch MessageContract = new CommandSwitch(MessageContractKey, "mc", SwitchType.Flag); public readonly CommandSwitch Namespace = new CommandSwitch(NamespaceMappingsKey, "n", SwitchType.ValueList); public readonly CommandSwitch NoBootstraping = new CommandSwitch(NoBootstrappingKey, "nb", SwitchType.Flag, OperationalContext.Infrastructure); public readonly CommandSwitch NoLogo = new CommandSwitch(NoLogoKey, "nl", SwitchType.Flag); public readonly CommandSwitch NoProjectUpdates = new CommandSwitch(NoProjectUpdatesKey, "npu", SwitchType.Flag, OperationalContext.Infrastructure); public readonly CommandSwitch NoTelemetry = new CommandSwitch(NoTelemetryKey, "nm", SwitchType.Flag, OperationalContext.Infrastructure); public readonly CommandSwitch NoTypeReuse = new CommandSwitch("noTypeReuse", "ntr", SwitchType.Flag, OperationalContext.Project); // this maps to TypeReuseMode, for the command line a flag makes more sense. public readonly CommandSwitch NoStdlib = new CommandSwitch(NoStandardLibraryKey, "nsl", SwitchType.Flag); public readonly CommandSwitch OutputDirectory = new CommandSwitch(OutputDirKey, "d", SwitchType.SingletonValue, OperationalContext.Global); public readonly CommandSwitch OutputFile = new CommandSwitch(OutputFileKey, "o", SwitchType.SingletonValue, OperationalContext.Global); public readonly CommandSwitch ProjectFile = new CommandSwitch(ProjectFileKey, "pf", SwitchType.SingletonValue, OperationalContext.Global); public readonly CommandSwitch Reference = new CommandSwitch(ReferencesKey, "r", SwitchType.ValueList); public readonly CommandSwitch RuntimeIdentifier = new CommandSwitch(RuntimeIdentifierKey, "ri", SwitchType.SingletonValue, OperationalContext.Global); public readonly CommandSwitch Serializer = new CommandSwitch(SerializerModeKey, "ser", SwitchType.SingletonValue); public readonly CommandSwitch Sync = new CommandSwitch(SyncKey, "syn", SwitchType.Flag); public readonly CommandSwitch TargetFramework = new CommandSwitch(TargetFrameworkKey, "tf", SwitchType.SingletonValue, OperationalContext.Global); public readonly CommandSwitch ToolContext = new CommandSwitch(ToolContextKey, "tc", SwitchType.SingletonValue, OperationalContext.Infrastructure); public readonly CommandSwitch Update = new CommandSwitch(UpdateServiceReferenceKey, "u", SwitchType.FlagOrSingletonValue, OperationalContext.Project); public readonly CommandSwitch Verbosity = new CommandSwitch(VerbosityKey, "v", SwitchType.SingletonValue); public readonly CommandSwitch Wrapped = new CommandSwitch(WrappedKey, "wr", SwitchType.Flag); public void Init() { } // provided as a way to get the static class Switches loaded early. } #endregion public CommandProcessorOptions() { this.ReferencedTypes = new List<Type>(); this.ReferencedAssemblies = new List<Assembly>(); this.ReferencedCollectionTypes = new List<Type>(); RegisterOptions( new SingleValueOption<string>(UpdateServiceReferenceKey) { CanSerialize = false }); var typeReuseModeOption = this.GetOption(TypeReuseModeKey); typeReuseModeOption.Aliases.Add(Switches.NoTypeReuse.Name); typeReuseModeOption.ValueChanging += (s, e) => e.Value = ParseNoTypeReuseOptionValue(e.Value); Switches.Init(); } public static new CommandProcessorOptions FromFile(string filePath, bool throwOnError = true) { return FromFile<CommandProcessorOptions>(filePath, throwOnError); } public static bool TryFromFile(string filePath, out CommandProcessorOptions options) { options = null; try { options = FromFile<CommandProcessorOptions>(filePath, throwOnError: false); } catch { } return options?.Errors.Count() == 0; } #region option processing methods internal static async Task<CommandProcessorOptions> ParseArgumentsAsync(string[] args, ILogger logger, CancellationToken cancellationToken) { CommandProcessorOptions cmdOptions = new CommandProcessorOptions(); try { cmdOptions = CommandParser.ParseCommand(args); // Try to load parameters from input file. if (cmdOptions.Errors.Count() == 0 && cmdOptions.Inputs.Count == 1) { if (PathHelper.IsFile(cmdOptions.Inputs[0], Directory.GetCurrentDirectory(), out var fileUri) && TryFromFile(fileUri.LocalPath, out var fileOptions) && fileOptions.GetOptions().Count() > 0) { // user switches are disallowed when a params file is provided. var options = cmdOptions.GetOptions().ToList(); var disallowedSwitchesOnParamsFilesProvided = CommandSwitch.All .Where(s => !s_cmdLineOverwriteSwitches.Contains(s.Name) && s.SwitchLevel <= OperationalContext.Global && options.Any(o => { if (o.HasSameId(s.Name)) { o.Value = null; return true; } return false; })); // warn about disallowed options when params file has been provided and clear them. if (disallowedSwitchesOnParamsFilesProvided.Count() > 0) { fileOptions.AddWarning(string.Format(SR.WrnExtraParamsOnInputFileParamIgnoredFormat, disallowedSwitchesOnParamsFilesProvided.Select(s => $"'{s.Name}'").Aggregate((msg, n) => $"{msg}, '{n}'")), 0); } fileOptions.ResolveFullPathsFrom(new DirectoryInfo(Path.GetDirectoryName(fileUri.LocalPath))); // ensure inputs are clear as the params file is the input. cmdOptions.Inputs.Clear(); cmdOptions.CopyTo(fileOptions); cmdOptions = fileOptions; } } } catch (ArgumentException ae) { cmdOptions.AddError(ae); } catch (FileLoadException fle) { cmdOptions.AddError(fle); } catch (FormatException fe) { cmdOptions.AddError(fe); } await cmdOptions.ProcessBasicOptionsAsync(logger, cancellationToken); return cmdOptions; } public async Task ResolveAsync(CancellationToken cancellationToken) { try { if (this.Help != true && this.Errors.Count() == 0) { ProcessLanguageOption(); ProcessSerializerOption(); // process project file first as it can define the working directory. await ProcessProjectFileOptionAsync(cancellationToken).ConfigureAwait(false); // next update option as the options may change. await ProcessUpdateOptionAsync(cancellationToken).ConfigureAwait(false); // next output directory and output file, they have a circular dependency resolved with the working directory. await ProcessOutputDirOptionAsync(this.Project?.DirectoryPath, cancellationToken).ConfigureAwait(false); await ProcessOutputFileOptionAsync(this.OutputDir.FullName, cancellationToken); // target framework option depends on the boostrapping option (a temporary project may be needed). await ProcessBootstrapDirOptionAsync(cancellationToken).ConfigureAwait(false); // namespace mappings depends on the project and outputdir options to compute default namespace. await ProcessNamespaceMappingsOptionAsync(cancellationToken).ConfigureAwait(false); // inputs depends on the update option in case the real inputs come from the update params file. await ProcessInputsAsync(cancellationToken).ConfigureAwait(false); // target framework is needed by the references option. await ProcessTargetFrameworkOptionAsync(cancellationToken).ConfigureAwait(false); // type reuse is needed by the references option. ProcessTypeReuseModeOption(); await ProcessReferencesOptionAsync(cancellationToken).ConfigureAwait(false); // bootstrapping option deteremines whether referenced assemblies(next) should be processed now or by the bootstrapper. ProcessBootstrappingOption(); await ProcessReferenceAssembliesAsync(cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; this.AddError(ex); } } internal async Task ProcessBasicOptionsAsync(ILogger logger, CancellationToken cancellation) { var userOptions = this.GetOptions().ToList(); if (userOptions.Count == 0) { // no options provided in the command line. this.Help = true; } if (!this.ToolContext.HasValue) { this.ToolContext = CommandSwitch.DefaultSwitchLevel; } if (!this.Verbosity.HasValue) { this.Verbosity = Svcutil.Verbosity.Normal; } this.Logger = logger ?? new DebugLogger(); if (this.Logger is DebugLogger debugLooger) { debugLooger.EnableTracing = this.EnableLoggingMarkup == true || this.Verbosity == Svcutil.Verbosity.Debug; } if (this.Help != true) { using (SafeLogger safeLogger = await SafeLogger.WriteStartOperationAsync(this.Logger, "Validating options ...").ConfigureAwait(false)) { await safeLogger.WriteMessageAsync($"Tool context: {this.ToolContext}", logToUI: false).ConfigureAwait(false); var disallowedContextSwitches = CommandSwitch.All.Where(s => s != Switches.ToolContext && s.SwitchLevel > this.ToolContext && userOptions.Any(o => o.HasSameId(s.Name))); foreach (var cmdSwitch in disallowedContextSwitches) { this.AddWarning(string.Format(SR.WrnUnexpectedArgumentFormat, cmdSwitch.Name), 0); } if (IsUpdateOperation) { s_cmdLineOverwriteSwitches.Add(Switches.Update.Name); var disallowedUserOptionsOnUpdateOperation = this.GetOptions().Where(o => !s_cmdLineOverwriteSwitches.Any(n => o.HasSameId(n))); // special-case inputs as there's no switch for them. if (this.Inputs.Count > 0) { this.AddWarning(string.Format(SR.WrnUnexpectedInputsFormat, this.Inputs.Select(i => $"{i}''").Aggregate((msg, i) => $"{msg}, {i}"))); await safeLogger.WriteMessageAsync($"Resetting unexpected option '{InputsKey}' ...", logToUI: false).ConfigureAwait(false); this.Inputs.Clear(); } foreach (var option in disallowedUserOptionsOnUpdateOperation) { this.AddWarning(string.Format(SR.WrnUnexpectedArgumentFormat, option.Name)); await safeLogger.WriteMessageAsync($"Resetting unexpected option '{option.Name}' ...", logToUI: false).ConfigureAwait(false); option.Value = null; // this will exclude the invalid option from processing/serializing. } } } } Debug.Assert(this.ToolContext.HasValue, $"{nameof(ToolContext)} is not initialized!"); Debug.Assert(this.Verbosity.HasValue, $"{nameof(Verbosity)} is not initialized!"); } private async Task ProcessProjectFileOptionAsync(CancellationToken cancellationToken) { var projectFile = this.Project?.FullPath; if (projectFile == null) { using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Resolving {ProjectFileKey} option ...").ConfigureAwait(false)) { // Resolve the project in the current directory. var workingDirectory = Directory.GetCurrentDirectory(); var projects = Directory.GetFiles(workingDirectory, "*.csproj", SearchOption.TopDirectoryOnly); if (projects.Length == 1) { projectFile = projects[0]; } else if (projects.Length == 0) { if (this.ToolContext == OperationalContext.Project) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrInvalidOperationNoProjectFileFoundUnderFolderFormat, workingDirectory)); } } else if (projects.Length > 1) { var moreThanOneProjectMsg = string.Format(CultureInfo.CurrentCulture, SR.ErrMoreThanOneProjectFoundFormat, workingDirectory); if (this.ToolContext != OperationalContext.Project) { var projectItems = projects.Aggregate((projectMsg, projectItem) => $"{projectMsg}, {projectItem}").Trim(',').Trim(); var useProjectOptions = string.Format(CultureInfo.CurrentCulture, SR.UseProjectFileOptionOnMultipleFilesMsgFormat, Switches.ProjectFile.Name, projectItems); throw new ToolArgumentException($"{moreThanOneProjectMsg}{Environment.NewLine}{useProjectOptions}"); } else { throw new ToolArgumentException(moreThanOneProjectMsg); } } await logger.WriteMessageAsync($"{ProjectFileKey}:\"{projectFile}\"", logToUI: false).ConfigureAwait(false); } } if (this.Project == null && projectFile != null) { this.Project = await MSBuildProj.FromPathAsync(projectFile, this.Logger, cancellationToken).ConfigureAwait(false); } } private async Task ProcessOutputDirOptionAsync(string workingDirectory, CancellationToken cancellationToken) { if (this.OutputDir == null) { using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Resolving {OutputDirKey} option ...").ConfigureAwait(false)) { if (string.IsNullOrEmpty(workingDirectory)) { // First check the output file and use its directory if fully qualified, second try to use the project's directory if available, // use the current directory otherwise. var defaultDir = this.Project?.DirectoryPath ?? Directory.GetCurrentDirectory(); await ProcessOutputFileOptionAsync(defaultDir, cancellationToken).ConfigureAwait(false); workingDirectory = Path.IsPathRooted(this.OutputFile.OriginalPath()) ? Path.GetDirectoryName(this.OutputFile.FullName) : Path.GetDirectoryName(Path.Combine(Directory.GetCurrentDirectory(), this.OutputFile.OriginalPath())); } // Guard against infinite recursion as reentrancy can happen when resolving the output file above as it checks the output dir as well. if (this.OutputDir == null) { this.OutputDir = IsUpdateOperation ? new DirectoryInfo(Path.Combine(workingDirectory, this.UpdateServiceReferenceFolder)) : PathHelper.CreateUniqueDirectoryName(BaseServiceReferenceName, new DirectoryInfo(workingDirectory)); } await logger.WriteMessageAsync($"{OutputDirKey}:\"{this.OutputDir}\"", logToUI: false).ConfigureAwait(false); } } else { var originalDirSpec = this.OutputDir.ToString(); // ToString provides the original value of the DirectoryInfo. if (!Path.IsPathRooted(originalDirSpec)) { workingDirectory = workingDirectory ?? Directory.GetCurrentDirectory(); this.OutputDir = new DirectoryInfo(Path.Combine(workingDirectory, originalDirSpec)); } } } private async Task ProcessOutputFileOptionAsync(string workingDirectory, CancellationToken cancellationToken) { using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Resolving {OutputFileKey} option ...").ConfigureAwait(false)) { var outputFile = this.OutputFile?.OriginalPath(); if (outputFile == null) { outputFile = "Reference.cs"; } if (!outputFile.EndsWith(this.CodeProvider.FileExtension, RuntimeEnvironmentHelper.FileStringComparison)) { outputFile += $".{this.CodeProvider.FileExtension}"; } // Ensure the ouput directory has been resolved first by using the specified directory as the default if not null, // the project file directory if available, the current application directory otherwise. var defaultDir = workingDirectory ?? this.Project?.DirectoryPath ?? Directory.GetCurrentDirectory(); await ProcessOutputDirOptionAsync(defaultDir, cancellationToken); if (PathHelper.IsUnderDirectory(outputFile, this.OutputDir, out var filePath, out var relPath)) { // if adding a new service reference fail if the output file already exists. // notice that if bootstrapping, the bootstrapper doesn't understand the update opertion, it just knows to add the reference file. if (!IsUpdateOperation && this.ToolContext <= OperationalContext.Global && File.Exists(filePath)) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrOutputFileAlreadyExistsFormat, filePath, Switches.OutputFile.Name)); } outputFile = filePath; } else { throw new ToolArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ErrOutputFileNotUnderOutputDirFormat, Switches.OutputFile.Name, outputFile, this.OutputDir, Switches.OutputDirectory.Name)); } if (this.ToolContext == OperationalContext.Project && this.Project != null && !PathHelper.IsUnderDirectory(outputFile, new DirectoryInfo(this.Project.DirectoryPath), out filePath, out relPath)) { this.AddWarning(string.Format(CultureInfo.CurrentCulture, SR.WrnSpecifiedFilePathNotUndeProjectDirFormat, Switches.OutputFile.Name, outputFile, this.Project.DirectoryPath)); } this.OutputFile = new FileInfo(outputFile); await logger.WriteMessageAsync($"{OutputFileKey}:\"{filePath}\"", logToUI: false).ConfigureAwait(false); } } private async Task ProcessUpdateOptionAsync(CancellationToken cancellation) { if (IsUpdateOperation) { using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Processing {UpdateServiceReferenceKey} option ...").ConfigureAwait(false)) { var projectDir = this.Project?.DirectoryPath; if (projectDir == null) { if (this.ToolContext == OperationalContext.Project) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrInvalidOperationNoProjectFileFoundUnderFolderFormat, Directory.GetCurrentDirectory())); } else { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrProjectToUpdateNotFoundFormat, Switches.Update.Name, Switches.ProjectFile.Name)); } } var paramsFilePath = string.Empty; var fileRelPath = string.Empty; // check whether the params file was passed instead of the folder name, this is not expected but let's deal with it. var updateFileName = Path.GetFileName(this.UpdateServiceReferenceFolder); if (updateFileName.Equals(CommandProcessorOptions.SvcutilParamsFileName, RuntimeEnvironmentHelper.FileStringComparison) || updateFileName.Equals(CommandProcessorOptions.WCFCSParamsFileName, RuntimeEnvironmentHelper.FileStringComparison)) { // if the resolved path is empty, we will try to find the params file next. this.UpdateServiceReferenceFolder = Path.GetDirectoryName(this.UpdateServiceReferenceFolder); } if (this.UpdateServiceReferenceFolder == string.Empty) { // param passed as flag, there must be only one service under the project. var excludeJsonFiles = Directory.GetFiles(projectDir, "*.json", SearchOption.TopDirectoryOnly); // update json files must be under a reference folder, exclude any top json files. var jsonFiles = Directory.GetFiles(projectDir, "*.json", SearchOption.AllDirectories); var paramsFiles = jsonFiles.Except(excludeJsonFiles).Where(fn => Path.GetFileName(fn).Equals(CommandProcessorOptions.SvcutilParamsFileName, RuntimeEnvironmentHelper.FileStringComparison) || Path.GetFileName(fn).Equals(CommandProcessorOptions.WCFCSParamsFileName, RuntimeEnvironmentHelper.FileStringComparison)); if (paramsFiles.Count() == 1) { paramsFilePath = paramsFiles.First(); } else if (paramsFiles.Count() == 0) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrNoUpdateParamsFileFoundFormat, this.Project.FullPath)); } // no else here, this check applies to the inner block above as well. if (paramsFiles.Count() > 1) { var svcRefNames = paramsFiles.Select(pf => { PathHelper.GetRelativePath(Path.GetDirectoryName(pf), new DirectoryInfo(projectDir), out var relPath); return relPath; }) .Select(f => $"'{f}'").Aggregate((files, f) => $"{files}, {f}"); throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrMoreThanOneUpdateParamsFilesFoundFormat, this.Project.FullPath, Switches.Update.Name, svcRefNames)); } PathHelper.GetRelativePath(paramsFilePath, new DirectoryInfo(projectDir), out fileRelPath); } else { var projectDirInfo = new DirectoryInfo(projectDir); var svcutilParmasFile = Path.Combine(projectDir, this.UpdateServiceReferenceFolder, CommandProcessorOptions.SvcutilParamsFileName); if (!PathHelper.IsUnderDirectory(svcutilParmasFile, projectDirInfo, out paramsFilePath, out fileRelPath) || !File.Exists(paramsFilePath)) { var wcfcsParamsFile = Path.Combine(projectDir, this.UpdateServiceReferenceFolder, CommandProcessorOptions.WCFCSParamsFileName); if (!PathHelper.IsUnderDirectory(wcfcsParamsFile, projectDirInfo, out paramsFilePath, out fileRelPath) || !File.Exists(paramsFilePath)) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrServiceReferenceNotFoundUnderProjectFormat, this.UpdateServiceReferenceFolder, this.Project.FullPath)); } } } var relDir = Path.GetDirectoryName(fileRelPath); if (string.IsNullOrEmpty(relDir)) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrNoUpdateParamsFileFoundFormat, this.Project.FullPath)); } this.UpdateServiceReferenceFolder = relDir; UpdateOptions updateOptions = null; if (Path.GetFileName(paramsFilePath).Equals(CommandProcessorOptions.WCFCSParamsFileName)) { var wcfOptions = WCFCSUpdateOptions.FromFile(paramsFilePath); updateOptions = wcfOptions.CloneAs<UpdateOptions>(); } else { updateOptions = UpdateOptions.FromFile(paramsFilePath); } updateOptions.ResolveFullPathsFrom(new DirectoryInfo(Path.GetDirectoryName(paramsFilePath))); // merge/overwrite options. updateOptions.CopyTo(this); await logger.WriteMessageAsync($"Update option read from \"{paramsFilePath}\" ...", logToUI: false).ConfigureAwait(false); } } } private async Task ProcessBootstrapDirOptionAsync(CancellationToken cancellationToken) { // NOTE: The bootstrapping directory is not only used for the svcutil bootstrapper but also for other temporary projects // like the one generated to get the target framework. The svcutil bootstrapper is created under this directory. using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Processing {BootstrapPathKey} option ...").ConfigureAwait(false)) { if (this.BootstrapPath == null) { var tempDir = Path.GetTempPath(); var baseDirName = $"{Tool.AssemblyName}_Temp"; var sessionDirName = DateTime.Now.ToString("yyyy_MMM_dd_HH_mm_ss", CultureInfo.InvariantCulture); this.BootstrapPath = new DirectoryInfo(Path.Combine(tempDir, baseDirName, sessionDirName)); } // delay creating the bootstrapping directory until needed. await logger.WriteMessageAsync($"{BootstrapPathKey}:\"{this.BootstrapPath}\"", logToUI: false).ConfigureAwait(false); } } private void ProcessBootstrappingOption() { if (this.NoBootstrapping != true) // value not set or set to false, check whether we need the boostrapper or not. { // bootstrapping is required for type reuse when targetting a supported .NET Core platform and when there are project references // different form the .NET Core and WCF ones. this.RequiresBoostrapping = SvcutilBootstrapper.RequiresBootstrapping(this.TargetFramework, this.References); } } private void ProcessTypeReuseModeOption() { if (!this.TypeReuseMode.HasValue) { this.TypeReuseMode = this.References.Count == 0 ? Svcutil.TypeReuseMode.All : Svcutil.TypeReuseMode.Specified; } } private async Task ProcessReferencesOptionAsync(CancellationToken cancellationToken) { // references are resolved in order to reuse types from referenced assemblies for the proxy code generation, supported on DNX frameworks only. // resolve project references when the type reuse option or the bootstrapping option (which is meant for processing external references) have not been disabled // and either no specific references have been provided or the service reference is being updated. In the latter case if type reuse is enabled for all // assemblies, we need to resolve references regardless because the user could have changed the project refernces since the web service reference was added. bool resolveReferences = this.Project != null && this.TargetFramework.IsDnx && this.NoBootstrapping != true && this.TypeReuseMode != Svcutil.TypeReuseMode.None && (this.IsUpdateOperation || this.TypeReuseMode == Svcutil.TypeReuseMode.All); if (resolveReferences) { using (var logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Processing {nameof(this.References)}, count: {this.References.Count}. Reference resolution enabled: {resolveReferences}").ConfigureAwait(false)) { await logger.WriteMessageAsync(Shared.Resources.ResolvingProjectReferences, logToUI: this.ToolContext <= OperationalContext.Global).ConfigureAwait(false); var references = await this.Project.ResolveProjectReferencesAsync(ProjectDependency.IgnorableDependencies, logger, cancellationToken).ConfigureAwait(false); if (this.TypeReuseMode == Svcutil.TypeReuseMode.All) { this.References.Clear(); this.References.AddRange(references); } else // Update operation: remove any reference no longer in the project! { for (int idx = this.References.Count - 1; idx >= 0; idx--) { if (!references.Contains(this.References[idx])) { this.References.RemoveAt(idx); } } } } } this.References.Sort(); } private async Task ProcessNamespaceMappingsOptionAsync(CancellationToken cancellationToken) { using (var logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Processing {nameof(this.NamespaceMappings)}, count: {this.NamespaceMappings.Count}").ConfigureAwait(false)) { if (this.NamespaceMappings.Count == 0) { // try to add default namespace. if (this.Project != null && PathHelper.GetRelativePath(this.OutputDir.FullName, new DirectoryInfo(this.Project.DirectoryPath), out var relPath)) { var clrNamespace = CodeDomHelpers.GetValidValueTypeIdentifier(relPath); this.NamespaceMappings.Add(new KeyValuePair<string, string>("*", clrNamespace)); } } else { // validate provided namespace values. var invalidNamespaces = this.NamespaceMappings.Where(nm => !CodeDomHelpers.IsValidNameSpace(nm.Value)); if (invalidNamespaces.Count() > 0) { throw new ToolArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ErrInvalidNamespaceFormat, invalidNamespaces.Select(n => $"'{n.Key},{n.Value}'").Aggregate((msg, n) => $"{msg}, {n}"))); } } } } private async Task ProcessTargetFrameworkOptionAsync(CancellationToken cancellationToken) { if (this.TargetFramework == null) { var targetFrameworkMoniker = string.Empty; if (this.Project != null) { targetFrameworkMoniker = this.Project.TargetFramework; } else { Debug.Assert(this.BootstrapPath != null, $"{nameof(this.BootstrapPath)} is not initialized!"); using (SafeLogger logger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Resolving {TargetFrameworkKey} option ...").ConfigureAwait(false)) { var projectFullPath = Path.Combine(this.BootstrapPath.FullName, "TFMResolver", "TFMResolver.csproj"); if (File.Exists(projectFullPath)) { // this is not expected unless the boostrapping directory is reused (as in testing) // as we don't know what SDK version was used to create the temporary project we better clean up. Directory.Delete(Path.GetDirectoryName(projectFullPath)); } await SetupBootstrappingDirectoryAsync(logger, cancellationToken).ConfigureAwait(false); using (var proj = await MSBuildProj.DotNetNewAsync(projectFullPath, this.Logger, cancellationToken).ConfigureAwait(false)) { targetFrameworkMoniker = proj.TargetFramework; } } } ProcessToolArg(() => this.TargetFramework = TargetFrameworkHelper.GetValidFrameworkInfo(targetFrameworkMoniker)); } AppSettings.Initialize(this.TargetFramework); } private async Task ProcessInputsAsync(CancellationToken cancellationToken) { if (this.Inputs.Count == 0) { throw new ToolInputException(SR.ErrNoValidInputSpecified); } using (var safeLogger = await SafeLogger.WriteStartOperationAsync(this.Logger, $"Processing inputs, count: {this.Inputs.Count} ...").ConfigureAwait(false)) { for (int idx = 0; idx < this.Inputs.Count; idx++) { if (PathHelper.IsFile(this.Inputs[idx], Directory.GetCurrentDirectory(), out Uri metadataUri)) { this.Inputs.RemoveAt(idx); var inputFiles = Metadata.MetadataFileNameManager.ResolveFiles(metadataUri.LocalPath).Select(f => f.FullName); await safeLogger.WriteMessageAsync($"resolved inputs: {inputFiles.Count()}", logToUI: false).ConfigureAwait(false); foreach (var file in inputFiles) { this.Inputs.Insert(idx, new Uri(file)); } } } } } private void ProcessSerializerOption() { if (!this.SerializerMode.HasValue) { this.SerializerMode = Svcutil.SerializerMode.Default; } } private void ProcessLanguageOption() { if (this.CodeProvider == null) { this.CodeProvider = CodeDomProvider.CreateProvider("csharp"); } } #endregion #region serialization methods private object ParseNoTypeReuseOptionValue(object value) { object typeReuseMode = this.GetOption(TypeReuseModeKey).DefaultValue; if (value != null) { var stringValue = value.ToString(); if (bool.TryParse(stringValue, out var notTypeReuse)) { typeReuseMode = notTypeReuse ? (object)Svcutil.TypeReuseMode.None : null; } else { typeReuseMode = OptionValueParser.ParseEnum<TypeReuseMode>(stringValue, this.GetOption(TypeReuseModeKey)); } } return typeReuseMode; } protected override void OnBeforeSerialize() { base.OnBeforeSerialize(); if (this.TypeReuseMode == Svcutil.TypeReuseMode.All) { // no need to serialize references as they will have to be resolved again if service reference is updated. this.References.Clear(); } } #endregion #region helper methods private async Task ProcessReferenceAssembliesAsync(CancellationToken cancellationToken) { // Reference processing is done when no bootstrapping is needed or by the boostrapper! if (!this.RequiresBoostrapping) { using (var logger = await SafeLogger.WriteStartOperationAsync(this.Logger, "Processing reference assemblies ...").ConfigureAwait(false)) { var foundCollectionTypes = AddSpecifiedTypesToDictionary(this.CollectionTypes, Switches.CollectionType.Name); var excludedTypes = AddSpecifiedTypesToDictionary(this.ExcludeTypes, Switches.ExcludeType.Name); LoadReferencedAssemblies(); foreach (Assembly assembly in this.ReferencedAssemblies) { AddReferencedTypesFromAssembly(assembly, foundCollectionTypes, excludedTypes); } if (this.NoStandardLibrary != true) { AddStdLibraries(foundCollectionTypes, excludedTypes); } AddReferencedCollectionTypes(this.CollectionTypes, foundCollectionTypes); } } } private void LoadReferencedAssemblies() { // we should not load the ServiceModel assemblies as types will clash with the private code types. var loadableReferences = this.References.Where(r => !TargetFrameworkHelper.ServiceModelPackages.Any(s => s.Name == r.Name)); foreach (ProjectDependency reference in loadableReferences) { Assembly assembly = TypeLoader.LoadAssembly(reference.AssemblyName); if (assembly != null) { if (!this.ReferencedAssemblies.Contains(assembly)) { this.ReferencedAssemblies.Add(assembly); } } } } private static Dictionary<string, Type> AddSpecifiedTypesToDictionary(IList<string> typeArgs, string cmd) { Dictionary<string, Type> specifiedTypes = new Dictionary<string, Type>(typeArgs.Count); foreach (string typeArg in typeArgs) { if (specifiedTypes.ContainsKey(typeArg)) { throw new ToolArgumentException(string.Format(SR.ErrDuplicateValuePassedToTypeArgFormat, cmd, typeArg)); } specifiedTypes.Add(typeArg, null); } return specifiedTypes; } private void AddReferencedTypesFromAssembly(Assembly assembly, Dictionary<string, Type> foundCollectionTypes, Dictionary<string, Type> excludedTypes) { foreach (Type type in TypeLoader.LoadTypes(assembly, this.Verbosity.Value)) { TypeInfo info = type.GetTypeInfo(); if (info.IsPublic || info.IsNestedPublic) { if (!IsTypeSpecified(type, excludedTypes, Switches.ExcludeType.Name)) { this.ReferencedTypes.Add(type); } if (IsTypeSpecified(type, foundCollectionTypes, Switches.CollectionType.Name)) { this.ReferencedCollectionTypes.Add(type); } } } } private void AddStdLibraries(Dictionary<string, Type> foundCollectionTypes, Dictionary<string, Type> excludedTypes) { List<Type> coreTypes = new List<Type> { typeof(int), // System.Runtime.dll typeof(System.ServiceModel.ChannelFactory), // System.ServiceModel (svcutil private code) }; foreach (var type in coreTypes) { Assembly stdLib = type.GetTypeInfo().Assembly; if (!this.ReferencedAssemblies.Contains(stdLib)) { AddReferencedTypesFromAssembly(stdLib, foundCollectionTypes, excludedTypes); } } } private static bool IsTypeSpecified(Type type, Dictionary<string, Type> specifiedTypes, string cmd) { string foundTypeName = null; // Search the Dictionary for the type // -------------------------------------------------------------------------------------------------------- if (specifiedTypes.TryGetValue(type.FullName, out Type foundType)) { foundTypeName = type.FullName; } else if (specifiedTypes.TryGetValue(type.AssemblyQualifiedName, out foundType)) { foundTypeName = type.AssemblyQualifiedName; } // Throw appropriate error message if we found something and the entry value wasn't null // -------------------------------------------------------------------------------------------------------- if (foundTypeName != null) { if (foundType != null && foundType != type) { throw new ToolArgumentException(string.Format(SR.ErrCannotDisambiguateSpecifiedTypesFormat, cmd, type.AssemblyQualifiedName, foundType.AssemblyQualifiedName)); } else { specifiedTypes[foundTypeName] = type; } return true; } return false; } private void AddReferencedCollectionTypes(IList<string> collectionTypesArgs, Dictionary<string, Type> foundCollectionTypes) { // Instantiated generics specified via /rct can only be added via assembly.GetType or Type.GetType foreach (string collectionType in collectionTypesArgs) { if (foundCollectionTypes[collectionType] == null) { Type foundType = null; foreach (Assembly assembly in this.ReferencedAssemblies) { try { foundType = assembly.GetType(collectionType); foundCollectionTypes[collectionType] = foundType; } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; } if (foundType != null) break; } try { foundType = foundType ?? Type.GetType(collectionType); } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; } if (foundType == null) { throw new ToolArgumentException(string.Format(SR.ErrCannotLoadSpecifiedTypeFormat, Switches.CollectionType.Name, collectionType, Switches.Reference.Name)); } else { this.ReferencedCollectionTypes.Add(foundType); } } } } private static void ProcessToolArg(Action action) { try { action(); } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; throw new ToolArgumentException(ex.Message); } } internal async Task SetupBootstrappingDirectoryAsync(ILogger logger, CancellationToken cancellationToken) { var workingDirectory = this.Project?.DirectoryPath ?? Directory.GetCurrentDirectory(); if (!Directory.Exists(this.BootstrapPath.FullName)) { Directory.CreateDirectory(this.BootstrapPath.FullName); this.OwnsBootstrapDir = true; } await RuntimeEnvironmentHelper.TryCopyingConfigFiles(workingDirectory, this.BootstrapPath.FullName, logger, cancellationToken).ConfigureAwait(false); } #endregion internal void Cleanup() { try { this.Project?.Dispose(); if (this.BootstrapPath != null && this.BootstrapPath.Exists) { if (this.KeepBootstrapDir) { this.Logger?.WriteMessageAsync($"Bootstrap directory '{this.BootstrapPath}' ...", logToUI: false); } else if (this.OwnsBootstrapDir) { this.Logger?.WriteMessageAsync($"Deleting bootstrap directory '{this.BootstrapPath}' ...", logToUI: false); this.BootstrapPath.Delete(recursive: true); } } } catch { } } public string ToTelemetryString() { return GetOptions() .Where(o => o.CanSerialize) .Select(o => $"{o.Name}:[{OptionValueParser.GetTelemetryValue(o)}]") .Aggregate((num, s) => num + ", " + s).ToString(); } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace CartographerLibrary { /// <summary> /// Base class for rectangle-based graphics: /// rectangle and ellipse. /// </summary> public abstract class GraphicsRectangleBase : GraphicsBase { #region Class Members protected double rectangleLeft; protected double rectangleTop; protected double rectangleRight; protected double rectangleBottom; #endregion Class Members #region Properties /// <summary> /// Read-only property, returns Rect calculated on the fly from four points. /// Points can make inverted rectangle, fix this. /// </summary> public Rect Rectangle { get { double l, t, w, h; if ( rectangleLeft <= rectangleRight) { l = rectangleLeft; w = rectangleRight - rectangleLeft; } else { l = rectangleRight; w = rectangleLeft - rectangleRight; } if ( rectangleTop <= rectangleBottom ) { t = rectangleTop; h = rectangleBottom - rectangleTop; } else { t = rectangleBottom; h = rectangleTop - rectangleBottom; } return new Rect(l, t, w, h); } } public double Left { get { return rectangleLeft; } set { rectangleLeft = value; } } public double Top { get { return rectangleTop; } set { rectangleTop = value; } } public double Right { get { return rectangleRight; } set { rectangleRight = value; } } public double Bottom { get { return rectangleBottom; } set { rectangleBottom = value; } } #endregion Properties #region Overrides /// <summary> /// Get number of handles /// </summary> public override int HandleCount { get { return 8; } } /// <summary> /// Get handle point by 1-based number /// </summary> public override Point GetHandle(int handleNumber) { double x, y, xCenter, yCenter; xCenter = (rectangleRight + rectangleLeft) / 2; yCenter = (rectangleBottom + rectangleTop) / 2; x = rectangleLeft; y = rectangleTop; switch (handleNumber) { case 1: x = rectangleLeft; y = rectangleTop; break; case 2: x = xCenter; y = rectangleTop; break; case 3: x = rectangleRight; y = rectangleTop; break; case 4: x = rectangleRight; y = yCenter; break; case 5: x = rectangleRight; y = rectangleBottom; break; case 6: x = xCenter; y = rectangleBottom; break; case 7: x = rectangleLeft; y = rectangleBottom; break; case 8: x = rectangleLeft; y = yCenter; break; } return new Point(x, y); } /// <summary> /// Hit test. /// Return value: -1 - no hit /// 0 - hit anywhere /// > 1 - handle number /// </summary> public override int MakeHitTest(Point point) { if (IsSelected) { for (int i = 1; i <= HandleCount; i++) { if (GetHandleRectangle(i).Contains(point)) return i; } } if (Contains(point)) return 0; return -1; } /// <summary> /// Get cursor for the handle /// </summary> public override Cursor GetHandleCursor(int handleNumber) { switch (handleNumber) { case 1: return Cursors.SizeNWSE; case 2: return Cursors.SizeNS; case 3: return Cursors.SizeNESW; case 4: return Cursors.SizeWE; case 5: return Cursors.SizeNWSE; case 6: return Cursors.SizeNS; case 7: return Cursors.SizeNESW; case 8: return Cursors.SizeWE; default: return HelperFunctions.DefaultCursor; } } /// <summary> /// Move handle to new point (resizing) /// </summary> public override void MoveHandleTo(Point point, int handleNumber) { switch (handleNumber) { case 1: rectangleLeft = point.X; rectangleTop = point.Y; break; case 2: rectangleTop = point.Y; break; case 3: rectangleRight = point.X; rectangleTop = point.Y; break; case 4: rectangleRight = point.X; break; case 5: rectangleRight = point.X; rectangleBottom = point.Y; break; case 6: rectangleBottom = point.Y; break; case 7: rectangleLeft = point.X; rectangleBottom = point.Y; break; case 8: rectangleLeft = point.X; break; } RefreshDrawing(); } /// <summary> /// Test whether object intersects with rectangle /// </summary> public override bool IntersectsWith(Rect rectangle) { return Rectangle.IntersectsWith(rectangle); } /// <summary> /// Move object by an amount /// </summary> public override void MoveBy(double deltaX, double deltaY) { rectangleLeft += deltaX; rectangleRight += deltaX; rectangleTop += deltaY; rectangleBottom += deltaY; RefreshDrawing(); } /// <summary> /// Move object to a location /// </summary> public override void MoveTo(Point p) { double halfW = Math.Abs(rectangleRight - rectangleLeft)/2; double halfH = Math.Abs(rectangleTop - rectangleBottom)/2; rectangleLeft = p.X - halfW; rectangleRight = p.X + halfW; rectangleTop = p.Y - halfH; rectangleBottom = p.Y + halfH; RefreshDrawing(); } /// <summary> /// Normalize rectangle /// </summary> public override void Normalize() { if ( rectangleLeft > rectangleRight ) { double tmp = rectangleLeft; rectangleLeft = rectangleRight; rectangleRight = tmp; } if ( rectangleTop > rectangleBottom ) { double tmp = rectangleTop; rectangleTop = rectangleBottom; rectangleBottom = tmp; } } #endregion Overrides } }
// 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.Linq; using System.Text; using Xunit; namespace System.Tests { public static class BitConverterTests { [Fact] public static unsafe void IsLittleEndian() { short s = 1; Assert.Equal(BitConverter.IsLittleEndian, *((byte*)&s) == 1); } [Fact] public static void ValueArgumentNull() { AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToBoolean(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToChar(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToDouble(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt16(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt32(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt64(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToSingle(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt16(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt32(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt64(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null)); AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0)); AssertExtensions.Throws<ArgumentNullException>("value", null /* param name varies in NETFX */, () => BitConverter.ToString(null, 0, 0)); } [Fact] public static void StartIndexBeyondLength() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 8)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 9)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 8)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 9)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 5)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 8)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 9)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(new byte[1], 0, -1)); } [Fact] public static void StartIndexPlusNeededLengthTooLong() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[0], 0)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToChar(new byte[2], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToDouble(new byte[8], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToInt16(new byte[2], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToInt32(new byte[4], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToInt64(new byte[8], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToSingle(new byte[4], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToUInt16(new byte[2], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToUInt32(new byte[4], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToUInt64(new byte[8], 1)); AssertExtensions.Throws<ArgumentException>("value", null, () => BitConverter.ToString(new byte[2], 1, 2)); } [Fact] public static void DoubleToInt64Bits() { double input = 123456.3234; long result = BitConverter.DoubleToInt64Bits(input); Assert.Equal(4683220267154373240L, result); double roundtripped = BitConverter.Int64BitsToDouble(result); Assert.Equal(input, roundtripped); } [Fact] public static void RoundtripBoolean() { byte[] bytes = BitConverter.GetBytes(true); Assert.Equal(1, bytes.Length); Assert.Equal(1, bytes[0]); Assert.True(BitConverter.ToBoolean(bytes, 0)); bytes = BitConverter.GetBytes(false); Assert.Equal(1, bytes.Length); Assert.Equal(0, bytes[0]); Assert.False(BitConverter.ToBoolean(bytes, 0)); } [Fact] public static void RoundtripChar() { char input = 'A'; byte[] expected = { 0x41, 0 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToChar, input, expected); } [Fact] public static void RoundtripDouble() { double input = 123456.3234; byte[] expected = { 0x78, 0x7a, 0xa5, 0x2c, 0x05, 0x24, 0xfe, 0x40 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToDouble, input, expected); } [Fact] public static void RoundtripSingle() { float input = 8392.34f; byte[] expected = { 0x5c, 0x21, 0x03, 0x46 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToSingle, input, expected); } [Fact] public static void RoundtripInt16() { short input = 0x1234; byte[] expected = { 0x34, 0x12 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt16, input, expected); } [Fact] public static void RoundtripInt32() { int input = 0x12345678; byte[] expected = { 0x78, 0x56, 0x34, 0x12 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt32, input, expected); } [Fact] public static void RoundtripInt64() { long input = 0x0123456789abcdef; byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt64, input, expected); } [Fact] public static void RoundtripUInt16() { ushort input = 0x1234; byte[] expected = { 0x34, 0x12 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt16, input, expected); } [Fact] public static void RoundtripUInt32() { uint input = 0x12345678; byte[] expected = { 0x78, 0x56, 0x34, 0x12 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt32, input, expected); } [Fact] public static void RoundtripUInt64() { ulong input = 0x0123456789abcdef; byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 }; VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt64, input, expected); } [Fact] public static void RoundtripString() { byte[] bytes = { 0x12, 0x34, 0x56, 0x78, 0x9a }; Assert.Equal("12-34-56-78-9A", BitConverter.ToString(bytes)); Assert.Equal("56-78-9A", BitConverter.ToString(bytes, 2)); Assert.Equal("56", BitConverter.ToString(bytes, 2, 1)); Assert.Same(string.Empty, BitConverter.ToString(new byte[0])); Assert.Same(string.Empty, BitConverter.ToString(new byte[3], 1, 0)); } [Fact] public static void ToString_ByteArray_Long() { byte[] bytes = Enumerable.Range(0, 256 * 4).Select(i => unchecked((byte)i)).ToArray(); string expected = string.Join("-", bytes.Select(b => b.ToString("X2"))); Assert.Equal(expected, BitConverter.ToString(bytes)); Assert.Equal(expected.Substring(3, expected.Length - 6), BitConverter.ToString(bytes, 1, bytes.Length - 2)); } [Fact] public static void ToString_ByteArrayTooLong_Throws() { byte[] arr; try { arr = new byte[int.MaxValue / 3 + 1]; } catch (OutOfMemoryException) { // Exit out of the test if we don't have an enough contiguous memory // available to create a big enough array. return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(arr)); } private static void VerifyRoundtrip<TInput>(Func<TInput, byte[]> getBytes, Func<byte[], int, TInput> convertBack, TInput input, byte[] expectedBytes) { byte[] bytes = getBytes(input); Assert.Equal(expectedBytes.Length, bytes.Length); if (!BitConverter.IsLittleEndian) { Array.Reverse(expectedBytes); } Assert.Equal(expectedBytes, bytes); Assert.Equal(input, convertBack(bytes, 0)); // Also try unaligned startIndex byte[] longerBytes = new byte[bytes.Length + 1]; longerBytes[0] = 0; Array.Copy(bytes, 0, longerBytes, 1, bytes.Length); Assert.Equal(input, convertBack(longerBytes, 1)); } [Fact] public static void SingleToInt32Bits() { float input = 12345.63f; int result = BitConverter.SingleToInt32Bits(input); Assert.Equal(1178658437, result); float roundtripped = BitConverter.Int32BitsToSingle(result); Assert.Equal(input, roundtripped); } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using OpenMetaverse.Imaging; using OpenMetaverse.Assets; namespace OpenMetaverse.GUI { /// <summary> /// PictureBox GUI component for displaying a client's mini-map /// </summary> public class MiniMap : PictureBox { private static Brush BG_COLOR = Brushes.Navy; private UUID _MapImageID; private GridClient _Client; private Image _MapLayer; //warning CS0414: The private field `OpenMetaverse.GUI.MiniMap._MousePosition' is assigned but its value is never used //private Point _MousePosition; ToolTip _ToolTip; /// <summary> /// Gets or sets the GridClient associated with this control /// </summary> public GridClient Client { get { return _Client; } set { if (value != null) InitializeClient(value); } } /// <summary> /// PictureBox control for an unspecified client's mini-map /// </summary> public MiniMap() { this.BorderStyle = BorderStyle.FixedSingle; this.SizeMode = PictureBoxSizeMode.Zoom; } /// <summary> /// PictureBox control for the specified client's mini-map /// </summary> public MiniMap(GridClient client) : this () { InitializeClient(client); _ToolTip = new ToolTip(); _ToolTip.Active = true; _ToolTip.AutomaticDelay = 1; this.MouseHover += new System.EventHandler(MiniMap_MouseHover); this.MouseMove += new MouseEventHandler(MiniMap_MouseMove); } /// <summary>Sets the map layer to the specified bitmap image</summary> /// <param name="mapImage"></param> public void SetMapLayer(Bitmap mapImage) { if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { SetMapLayer(mapImage); }); else { if (mapImage == null) { Bitmap bmp = new Bitmap(256, 256); Graphics g = Graphics.FromImage(bmp); g.Clear(this.BackColor); g.FillRectangle(BG_COLOR, 0f, 0f, 256f, 256f); g.DrawImage(bmp, 0, 0); _MapLayer = bmp; } else _MapLayer = mapImage; } } private void InitializeClient(GridClient client) { _Client = client; _Client.Grid.CoarseLocationUpdate += Grid_CoarseLocationUpdate; _Client.Network.SimChanged += Network_OnCurrentSimChanged; } void Grid_CoarseLocationUpdate(object sender, CoarseLocationUpdateEventArgs e) { UpdateMiniMap(e.Simulator); } private void UpdateMiniMap(Simulator sim) { if (!this.IsHandleCreated) return; if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { UpdateMiniMap(sim); }); else { if (_MapLayer == null) SetMapLayer(null); Bitmap bmp = (Bitmap)_MapLayer.Clone(); Graphics g = Graphics.FromImage(bmp); Vector3 myCoarsePos; if (!sim.AvatarPositions.TryGetValue(Client.Self.AgentID, out myCoarsePos)) return; int i = 0; _Client.Network.CurrentSim.AvatarPositions.ForEach( delegate(KeyValuePair<UUID, Vector3> coarse) { int x = (int)coarse.Value.X; int y = 255 - (int)coarse.Value.Y; if (coarse.Key == Client.Self.AgentID) { g.FillEllipse(Brushes.Yellow, x - 5, y - 5, 10, 10); g.DrawEllipse(Pens.Khaki, x - 5, y - 5, 10, 10); } else { Pen penColor; Brush brushColor; if (Client.Network.CurrentSim.ObjectsAvatars.Find(delegate(Avatar av) { return av.ID == coarse.Key; }) != null) { brushColor = Brushes.PaleGreen; penColor = Pens.Green; } else { brushColor = Brushes.LightGray; penColor = Pens.Gray; } if (myCoarsePos.Z - coarse.Value.Z > 1) { Point[] points = new Point[3] { new Point(x - 6, y - 6), new Point(x + 6, y - 6), new Point(x, y + 6) }; g.FillPolygon(brushColor, points); g.DrawPolygon(penColor, points); } else if (myCoarsePos.Z - coarse.Value.Z < -1) { Point[] points = new Point[3] { new Point(x - 6, y + 6), new Point(x + 6, y + 6), new Point(x, y - 6) }; g.FillPolygon(brushColor, points); g.DrawPolygon(penColor, points); } else { g.FillEllipse(brushColor, x - 5, y - 5, 10, 10); g.DrawEllipse(penColor, x - 5, y - 5, 10, 10); } } i++; } ); g.DrawImage(bmp, 0, 0); this.Image = bmp; } } void MiniMap_MouseHover(object sender, System.EventArgs e) { _ToolTip.SetToolTip(this, "test"); _ToolTip.Show("test", this); //TODO: tooltip popup with closest avatar's name, if within range } void MiniMap_MouseMove(object sender, MouseEventArgs e) { _ToolTip.Hide(this); //warning CS0414: The private field `OpenMetaverse.GUI.MiniMap._MousePosition' is assigned but its value is never used //_MousePosition = e.Location; } void Network_OnCurrentSimChanged(object sender, SimChangedEventArgs e) { if (_Client.Network.Connected) return; GridRegion region; if (Client.Grid.GetGridRegion(Client.Network.CurrentSim.Name, GridLayerType.Objects, out region)) { SetMapLayer(null); _MapImageID = region.MapImageID; ManagedImage nullImage; Client.Assets.RequestImage(_MapImageID, ImageType.Baked, delegate(TextureRequestState state, AssetTexture asset) { if(state == TextureRequestState.Finished) OpenJPEG.DecodeToImage(asset.AssetData, out nullImage, out _MapLayer); }); } } } }
// 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: Pointer Type to a EEType in the runtime. ** ** ===========================================================*/ using System.Runtime; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using EEType = Internal.Runtime.EEType; using EETypeRef = Internal.Runtime.EETypeRef; namespace System { [StructLayout(LayoutKind.Sequential)] internal unsafe struct EETypePtr : IEquatable<EETypePtr> { private EEType* _value; public EETypePtr(IntPtr value) { _value = (EEType*)value; } internal EEType* ToPointer() { return _value; } public override bool Equals(Object obj) { if (obj is EETypePtr) { return this == (EETypePtr)obj; } return false; } public bool Equals(EETypePtr p) { return this == p; } public static bool operator ==(EETypePtr value1, EETypePtr value2) { if (value1.IsNull) return value2.IsNull; else if (value2.IsNull) return false; else return RuntimeImports.AreTypesEquivalent(value1, value2); } public static bool operator !=(EETypePtr value1, EETypePtr value2) { return !(value1 == value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return (int)_value->HashCode; } // // Faster version of Equals for use on EETypes that are known not to be null and where the "match" case is the hot path. // public bool FastEquals(EETypePtr other) { Debug.Assert(!this.IsNull); Debug.Assert(!other.IsNull); // Fast check for raw equality before making call to helper. if (this.RawValue == other.RawValue) return true; return RuntimeImports.AreTypesEquivalent(this, other); } // Caution: You cannot safely compare RawValue's as RH does NOT unify EETypes. Use the == or Equals() methods exposed by EETypePtr itself. internal IntPtr RawValue { get { return (IntPtr)_value; } } internal bool IsNull { get { return _value == null; } } internal bool IsArray { get { return _value->IsArray; } } internal bool IsSzArray { get { return _value->IsSzArray; } } internal bool IsPointer { get { return _value->IsPointerType; } } internal bool IsByRef { get { return _value->IsByRefType; } } internal bool IsValueType { get { return _value->IsValueType; } } internal bool IsString { get { return _value->IsString; } } /// <summary> /// Warning! UNLIKE the similarly named Reflection api, this method also returns "true" for Enums. /// </summary> internal bool IsPrimitive { get { RuntimeImports.RhCorElementType et = CorElementType; return ((et >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN) && (et <= RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_I) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_U); } } internal bool IsEnum { get { // Q: When is an enum type a constructed generic type? // A: When it's nested inside a generic type. if (!(IsDefType)) return false; EETypePtr baseType = this.BaseType; return baseType == EETypePtr.EETypePtrOf<Enum>(); } } /// <summary> /// Gets a value indicating whether this is a generic type definition (an uninstantiated generic type). /// </summary> internal bool IsGenericTypeDefinition { get { return _value->IsGenericTypeDefinition; } } /// <summary> /// Gets a value indicating whether this is an instantiated generic type. /// </summary> internal bool IsGeneric { get { return _value->IsGeneric; } } internal GenericArgumentCollection Instantiation { get { return new GenericArgumentCollection(_value->GenericArity, _value->GenericArguments); } } internal EETypePtr GenericDefinition { get { return new EETypePtr((IntPtr)_value->GenericDefinition); } } /// <summary> /// Gets a value indicating whether this is a class, a struct, an enum, or an interface. /// </summary> internal bool IsDefType { get { return !_value->IsParameterizedType; } } internal bool IsDynamicType { get { return _value->IsDynamicType; } } internal bool IsInterface { get { return _value->IsInterface; } } internal bool IsAbstract { get { return _value->IsAbstract; } } internal bool IsByRefLike { get { return _value->IsByRefLike; } } internal bool IsNullable { get { return _value->IsNullable; } } internal bool HasCctor { get { return _value->HasCctor; } } internal EETypePtr NullableType { get { return new EETypePtr((IntPtr)_value->NullableType); } } internal EETypePtr ArrayElementType { get { return new EETypePtr((IntPtr)_value->RelatedParameterType); } } internal int ArrayRank { get { return _value->ArrayRank; } } internal InterfaceCollection Interfaces { get { return new InterfaceCollection(_value); } } internal EETypePtr BaseType { get { if (IsArray) return EETypePtr.EETypePtrOf<Array>(); if (IsPointer || IsByRef) return new EETypePtr(default(IntPtr)); EETypePtr baseEEType = new EETypePtr((IntPtr)_value->NonArrayBaseType); return baseEEType; } } internal ushort ComponentSize { get { return _value->ComponentSize; } } internal uint BaseSize { get { return _value->BaseSize; } } // Has internal gc pointers. internal bool HasPointers { get { return _value->HasGCPointers; } } internal uint ValueTypeSize { get { return _value->ValueTypeSize; } } internal RuntimeImports.RhCorElementType CorElementType { get { Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_I1 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1); Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_R8 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8); return (RuntimeImports.RhCorElementType)_value->CorElementType; } } internal RuntimeImports.RhCorElementTypeInfo CorElementTypeInfo { get { RuntimeImports.RhCorElementType corElementType = this.CorElementType; return RuntimeImports.GetRhCorElementTypeInfo(corElementType); } } [Intrinsic] internal static EETypePtr EETypePtrOf<T>() { // Compilers are required to provide a low level implementation of this method. // This can be achieved by optimizing away the reflection part of this implementation // by optimizing typeof(!!0).TypeHandle into "ldtoken !!0", or by // completely replacing the body of this method. return typeof(T).TypeHandle.ToEETypePtr(); } public struct InterfaceCollection { private EEType* _value; internal InterfaceCollection(EEType* value) { _value = value; } public int Count { get { return _value->NumInterfaces; } } public EETypePtr this[int index] { get { Debug.Assert((uint)index < _value->NumInterfaces); EEType* interfaceType = _value->InterfaceMap[index].InterfaceType; return new EETypePtr((IntPtr)interfaceType); } } } public struct GenericArgumentCollection { private EETypeRef* _arguments; private uint _argumentCount; internal GenericArgumentCollection(uint argumentCount, EETypeRef* arguments) { _argumentCount = argumentCount; _arguments = arguments; } public int Length { get { return (int)_argumentCount; } } public EETypePtr this[int index] { get { Debug.Assert((uint)index < _argumentCount); return new EETypePtr((IntPtr)_arguments[index].Value); } } } } }
#region Apache License // // 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. // #endregion using System.Collections; using log4net.Core; using log4net.Repository.Hierarchy; using log4net.Tests.Appender; using NUnit.Framework; namespace log4net.Tests.Hierarchy { /// <summary> /// Used for internal unit testing the <see cref="Logger"/> class. /// </summary> /// <remarks> /// Internal unit test. Uses the NUnit test harness. /// </remarks> [TestFixture] public class LoggerTest { private Logger log; // A short message. private static string MSG = "M"; /// <summary> /// Any initialization that happens before each test can /// go here /// </summary> [SetUp] public void SetUp() { } /// <summary> /// Any steps that happen after each test go here /// </summary> [TearDown] public void TearDown() { // Regular users should not use the clear method lightly! LogManager.GetRepository().ResetConfiguration(); LogManager.GetRepository().Shutdown(); ((Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Clear(); } /// <summary> /// Add an appender and see if it can be retrieved. /// </summary> [Test] public void TestAppender1() { log = (Logger)LogManager.GetLogger("test").Logger; CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender1"; log.AddAppender(a1); IEnumerator enumAppenders = ((IEnumerable)log.Appenders).GetEnumerator(); Assert.IsTrue(enumAppenders.MoveNext()); CountingAppender aHat = (CountingAppender)enumAppenders.Current; Assert.AreEqual(a1, aHat); } /// <summary> /// Add an appender X, Y, remove X and check if Y is the only /// remaining appender. /// </summary> [Test] public void TestAppender2() { CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender2.1"; CountingAppender a2 = new CountingAppender(); a2.Name = "testAppender2.2"; log = (Logger)LogManager.GetLogger("test").Logger; log.AddAppender(a1); log.AddAppender(a2); CountingAppender aHat = (CountingAppender)log.GetAppender(a1.Name); Assert.AreEqual(a1, aHat); aHat = (CountingAppender)log.GetAppender(a2.Name); Assert.AreEqual(a2, aHat); log.RemoveAppender("testAppender2.1"); IEnumerator enumAppenders = ((IEnumerable)log.Appenders).GetEnumerator(); Assert.IsTrue(enumAppenders.MoveNext()); aHat = (CountingAppender)enumAppenders.Current; Assert.AreEqual(a2, aHat); Assert.IsTrue(!enumAppenders.MoveNext()); aHat = (CountingAppender)log.GetAppender(a2.Name); Assert.AreEqual(a2, aHat); } /// <summary> /// Test if logger a.b inherits its appender from a. /// </summary> [Test] public void TestAdditivity1() { Logger a = (Logger)LogManager.GetLogger("a").Logger; Logger ab = (Logger)LogManager.GetLogger("a.b").Logger; CountingAppender ca = new CountingAppender(); a.AddAppender(ca); a.Repository.Configured = true; Assert.AreEqual(ca.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(ca.Counter, 1); ab.Log(Level.Info, MSG, null); Assert.AreEqual(ca.Counter, 2); ab.Log(Level.Warn, MSG, null); Assert.AreEqual(ca.Counter, 3); ab.Log(Level.Error, MSG, null); Assert.AreEqual(ca.Counter, 4); } /// <summary> /// Test multiple additivity. /// </summary> [Test] public void TestAdditivity2() { Logger a = (Logger)LogManager.GetLogger("a").Logger; Logger ab = (Logger)LogManager.GetLogger("a.b").Logger; Logger abc = (Logger)LogManager.GetLogger("a.b.c").Logger; Logger x = (Logger)LogManager.GetLogger("x").Logger; CountingAppender ca1 = new CountingAppender(); CountingAppender ca2 = new CountingAppender(); a.AddAppender(ca1); abc.AddAppender(ca2); a.Repository.Configured = true; Assert.AreEqual(ca1.Counter, 0); Assert.AreEqual(ca2.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 1); Assert.AreEqual(ca2.Counter, 0); abc.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 2); Assert.AreEqual(ca2.Counter, 1); x.Log(Level.Debug, MSG, null); Assert.AreEqual(ca1.Counter, 2); Assert.AreEqual(ca2.Counter, 1); } /// <summary> /// Test additivity flag. /// </summary> [Test] public void TestAdditivity3() { Logger root = ((Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; Logger a = (Logger)LogManager.GetLogger("a").Logger; Logger ab = (Logger)LogManager.GetLogger("a.b").Logger; Logger abc = (Logger)LogManager.GetLogger("a.b.c").Logger; CountingAppender caRoot = new CountingAppender(); CountingAppender caA = new CountingAppender(); CountingAppender caABC = new CountingAppender(); root.AddAppender(caRoot); a.AddAppender(caA); abc.AddAppender(caABC); a.Repository.Configured = true; Assert.AreEqual(caRoot.Counter, 0); Assert.AreEqual(caA.Counter, 0); Assert.AreEqual(caABC.Counter, 0); ab.Additivity = false; a.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 0); abc.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 1); Assert.AreEqual(caA.Counter, 1); Assert.AreEqual(caABC.Counter, 1); } /// <summary> /// Test the ability to disable a level of message /// </summary> [Test] public void TestDisable1() { CountingAppender caRoot = new CountingAppender(); Logger root = ((Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; root.AddAppender(caRoot); Repository.Hierarchy.Hierarchy h = ((Repository.Hierarchy.Hierarchy)LogManager.GetRepository()); h.Threshold = Level.Info; h.Configured = true; Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 1); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 2); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 3); h.Threshold = Level.Warn; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 4); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 5); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); h.Threshold = Level.Off; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); } /// <summary> /// Tests the Exists method of the Logger class /// </summary> [Test] public void TestExists() { object a = LogManager.GetLogger("a"); object a_b = LogManager.GetLogger("a.b"); object a_b_c = LogManager.GetLogger("a.b.c"); object t; t = LogManager.Exists("xx"); Assert.IsNull(t); t = LogManager.Exists("a"); Assert.AreSame(a, t); t = LogManager.Exists("a.b"); Assert.AreSame(a_b, t); t = LogManager.Exists("a.b.c"); Assert.AreSame(a_b_c, t); } /// <summary> /// Tests the chained level for a hierarchy /// </summary> [Test] public void TestHierarchy1() { Repository.Hierarchy.Hierarchy h = new Repository.Hierarchy.Hierarchy(); h.Root.Level = Level.Error; Logger a0 = (Logger)h.GetLogger("a"); Assert.AreEqual("a", a0.Name); Assert.IsNull(a0.Level); Assert.AreSame(Level.Error, a0.EffectiveLevel); Logger a1 = (Logger)h.GetLogger("a"); Assert.AreSame(a0, a1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class DynamicChainTests { public static object[][] InvalidSignature3Cases { get; } = new object[][] { new object[] { X509ChainStatusFlags.NotSignatureValid, X509ChainStatusFlags.NoError, X509ChainStatusFlags.UntrustedRoot, }, new object[] { X509ChainStatusFlags.NoError, X509ChainStatusFlags.NotSignatureValid, X509ChainStatusFlags.UntrustedRoot, }, new object[] { X509ChainStatusFlags.NoError, X509ChainStatusFlags.NoError, X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.UntrustedRoot, }, new object[] { X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid, X509ChainStatusFlags.NoError, X509ChainStatusFlags.UntrustedRoot, }, new object[] { X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid, X509ChainStatusFlags.NotTimeValid, X509ChainStatusFlags.UntrustedRoot, }, new object[] { X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.NotTimeValid, X509ChainStatusFlags.NotTimeValid, X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid, }, }; [Theory] [MemberData(nameof(InvalidSignature3Cases))] public static void BuildInvalidSignatureTwice( X509ChainStatusFlags endEntityErrors, X509ChainStatusFlags intermediateErrors, X509ChainStatusFlags rootErrors) { TestDataGenerator.MakeTestChain3( out X509Certificate2 endEntityCert, out X509Certificate2 intermediateCert, out X509Certificate2 rootCert); X509Certificate2 TamperIfNeeded(X509Certificate2 input, X509ChainStatusFlags flags) { if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) { X509Certificate2 tampered = TamperSignature(input); input.Dispose(); return tampered; } return input; } DateTime RewindIfNeeded(DateTime input, X509Certificate2 cert, X509ChainStatusFlags flags) { if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) { return cert.NotBefore.AddMinutes(-1); } return input; } int expectedCount = 3; DateTime verificationTime = endEntityCert.NotBefore.AddMinutes(1); verificationTime = RewindIfNeeded(verificationTime, endEntityCert, endEntityErrors); verificationTime = RewindIfNeeded(verificationTime, intermediateCert, intermediateErrors); verificationTime = RewindIfNeeded(verificationTime, rootCert, rootErrors); // Replace the certs for the scenario. endEntityCert = TamperIfNeeded(endEntityCert, endEntityErrors); intermediateCert = TamperIfNeeded(intermediateCert, intermediateErrors); rootCert = TamperIfNeeded(rootCert, rootErrors); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // For the lower levels, turn NotSignatureValid into PartialChain, // and clear all errors at higher levels. if ((endEntityErrors & X509ChainStatusFlags.NotSignatureValid) != 0) { expectedCount = 1; endEntityErrors &= ~X509ChainStatusFlags.NotSignatureValid; endEntityErrors |= X509ChainStatusFlags.PartialChain; intermediateErrors = X509ChainStatusFlags.NoError; rootErrors = X509ChainStatusFlags.NoError; } else if ((intermediateErrors & X509ChainStatusFlags.NotSignatureValid) != 0) { expectedCount = 2; intermediateErrors &= ~X509ChainStatusFlags.NotSignatureValid; intermediateErrors |= X509ChainStatusFlags.PartialChain; rootErrors = X509ChainStatusFlags.NoError; } else if ((rootErrors & X509ChainStatusFlags.NotSignatureValid) != 0) { rootErrors &= ~X509ChainStatusFlags.NotSignatureValid; // On 10.12 this is just UntrustedRoot. // On 10.13+ it becomes PartialChain, and UntrustedRoot goes away. if (PlatformDetection.IsMacOsHighSierraOrHigher) { rootErrors &= ~X509ChainStatusFlags.UntrustedRoot; rootErrors |= X509ChainStatusFlags.PartialChain; } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Windows only reports NotTimeValid on the start-of-chain (end-entity in this case) // If it were possible in this suite to get only a higher-level cert as NotTimeValid // without the lower one, that would have resulted in NotTimeNested. intermediateErrors &= ~X509ChainStatusFlags.NotTimeValid; rootErrors &= ~X509ChainStatusFlags.NotTimeValid; } X509ChainStatusFlags expectedAllErrors = endEntityErrors | intermediateErrors | rootErrors; // If PartialChain or UntrustedRoot are the only remaining errors, the chain will succeed. const X509ChainStatusFlags SuccessCodes = X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain; bool expectSuccess = (expectedAllErrors & ~SuccessCodes) == 0; using (endEntityCert) using (intermediateCert) using (rootCert) using (ChainHolder chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.VerificationTime = verificationTime; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.ExtraStore.Add(intermediateCert); chain.ChainPolicy.ExtraStore.Add(rootCert); chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority; int i = 0; void CheckChain() { i++; bool valid = chain.Build(endEntityCert); if (expectSuccess) { Assert.True(valid, $"Chain build on iteration {i}"); } else { Assert.False(valid, $"Chain build on iteration {i}"); } Assert.Equal(expectedCount, chain.ChainElements.Count); Assert.Equal(expectedAllErrors, chain.AllStatusFlags()); Assert.Equal(endEntityErrors, chain.ChainElements[0].AllStatusFlags()); if (expectedCount > 2) { Assert.Equal(rootErrors, chain.ChainElements[2].AllStatusFlags()); } if (expectedCount > 1) { Assert.Equal(intermediateErrors, chain.ChainElements[1].AllStatusFlags()); } chainHolder.DisposeChainElements(); } CheckChain(); CheckChain(); } } [Fact] public static void TestInvalidAia() { using (RSA key = RSA.Create()) { CertificateRequest rootReq = new CertificateRequest( "CN=Root", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); rootReq.CertificateExtensions.Add( new X509BasicConstraintsExtension(true, false, 0, true)); CertificateRequest certReq = new CertificateRequest( "CN=test", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); certReq.CertificateExtensions.Add( new X509BasicConstraintsExtension(false, false, 0, false)); certReq.CertificateExtensions.Add( new X509Extension( "1.3.6.1.5.5.7.1.1", new byte[] { 5 }, critical: false)); DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddDays(-1); DateTimeOffset notAfter = notBefore.AddDays(30); using (X509Certificate2 root = rootReq.CreateSelfSigned(notBefore, notAfter)) using (X509Certificate2 ee = certReq.Create(root, notBefore, notAfter, root.GetSerialNumber())) { X509Chain chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; Assert.False(chain.Build(ee)); Assert.Equal(1, chain.ChainElements.Count); Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags()); } } } [Fact] // macOS (10.14) will not load certificates with NumericString in their subject // if the 0x12 (NumericString) is changed to 0x13 (PrintableString) then the cert // import doesn't fail. [PlatformSpecific(~TestPlatforms.OSX)] public static void VerifyNumericStringSubject() { X500DistinguishedName dn = new X500DistinguishedName( "30283117301506052901020203120C313233203635342037383930310D300B0603550403130454657374".HexToByteArray()); using (RSA key = RSA.Create()) { CertificateRequest req = new CertificateRequest( dn, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = req.CreateSelfSigned(now.AddDays(-1), now.AddDays(1))) { Assert.Equal("CN=Test, OID.1.1.1.2.2.3=123 654 7890", cert.Subject); } } } [Theory] // Test with intermediate certificates in CustomTrustStore [InlineData(true, X509ChainStatusFlags.NoError)] // Test with ExtraStore containing root certificate [InlineData(false, X509ChainStatusFlags.UntrustedRoot)] public static void CustomRootTrustDoesNotTrustIntermediates( bool saveAllInCustomTrustStore, X509ChainStatusFlags chainFlags) { TestDataGenerator.MakeTestChain3( out X509Certificate2 endEntityCert, out X509Certificate2 intermediateCert, out X509Certificate2 rootCert); using (endEntityCert) using (intermediateCert) using (rootCert) using (ChainHolder chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(intermediateCert); if (saveAllInCustomTrustStore) { chain.ChainPolicy.CustomTrustStore.Add(rootCert); } else { chain.ChainPolicy.ExtraStore.Add(rootCert); } Assert.Equal(saveAllInCustomTrustStore, chain.Build(endEntityCert)); Assert.Equal(3, chain.ChainElements.Count); Assert.Equal(chainFlags, chain.AllStatusFlags()); } } [Fact] public static void CustomTrustModeWithNoCustomTrustCerts() { TestDataGenerator.MakeTestChain3( out X509Certificate2 endEntityCert, out X509Certificate2 intermediateCert, out X509Certificate2 rootCert); using (endEntityCert) using (intermediateCert) using (rootCert) using (ChainHolder chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = endEntityCert.NotBefore.AddSeconds(1); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; Assert.False(chain.Build(endEntityCert)); Assert.Equal(1, chain.ChainElements.Count); Assert.Equal(X509ChainStatusFlags.PartialChain, chain.AllStatusFlags()); } } private static X509Certificate2 TamperSignature(X509Certificate2 input) { byte[] cert = input.RawData; cert[cert.Length - 1] ^= 0xFF; return new X509Certificate2(cert); } } }
using System; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Tests { [TestFixture] public class ECEncodingTest : SimpleTest { public override string Name { get { return "ECEncodingTest"; } } /** J.4.7 An Example with m = 304 */ private int m = 304; /** f = 010000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000807 */ private int k1 = 1; private int k2 = 2; private int k3 = 11; private static readonly byte[] hexa = {(byte)0xFD, 0x0D, 0x69, 0x31, 0x49, (byte)0xA1, 0x18, (byte)0xF6, 0x51 , (byte)0xE6, (byte)0xDC, (byte)0xE6, (byte)0x80, 0x20, (byte)0x85, 0x37, 0x7E, 0x5F, (byte)0x88, 0x2D, 0x1B, 0x51 , 0x0B, 0x44, 0x16, 0x00, 0x74, (byte)0xC1, 0x28, (byte)0x80, 0x78, 0x36, 0x5A, 0x03 , (byte)0x96, (byte)0xC8, (byte)0xE6, (byte)0x81}; private static readonly byte[] hexb = {(byte)0xBD, (byte)0xDB, (byte)0x97, (byte)0xE5, (byte)0x55 , (byte)0xA5, (byte)0x0A, (byte)0x90, (byte)0x8E, (byte)0x43, (byte)0xB0 , (byte)0x1C, (byte)0x79, (byte)0x8E, (byte)0xA5, (byte)0xDA, (byte)0xA6 , (byte)0x78, (byte)0x8F, (byte)0x1E, (byte)0xA2, (byte)0x79 , (byte)0x4E, (byte)0xFC, (byte)0xF5, (byte)0x71, (byte)0x66, (byte)0xB8 , (byte)0xC1, (byte)0x40, (byte)0x39, (byte)0x60, (byte)0x1E , (byte)0x55, (byte)0x82, (byte)0x73, (byte)0x40, (byte)0xBE}; private static readonly IBigInteger a = new BigInteger(1, hexa); private static readonly IBigInteger b = new BigInteger(1, hexb); /** Base point G (with point compression) */ private byte[] enc = {0x02, 0x19, 0x7B, 0x07, (byte)0x84, 0x5E, (byte)0x9B, (byte)0xE2, (byte)0xD9, 0x6A, (byte)0xDB, 0x0F , 0x5F, 0x3C, 0x7F, 0x2C, (byte)0xFF, (byte)0xBD, 0x7A, 0x3E, (byte)0xB8, (byte)0xB6, (byte)0xFE, (byte)0xC3, 0x5C, 0x7F, (byte)0xD6, 0x7F, 0x26, (byte)0xDD, (byte)0xF6 , 0x28, 0x5A, 0x64, 0x4F, 0x74, 0x0A, 0x26, 0x14}; private void doTestPointCompression() { ECCurve curve = new F2MCurve(m, k1, k2, k3, a, b); curve.DecodePoint(enc); int[] ks = new int[3]; ks[0] = k3; ks[1] = k2; ks[2] = k1; } public override void PerformTest() { byte[] ecParams = Hex.Decode("3081C8020101302806072A8648CE3D0101021D00D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF303C041C68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43041C2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B0439040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD021D00D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F020101"); doTestParams(ecParams, true); doTestParams(ecParams, false); ecParams = Hex.Decode("3081C8020101302806072A8648CE3D0101021D00D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF303C041C56E6C7E4F11A7B4B961A4DCB5BD282EB22E42E9BCBE3E7B361F18012041C4BE3E7B361F18012F2353D22975E02D8D05D2C6F3342DD8F57D4C76F0439048D127A0C27E0DE207ED3B7FB98F83C8BD5A2A57C827F4B97874DEB2C1BAEB0C006958CE61BB1FC81F5389E288CB3E86E2ED91FB47B08FCCA021D00D7C134AA264366862A18302575D11A5F7AABFBA3D897FF5CA727AF53020101"); doTestParams(ecParams, true); doTestParams(ecParams, false); ecParams = Hex.Decode("30820142020101303c06072a8648ce3d0101023100fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff3066043100fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc043100b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef046104aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab73617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f023100ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973020101"); doTestParams(ecParams, true); doTestParams(ecParams, false); doTestPointCompression(); } private void doTestParams( byte[] ecParameterEncoded, bool compress) { // string keyStorePass = "myPass"; Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(ecParameterEncoded); X9ECParameters x9 = new X9ECParameters(seq); IAsymmetricCipherKeyPair kp = null; bool success = false; while (!success) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); // kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); ECDomainParameters ecParams = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom())); kp = kpg.GenerateKeyPair(); // The very old Problem... we need a certificate chain to // save a private key... ECPublicKeyParameters pubKey = (ECPublicKeyParameters) kp.Public; if (!compress) { //pubKey.setPointFormat("UNCOMPRESSED"); pubKey = SetPublicUncompressed(pubKey, false); } byte[] x = pubKey.Q.X.ToBigInteger().ToByteArrayUnsigned(); byte[] y = pubKey.Q.Y.ToBigInteger().ToByteArrayUnsigned(); if (x.Length == y.Length) { success = true; } } // The very old Problem... we need a certificate chain to // save a private key... X509CertificateEntry[] chain = new X509CertificateEntry[] { new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress)) }; // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(null, keyStorePass.ToCharArray()); Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build(); keyStore.SetCertificateEntry("ECCert", chain[0]); ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters) kp.Private; keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain); // Test ec sign / verify ECPublicKeyParameters pub = (ECPublicKeyParameters) kp.Public; // string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded())); byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded(); string oldPrivateKey = Hex.ToHexString(oldPrivateKeyBytes); // string oldPublicKey = new string(Hex.encode(pub.getEncoded())); byte[] oldPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded(); string oldPublicKey = Hex.ToHexString(oldPublicKeyBytes); ECPrivateKeyParameters newKey = (ECPrivateKeyParameters) keyStore.GetKey("ECPrivKey").Key; ECPublicKeyParameters newPubKey = (ECPublicKeyParameters) keyStore.GetCertificate("ECCert").Certificate.GetPublicKey(); if (!compress) { // TODO Private key compression? //newKey.setPointFormat("UNCOMPRESSED"); //newPubKey.setPointFormat("UNCOMPRESSED"); newPubKey = SetPublicUncompressed(newPubKey, false); } // string newPrivateKey = new string(Hex.encode(newKey.getEncoded())); byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded(); string newPrivateKey = Hex.ToHexString(newPrivateKeyBytes); // string newPublicKey = new string(Hex.encode(newPubKey.getEncoded())); byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded(); string newPublicKey = Hex.ToHexString(newPublicKeyBytes); if (!oldPrivateKey.Equals(newPrivateKey)) // if (!privateECKey.Equals(newKey)) { Fail("failed private key comparison"); } if (!oldPublicKey.Equals(newPublicKey)) // if (!pub.Equals(newPubKey)) { Fail("failed public key comparison"); } } /** * Create a self signed cert for our software emulation * * @param kp * is the keypair for our certificate * @return a self signed cert for our software emulation * @throws InvalidKeyException * on error * @throws SignatureException * on error */ private X509Certificate GenerateSelfSignedSoftECCert( IAsymmetricCipherKeyPair kp, bool compress) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); ECPrivateKeyParameters privECKey = (ECPrivateKeyParameters) kp.Private; ECPublicKeyParameters pubECKey = (ECPublicKeyParameters) kp.Public; if (!compress) { // TODO Private key compression? //privECKey.setPointFormat("UNCOMPRESSED"); //pubECKey.setPointFormat("UNCOMPRESSED"); pubECKey = SetPublicUncompressed(pubECKey, false); } certGen.SetSignatureAlgorithm("ECDSAwithSHA1"); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name("CN=Software emul (EC Cert)")); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50000)); certGen.SetSubjectDN(new X509Name("CN=Software emul (EC Cert)")); certGen.SetPublicKey(pubECKey); return certGen.Generate(privECKey); } private ECPublicKeyParameters SetPublicUncompressed( ECPublicKeyParameters key, bool withCompression) { ECPoint p = key.Q; return new ECPublicKeyParameters( key.AlgorithmName, p.Curve.CreatePoint(p.X.ToBigInteger(), p.Y.ToBigInteger(), withCompression), key.Parameters); } public static void Main( string[] args) { RunTest(new ECEncodingTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
/* * nMQTT, a .Net MQTT v3 client implementation. * http://wiki.github.com/markallanson/nmqtt * * Copyright (c) 2009 Mark Allanson ([email protected]) & Contributors * * Licensed under the MIT License. You may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.opensource.org/licenses/mit-license.php */ using System; using Nmqtt; using Moq; using Xunit; namespace NmqttTests.SubscriptionsManager { public class SubscriptionsManagerTests { [Fact] public void Ctor() { var chMock = new Mock<IMqttConnectionHandler>(); var pubMock = new Mock<IPublishingManager>(); chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())); var sub = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); chMock.VerifyAll(); sub.Dispose(); } [Fact] public void SubscriptionRequestCreatesPendingSubscription() { var chMock = new Mock<IMqttConnectionHandler>(); var pubMock = new Mock<IPublishingManager>(); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); Assert.Equal(SubscriptionStatus.Pending, subs.GetSubscriptionsStatus(topic)); } [Fact] public void DisposeUnregistersMessageCallback() { var chMock = new Mock<IMqttConnectionHandler>(); var pubMock = new Mock<IPublishingManager>(); chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())); chMock.Setup(x => x.UnRegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())); var subMgr = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subMgr.Dispose(); chMock.VerifyAll(); } [Fact] public void SubscriptionRequestInvokesSend() { MqttSubscribeMessage subMsg = null; var pubMock = new Mock<IPublishingManager>(); var chMock = new Mock<IMqttConnectionHandler>(); // mock the call to register and save the callback for later. chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())); // mock the call to Send(), which should occur when the subscription manager tries to subscribe chMock.Setup(x => x.SendMessage(It.IsAny<MqttSubscribeMessage>())) .Callback((MqttMessage msg) => subMsg = (MqttSubscribeMessage)msg); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); chMock.VerifyAll(); // now check the message generated by the subscription manager was good - ie contain the topic at the specified qos Assert.Contains(topic, subMsg.Payload.Subscriptions.Keys); Assert.Equal(MqttQos.AtMostOnce, subMsg.Payload.Subscriptions[topic]); } [Fact] public void AcknowledgedSubscriptionRequestCreatesActiveSubscription() { Func<MqttMessage, bool> theCallback = null; MqttSubscribeMessage subMsg = null; var pubMock = new Mock<IPublishingManager>(); var chMock = new Mock<IMqttConnectionHandler>(); // mock the call to register and save the callback for later. chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())) .Callback((MqttMessageType msgtype, Func<MqttMessage, bool> cb) => theCallback = cb); // mock the call to Send(), which should occur when the subscription manager tries to subscribe chMock.Setup(x => x.SendMessage(It.IsAny<MqttSubscribeMessage>())) .Callback((MqttMessage msg) => subMsg = (MqttSubscribeMessage)msg); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); chMock.VerifyAll(); // now check the message generated by the subscription manager was good - ie contain the topic at the specified qos Assert.Contains(topic, subMsg.Payload.Subscriptions.Keys); Assert.Equal(MqttQos.AtMostOnce, subMsg.Payload.Subscriptions[topic]); // execute the callback that would normally be initiated by the connection handler when a sub ack message arrived. theCallback(new MqttSubscribeAckMessage().WithMessageIdentifier(1).AddQosGrant(MqttQos.AtMostOnce)); Assert.Equal(SubscriptionStatus.Active, subs.GetSubscriptionsStatus(topic)); } [Fact] public void SubscriptionAckForNonPendingSubscriptionThrowsException() { Func<MqttMessage, bool> theCallback = null; MqttSubscribeMessage subMsg = null; var pubMock = new Mock<IPublishingManager>(); var chMock = new Mock<IMqttConnectionHandler>(); // mock the call to register and save the callback for later. chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())) .Callback((MqttMessageType msgtype, Func<MqttMessage, bool> cb) => theCallback = cb); // mock the call to Send(), which should occur when the subscription manager tries to subscribe chMock.Setup(x => x.SendMessage(It.IsAny<MqttSubscribeMessage>())) .Callback((MqttMessage msg) => subMsg = (MqttSubscribeMessage)msg); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); chMock.VerifyAll(); // now check the message generated by the subscription manager was good - ie contain the topic at the specified qos Assert.Contains(topic, subMsg.Payload.Subscriptions.Keys); Assert.Equal(MqttQos.AtMostOnce, subMsg.Payload.Subscriptions[topic]); // execute the callback with a bogus message identifier. Assert.Throws<ArgumentException>(() => theCallback(new MqttSubscribeAckMessage().WithMessageIdentifier(999).AddQosGrant(MqttQos.AtMostOnce))); } [Fact] public void GetSubscriptionWithValidTopicReturnsSubscription() { Func<MqttMessage, bool> theCallback = null; var chMock = new Mock<IMqttConnectionHandler>(); chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())) .Callback((MqttMessageType msgtype, Func<MqttMessage, bool> cb) => theCallback = cb); var pubMock = new Mock<IPublishingManager>(); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); // execute the callback that would normally be initiated by the connection handler when a sub ack message arrived. theCallback(new MqttSubscribeAckMessage().WithMessageIdentifier(1).AddQosGrant(MqttQos.AtMostOnce)); Assert.NotNull(subs.GetSubscription(topic)); } [Fact] public void GetSubscriptionWithInvalidTopicReturnsNull() { Func<MqttMessage, bool> theCallback = null; var pubMock = new Mock<IPublishingManager>(); var chMock = new Mock<IMqttConnectionHandler>(); chMock.Setup(x => x.RegisterForMessage(MqttMessageType.SubscribeAck, It.IsAny<Func<MqttMessage, bool>>())) .Callback((MqttMessageType msgtype, Func<MqttMessage, bool> cb) => theCallback = cb); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); // execute the callback that would normally be initiated by the connection handler when a sub ack message arrived. theCallback(new MqttSubscribeAckMessage().WithMessageIdentifier(1).AddQosGrant(MqttQos.AtMostOnce)); Assert.Null(subs.GetSubscription("abc_badTopic")); } [Fact] public void GetSubscriptionForPendingSubscriptionReturnsNull() { var chMock = new Mock<IMqttConnectionHandler>(); var pubMock = new Mock<IPublishingManager>(); const string topic = "testtopic"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); subs.RegisterSubscription<string, AsciiPayloadConverter>(topic, qos); Assert.Null(subs.GetSubscription(topic)); } [Fact] public void SubscriptionAgainstInvalidTopicThrowsInvalidTopicException() { var chMock = new Mock<IMqttConnectionHandler>(); var pubMock = new Mock<IPublishingManager>(); const string badTopic = "finance/ibm#"; const MqttQos qos = MqttQos.AtMostOnce; // run and verify the mocks were called. var subs = new Nmqtt.SubscriptionsManager(chMock.Object, pubMock.Object); Assert.Throws<InvalidTopicException>(() => subs.RegisterSubscription<byte[], PassThroughPayloadConverter>(badTopic, qos)); } } }
/* * OEML - REST API * * This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) * * The version of the OpenAPI document: v1 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = CoinAPI.OMS.API.SDK.Client.OpenAPIDateConverter; namespace CoinAPI.OMS.API.SDK.Model { /// <summary> /// The Position object. /// </summary> [DataContract(Name = "Position_data")] public partial class PositionData : IEquatable<PositionData>, IValidatableObject { /// <summary> /// Gets or Sets Side /// </summary> [DataMember(Name = "side", EmitDefaultValue = false)] public OrdSide? Side { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PositionData" /> class. /// </summary> /// <param name="symbolIdExchange">Exchange symbol..</param> /// <param name="symbolIdCoinapi">CoinAPI symbol..</param> /// <param name="avgEntryPrice">Calculated average price of all fills on this position..</param> /// <param name="quantity">The current position quantity..</param> /// <param name="side">side.</param> /// <param name="unrealizedPnl">Unrealised profit or loss (PNL) of this position..</param> /// <param name="leverage">Leverage for this position reported by the exchange..</param> /// <param name="crossMargin">Is cross margin mode enable for this position?.</param> /// <param name="liquidationPrice">Liquidation price. If mark price will reach this value, the position will be liquidated..</param> /// <param name="rawData">rawData.</param> public PositionData(string symbolIdExchange = default(string), string symbolIdCoinapi = default(string), decimal avgEntryPrice = default(decimal), decimal quantity = default(decimal), OrdSide? side = default(OrdSide?), decimal unrealizedPnl = default(decimal), decimal leverage = default(decimal), bool crossMargin = default(bool), decimal liquidationPrice = default(decimal), Object rawData = default(Object)) { this.SymbolIdExchange = symbolIdExchange; this.SymbolIdCoinapi = symbolIdCoinapi; this.AvgEntryPrice = avgEntryPrice; this.Quantity = quantity; this.Side = side; this.UnrealizedPnl = unrealizedPnl; this.Leverage = leverage; this.CrossMargin = crossMargin; this.LiquidationPrice = liquidationPrice; this.RawData = rawData; } /// <summary> /// Exchange symbol. /// </summary> /// <value>Exchange symbol.</value> [DataMember(Name = "symbol_id_exchange", EmitDefaultValue = false)] public string SymbolIdExchange { get; set; } /// <summary> /// CoinAPI symbol. /// </summary> /// <value>CoinAPI symbol.</value> [DataMember(Name = "symbol_id_coinapi", EmitDefaultValue = false)] public string SymbolIdCoinapi { get; set; } /// <summary> /// Calculated average price of all fills on this position. /// </summary> /// <value>Calculated average price of all fills on this position.</value> [DataMember(Name = "avg_entry_price", EmitDefaultValue = false)] public decimal AvgEntryPrice { get; set; } /// <summary> /// The current position quantity. /// </summary> /// <value>The current position quantity.</value> [DataMember(Name = "quantity", EmitDefaultValue = false)] public decimal Quantity { get; set; } /// <summary> /// Unrealised profit or loss (PNL) of this position. /// </summary> /// <value>Unrealised profit or loss (PNL) of this position.</value> [DataMember(Name = "unrealized_pnl", EmitDefaultValue = false)] public decimal UnrealizedPnl { get; set; } /// <summary> /// Leverage for this position reported by the exchange. /// </summary> /// <value>Leverage for this position reported by the exchange.</value> [DataMember(Name = "leverage", EmitDefaultValue = false)] public decimal Leverage { get; set; } /// <summary> /// Is cross margin mode enable for this position? /// </summary> /// <value>Is cross margin mode enable for this position?</value> [DataMember(Name = "cross_margin", EmitDefaultValue = true)] public bool CrossMargin { get; set; } /// <summary> /// Liquidation price. If mark price will reach this value, the position will be liquidated. /// </summary> /// <value>Liquidation price. If mark price will reach this value, the position will be liquidated.</value> [DataMember(Name = "liquidation_price", EmitDefaultValue = false)] public decimal LiquidationPrice { get; set; } /// <summary> /// Gets or Sets RawData /// </summary> [DataMember(Name = "raw_data", EmitDefaultValue = false)] public Object RawData { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class PositionData {\n"); sb.Append(" SymbolIdExchange: ").Append(SymbolIdExchange).Append("\n"); sb.Append(" SymbolIdCoinapi: ").Append(SymbolIdCoinapi).Append("\n"); sb.Append(" AvgEntryPrice: ").Append(AvgEntryPrice).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" Side: ").Append(Side).Append("\n"); sb.Append(" UnrealizedPnl: ").Append(UnrealizedPnl).Append("\n"); sb.Append(" Leverage: ").Append(Leverage).Append("\n"); sb.Append(" CrossMargin: ").Append(CrossMargin).Append("\n"); sb.Append(" LiquidationPrice: ").Append(LiquidationPrice).Append("\n"); sb.Append(" RawData: ").Append(RawData).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PositionData); } /// <summary> /// Returns true if PositionData instances are equal /// </summary> /// <param name="input">Instance of PositionData to be compared</param> /// <returns>Boolean</returns> public bool Equals(PositionData input) { if (input == null) { return false; } return ( this.SymbolIdExchange == input.SymbolIdExchange || (this.SymbolIdExchange != null && this.SymbolIdExchange.Equals(input.SymbolIdExchange)) ) && ( this.SymbolIdCoinapi == input.SymbolIdCoinapi || (this.SymbolIdCoinapi != null && this.SymbolIdCoinapi.Equals(input.SymbolIdCoinapi)) ) && ( this.AvgEntryPrice == input.AvgEntryPrice || this.AvgEntryPrice.Equals(input.AvgEntryPrice) ) && ( this.Quantity == input.Quantity || this.Quantity.Equals(input.Quantity) ) && ( this.Side == input.Side || this.Side.Equals(input.Side) ) && ( this.UnrealizedPnl == input.UnrealizedPnl || this.UnrealizedPnl.Equals(input.UnrealizedPnl) ) && ( this.Leverage == input.Leverage || this.Leverage.Equals(input.Leverage) ) && ( this.CrossMargin == input.CrossMargin || this.CrossMargin.Equals(input.CrossMargin) ) && ( this.LiquidationPrice == input.LiquidationPrice || this.LiquidationPrice.Equals(input.LiquidationPrice) ) && ( this.RawData == input.RawData || (this.RawData != null && this.RawData.Equals(input.RawData)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.SymbolIdExchange != null) { hashCode = (hashCode * 59) + this.SymbolIdExchange.GetHashCode(); } if (this.SymbolIdCoinapi != null) { hashCode = (hashCode * 59) + this.SymbolIdCoinapi.GetHashCode(); } hashCode = (hashCode * 59) + this.AvgEntryPrice.GetHashCode(); hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); hashCode = (hashCode * 59) + this.Side.GetHashCode(); hashCode = (hashCode * 59) + this.UnrealizedPnl.GetHashCode(); hashCode = (hashCode * 59) + this.Leverage.GetHashCode(); hashCode = (hashCode * 59) + this.CrossMargin.GetHashCode(); hashCode = (hashCode * 59) + this.LiquidationPrice.GetHashCode(); if (this.RawData != null) { hashCode = (hashCode * 59) + this.RawData.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.HWPF.Extractor; using TestCases.HWPF; using System; using System.Text; using TestCases; using NPOI.POIFS.FileSystem; using NPOI.HWPF; using System.Text.RegularExpressions; using NUnit.Framework; namespace TestCases.HWPF.Extractor { /** * Test the different routes to extracting text * * @author Nick Burch (nick at torchbox dot com) */ [TestFixture] public class TestWordExtractor { private String[] p_text1 = new String[] { "This is a simple word document\r\n", "\r\n", "It has a number of paragraphs in it\r\n", "\r\n", "Some of them even feature bold, italic and underlined text\r\n", "\r\n", "\r\n", "This bit is in a different font and size\r\n", "\r\n", "\r\n", "This bit features some red text.\r\n", "\r\n", "\r\n", "It is otherwise very very boring.\r\n" }; private String p_text1_block = ""; // Well behaved document private WordExtractor extractor; // Slightly iffy document private WordExtractor extractor2; // A word doc embeded in an excel file private String filename3; // With header and footer private String filename4; // With unicode header and footer private String filename5; // With footnote private String filename6; [SetUp] public void SetUp() { String filename = "test2.doc"; String filename2 = "test.doc"; filename3 = "excel_with_embeded.xls"; filename4 = "ThreeColHeadFoot.doc"; filename5 = "HeaderFooterUnicode.doc"; filename6 = "footnote.doc"; POIDataSamples docTests = POIDataSamples.GetDocumentInstance(); extractor = new WordExtractor(docTests.OpenResourceAsStream(filename)); extractor2 = new WordExtractor(docTests.OpenResourceAsStream(filename2)); // Build splat'd out text version for (int i = 0; i < p_text1.Length; i++) { p_text1_block += p_text1[i]; } } /** * Test paragraph based extraction */ [Test] public void TestExtractFromParagraphs() { String[] text = extractor.ParagraphText; Assert.AreEqual(p_text1.Length, text.Length); for (int i = 0; i < p_text1.Length; i++) { Assert.AreEqual(p_text1[i], text[i]); } // Lots of paragraphs with only a few lines in them Assert.AreEqual(24, extractor2.ParagraphText.Length); Assert.AreEqual("as d\r\n", extractor2.ParagraphText[16]); Assert.AreEqual("as d\r\n", extractor2.ParagraphText[17]); Assert.AreEqual("as d\r\n", extractor2.ParagraphText[18]); } /** * Test the paragraph -> flat extraction */ [Test] public void TestText() { Assert.AreEqual(p_text1_block, extractor.Text); Regex regex = new Regex("[\\r\\n]"); // For the 2nd, should give similar answers for // the two methods, differing only in line endings Assert.AreEqual( regex.Replace(extractor2.TextFromPieces, ""), regex.Replace(extractor2.Text, "")); } /** * Test textPieces based extraction */ [Test] public void TestExtractFromTextPieces() { String text = extractor.TextFromPieces; Assert.AreEqual(p_text1_block, text); } /** * Test that we can get data from two different * embeded word documents * @throws Exception */ [Test] public void TestExtractFromEmbeded() { POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream(filename3)); HWPFDocument doc; WordExtractor extractor3; DirectoryNode dirA = (DirectoryNode)fs.Root.GetEntry("MBD0000A3B7"); DirectoryNode dirB = (DirectoryNode)fs.Root.GetEntry("MBD0000A3B2"); // Should have WordDocument and 1Table Assert.IsNotNull(dirA.GetEntry("1Table")); Assert.IsNotNull(dirA.GetEntry("WordDocument")); Assert.IsNotNull(dirB.GetEntry("1Table")); Assert.IsNotNull(dirB.GetEntry("WordDocument")); // Check each in turn doc = new HWPFDocument(dirA, fs); extractor3 = new WordExtractor(doc); Assert.IsNotNull(extractor3.Text); Assert.IsTrue(extractor3.Text.Length > 20); Assert.AreEqual("I am a sample document\r\nNot much on me\r\nI am document 1\r\n", extractor3 .Text); Assert.AreEqual("Sample Doc 1", extractor3.SummaryInformation.Title); Assert.AreEqual("Sample Test", extractor3.SummaryInformation.Subject); doc = new HWPFDocument(dirB, fs); extractor3 = new WordExtractor(doc); Assert.IsNotNull(extractor3.Text); Assert.IsTrue(extractor3.Text.Length > 20); Assert.AreEqual("I am another sample document\r\nNot much on me\r\nI am document 2\r\n", extractor3.Text); Assert.AreEqual("Sample Doc 2", extractor3.SummaryInformation.Title); Assert.AreEqual("Another Sample Test", extractor3.SummaryInformation.Subject); } [Test] public void TestWithHeader() { // Non-unicode HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile(filename4); extractor = new WordExtractor(doc); Assert.AreEqual("First header column!\tMid header Right header!\n", extractor.HeaderText); String text = extractor.Text; Assert.IsTrue(text.IndexOf("First header column!") > -1); // Unicode doc = HWPFTestDataSamples.OpenSampleFile(filename5); extractor = new WordExtractor(doc); Assert.AreEqual("This is a simple header, with a \u20ac euro symbol in it.\n\n", extractor .HeaderText); text = extractor.Text; Assert.IsTrue(text.IndexOf("This is a simple header") > -1); } [Test] public void TestWithFooter() { // Non-unicode HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile(filename4); extractor = new WordExtractor(doc); Assert.AreEqual("Footer Left\tFooter Middle Footer Right\n", extractor.FooterText); String text = extractor.Text; Assert.IsTrue(text.IndexOf("Footer Left") > -1); // Unicode doc = HWPFTestDataSamples.OpenSampleFile(filename5); extractor = new WordExtractor(doc); Assert.AreEqual("The footer, with Moli\u00e8re, has Unicode in it.\n", extractor .FooterText); text = extractor.Text; Assert.IsTrue(text.IndexOf("The footer, with") > -1); } [Test] public void TestFootnote() { HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile(filename6); extractor = new WordExtractor(doc); String[] text = extractor.FootnoteText; StringBuilder b = new StringBuilder(); for (int i = 0; i < text.Length; i++) { b.Append(text[i]); } Assert.IsTrue(b.ToString().Contains("TestFootnote")); } [Test] public void TestEndnote() { HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile(filename6); extractor = new WordExtractor(doc); String[] text = extractor.EndnoteText; StringBuilder b = new StringBuilder(); for (int i = 0; i < text.Length; i++) { b.Append(text[i]); } Assert.IsTrue(b.ToString().Contains("TestEndnote")); } [Test] public void TestComments() { HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile(filename6); extractor = new WordExtractor(doc); String[] text = extractor.CommentsText; StringBuilder b = new StringBuilder(); for (int i = 0; i < text.Length; i++) { b.Append(text[i]); } Assert.IsTrue(b.ToString().Contains("TestComment")); } [Test] public void TestWord95() { // Too old for the default try { extractor = new WordExtractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("Word95.doc") ); Assert.Fail(); } catch (OldWordFileFormatException ) { } // Can work with the special one Word6Extractor w6e = new Word6Extractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("Word95.doc") ); String text = w6e.Text; Assert.IsTrue(text.Contains("The quick brown fox jumps over the lazy dog")); Assert.IsTrue(text.Contains("Paragraph 2")); Assert.IsTrue(text.Contains("Paragraph 3. Has some RED text and some BLUE BOLD text in it")); Assert.IsTrue(text.Contains("Last (4th) paragraph")); String[] tp = w6e.ParagraphText; Assert.AreEqual(7, tp.Length); Assert.AreEqual("The quick brown fox jumps over the lazy dog\r\n", tp[0]); Assert.AreEqual("\r\n", tp[1]); Assert.AreEqual("Paragraph 2\r\n", tp[2]); Assert.AreEqual("\r\n", tp[3]); Assert.AreEqual("Paragraph 3. Has some RED text and some BLUE BOLD text in it.\r\n", tp[4]); Assert.AreEqual("\r\n", tp[5]); Assert.AreEqual("Last (4th) paragraph.\r\n", tp[6]); } [Test] public void TestWord6() { // Too old for the default try { extractor = new WordExtractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("Word6.doc") ); Assert.Fail(); } catch (OldWordFileFormatException) { } Word6Extractor w6e = new Word6Extractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("Word6.doc") ); String text = w6e.Text; Assert.IsTrue(text.Contains("The quick brown fox jumps over the lazy dog")); String[] tp = w6e.ParagraphText; Assert.AreEqual(1, tp.Length); Assert.AreEqual("The quick brown fox jumps over the lazy dog\r\n", tp[0]); } [Test] public void TestFastSaved() { extractor = new WordExtractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("rasp.doc") ); String text = extractor.Text; Assert.IsTrue(text.Contains("\u0425\u0425\u0425\u0425\u0425")); Assert.IsTrue(text.Contains("\u0423\u0423\u0423\u0423\u0423")); } [Test] public void TestFirstParagraphFix() { extractor = new WordExtractor( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("Bug48075.doc") ); String text = extractor.Text; Assert.IsTrue(text.StartsWith("\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u0435")); } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn.Models { using Azure; using Management; using Cdn; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// CDN endpoint is the entity within a CDN profile containing /// configuration information such as origin, protocol, content caching and /// delivery behavior. The CDN endpoint uses the URL format /// &lt;endpointname&gt;.azureedge.net. /// </summary> [JsonTransformation] public partial class Endpoint : Resource { /// <summary> /// Initializes a new instance of the Endpoint class. /// </summary> public Endpoint() { } /// <summary> /// Initializes a new instance of the Endpoint class. /// </summary> /// <param name="location">Resource location.</param> /// <param name="origins">The source of the content being delivered via /// CDN.</param> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type.</param> /// <param name="tags">Resource tags.</param> /// <param name="originHostHeader">The host header CDN sends along with /// content requests to origin. The default value is the host name of /// the origin.</param> /// <param name="originPath">The path used when CDN sends request to /// origin.</param> /// <param name="contentTypesToCompress">List of content types on which /// compression applies. The value should be a valid MIME type.</param> /// <param name="isCompressionEnabled">Indicates whether content /// compression is enabled on CDN. Default value is false. If /// compression is enabled, content will be served as compressed if /// user requests for a compressed version. Content won't be compressed /// on CDN when requested content is smaller than 1 byte or larger than /// 1 MB.</param> /// <param name="isHttpAllowed">Indicates whether HTTP traffic is /// allowed on the endpoint. Default value is true. At least one /// protocol (HTTP or HTTPS) must be allowed.</param> /// <param name="isHttpsAllowed">Indicates whether HTTPS traffic is /// allowed on the endpoint. Default value is true. At least one /// protocol (HTTP or HTTPS) must be allowed.</param> /// <param name="queryStringCachingBehavior">Defines the query string /// caching behavior. Possible values include: 'IgnoreQueryString', /// 'BypassCaching', 'UseQueryString', 'NotSet'</param> /// <param name="optimizationType">Customer can specify what scenario /// they want this CDN endpoint to optimize, e.g. Download, Media /// services. With this information we can apply scenario driven /// optimization.</param> /// <param name="geoFilters">List of rules defining user geo access /// within a CDN endpoint. Each geo filter defines an acess rule to a /// specified path or content, e.g. block APAC for path /// /pictures/</param> /// <param name="hostName">The host name of the endpoint structured as /// {endpointName}.{DNSZone}, e.g. consoto.azureedge.net</param> /// <param name="resourceState">Resource status of the endpoint. /// Possible values include: 'Creating', 'Deleting', 'Running', /// 'Starting', 'Stopped', 'Stopping'</param> /// <param name="provisioningState">Provisioning status of the /// endpoint.</param> public Endpoint(string location, IList<DeepCreatedOrigin> origins, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string originHostHeader = default(string), string originPath = default(string), IList<string> contentTypesToCompress = default(IList<string>), bool? isCompressionEnabled = default(bool?), bool? isHttpAllowed = default(bool?), bool? isHttpsAllowed = default(bool?), QueryStringCachingBehavior? queryStringCachingBehavior = default(QueryStringCachingBehavior?), string optimizationType = default(string), IList<GeoFilter> geoFilters = default(IList<GeoFilter>), string hostName = default(string), string resourceState = default(string), string provisioningState = default(string)) : base(location, id, name, type, tags) { OriginHostHeader = originHostHeader; OriginPath = originPath; ContentTypesToCompress = contentTypesToCompress; IsCompressionEnabled = isCompressionEnabled; IsHttpAllowed = isHttpAllowed; IsHttpsAllowed = isHttpsAllowed; QueryStringCachingBehavior = queryStringCachingBehavior; OptimizationType = optimizationType; GeoFilters = geoFilters; HostName = hostName; Origins = origins; ResourceState = resourceState; ProvisioningState = provisioningState; } /// <summary> /// Gets or sets the host header CDN sends along with content requests /// to origin. The default value is the host name of the origin. /// </summary> [JsonProperty(PropertyName = "properties.originHostHeader")] public string OriginHostHeader { get; set; } /// <summary> /// Gets or sets the path used when CDN sends request to origin. /// </summary> [JsonProperty(PropertyName = "properties.originPath")] public string OriginPath { get; set; } /// <summary> /// Gets or sets list of content types on which compression applies. /// The value should be a valid MIME type. /// </summary> [JsonProperty(PropertyName = "properties.contentTypesToCompress")] public IList<string> ContentTypesToCompress { get; set; } /// <summary> /// Gets or sets indicates whether content compression is enabled on /// CDN. Default value is false. If compression is enabled, content /// will be served as compressed if user requests for a compressed /// version. Content won't be compressed on CDN when requested content /// is smaller than 1 byte or larger than 1 MB. /// </summary> [JsonProperty(PropertyName = "properties.isCompressionEnabled")] public bool? IsCompressionEnabled { get; set; } /// <summary> /// Gets or sets indicates whether HTTP traffic is allowed on the /// endpoint. Default value is true. At least one protocol (HTTP or /// HTTPS) must be allowed. /// </summary> [JsonProperty(PropertyName = "properties.isHttpAllowed")] public bool? IsHttpAllowed { get; set; } /// <summary> /// Gets or sets indicates whether HTTPS traffic is allowed on the /// endpoint. Default value is true. At least one protocol (HTTP or /// HTTPS) must be allowed. /// </summary> [JsonProperty(PropertyName = "properties.isHttpsAllowed")] public bool? IsHttpsAllowed { get; set; } /// <summary> /// Gets or sets defines the query string caching behavior. Possible /// values include: 'IgnoreQueryString', 'BypassCaching', /// 'UseQueryString', 'NotSet' /// </summary> [JsonProperty(PropertyName = "properties.queryStringCachingBehavior")] public QueryStringCachingBehavior? QueryStringCachingBehavior { get; set; } /// <summary> /// Gets or sets customer can specify what scenario they want this CDN /// endpoint to optimize, e.g. Download, Media services. With this /// information we can apply scenario driven optimization. /// </summary> [JsonProperty(PropertyName = "properties.optimizationType")] public string OptimizationType { get; set; } /// <summary> /// Gets or sets list of rules defining user geo access within a CDN /// endpoint. Each geo filter defines an acess rule to a specified path /// or content, e.g. block APAC for path /pictures/ /// </summary> [JsonProperty(PropertyName = "properties.geoFilters")] public IList<GeoFilter> GeoFilters { get; set; } /// <summary> /// Gets the host name of the endpoint structured as /// {endpointName}.{DNSZone}, e.g. consoto.azureedge.net /// </summary> [JsonProperty(PropertyName = "properties.hostName")] public string HostName { get; protected set; } /// <summary> /// Gets or sets the source of the content being delivered via CDN. /// </summary> [JsonProperty(PropertyName = "properties.origins")] public IList<DeepCreatedOrigin> Origins { get; set; } /// <summary> /// Gets resource status of the endpoint. Possible values include: /// 'Creating', 'Deleting', 'Running', 'Starting', 'Stopped', /// 'Stopping' /// </summary> [JsonProperty(PropertyName = "properties.resourceState")] public string ResourceState { get; protected set; } /// <summary> /// Gets provisioning status of the endpoint. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; protected set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (Origins == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Origins"); } if (GeoFilters != null) { foreach (var element in GeoFilters) { if (element != null) { element.Validate(); } } } if (Origins != null) { foreach (var element1 in Origins) { if (element1 != null) { element1.Validate(); } } } } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2011 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using OpenTK.Graphics; namespace OpenTK.Platform.Egl { using EGLNativeDisplayType = IntPtr; using EGLNativePixmapType = IntPtr; using EGLConfig = IntPtr; using EGLContext = IntPtr; using EGLDisplay = IntPtr; using EGLSurface = IntPtr; using EGLClientBuffer = IntPtr; [Flags] enum RenderableFlags { ES = Egl.OPENGL_ES_BIT, ES2 = Egl.OPENGL_ES2_BIT, GL = Egl.OPENGL_BIT, VG = Egl.OPENVG_BIT, } static partial class Egl { public const int VERSION_1_0 = 1; public const int VERSION_1_1 = 1; public const int VERSION_1_2 = 1; public const int VERSION_1_3 = 1; public const int VERSION_1_4 = 1; public const int FALSE = 0; public const int TRUE = 1; public const int DONT_CARE = -1; public const int SUCCESS = 12288; public const int NOT_INITIALIZED = 12289; public const int BAD_ACCESS = 12290; public const int BAD_ALLOC = 12291; public const int BAD_ATTRIBUTE = 12292; public const int BAD_CONFIG = 12293; public const int BAD_CONTEXT = 12294; public const int BAD_CURRENT_SURFACE = 12295; public const int BAD_DISPLAY = 12296; public const int BAD_MATCH = 12297; public const int BAD_NATIVE_PIXMAP = 12298; public const int BAD_NATIVE_WINDOW = 12299; public const int BAD_PARAMETER = 12300; public const int BAD_SURFACE = 12301; public const int CONTEXT_LOST = 12302; public const int BUFFER_SIZE = 12320; public const int ALPHA_SIZE = 12321; public const int BLUE_SIZE = 12322; public const int GREEN_SIZE = 12323; public const int RED_SIZE = 12324; public const int DEPTH_SIZE = 12325; public const int STENCIL_SIZE = 12326; public const int CONFIG_CAVEAT = 12327; public const int CONFIG_ID = 12328; public const int LEVEL = 12329; public const int MAX_PBUFFER_HEIGHT = 12330; public const int MAX_PBUFFER_PIXELS = 12331; public const int MAX_PBUFFER_WIDTH = 12332; public const int NATIVE_RENDERABLE = 12333; public const int NATIVE_VISUAL_ID = 12334; public const int NATIVE_VISUAL_TYPE = 12335; public const int PRESERVED_RESOURCES = 12336; public const int SAMPLES = 12337; public const int SAMPLE_BUFFERS = 12338; public const int SURFACE_TYPE = 12339; public const int TRANSPARENT_TYPE = 12340; public const int TRANSPARENT_BLUE_VALUE = 12341; public const int TRANSPARENT_GREEN_VALUE = 12342; public const int TRANSPARENT_RED_VALUE = 12343; public const int NONE = 12344; public const int BIND_TO_TEXTURE_RGB = 12345; public const int BIND_TO_TEXTURE_RGBA = 12346; public const int MIN_SWAP_INTERVAL = 12347; public const int MAX_SWAP_INTERVAL = 12348; public const int LUMINANCE_SIZE = 12349; public const int ALPHA_MASK_SIZE = 12350; public const int COLOR_BUFFER_TYPE = 12351; public const int RENDERABLE_TYPE = 12352; public const int MATCH_NATIVE_PIXMAP = 12353; public const int CONFORMANT = 12354; public const int SLOW_CONFIG = 12368; public const int NON_CONFORMANT_CONFIG = 12369; public const int TRANSPARENT_RGB = 12370; public const int RGB_BUFFER = 12430; public const int LUMINANCE_BUFFER = 12431; public const int NO_TEXTURE = 12380; public const int TEXTURE_RGB = 12381; public const int TEXTURE_RGBA = 12382; public const int TEXTURE_2D = 12383; public const int PBUFFER_BIT = 1; public const int PIXMAP_BIT = 2; public const int WINDOW_BIT = 4; public const int VG_COLORSPACE_LINEAR_BIT = 32; public const int VG_ALPHA_FORMAT_PRE_BIT = 64; public const int MULTISAMPLE_RESOLVE_BOX_BIT = 512; public const int SWAP_BEHAVIOR_PRESERVED_BIT = 1024; public const int OPENGL_ES_BIT = 1; public const int OPENVG_BIT = 2; public const int OPENGL_ES2_BIT = 4; public const int OPENGL_BIT = 8; public const int VENDOR = 12371; public const int VERSION = 12372; public const int EXTENSIONS = 12373; public const int CLIENT_APIS = 12429; public const int HEIGHT = 12374; public const int WIDTH = 12375; public const int LARGEST_PBUFFER = 12376; public const int TEXTURE_FORMAT = 12416; public const int TEXTURE_TARGET = 12417; public const int MIPMAP_TEXTURE = 12418; public const int MIPMAP_LEVEL = 12419; public const int RENDER_BUFFER = 12422; public const int VG_COLORSPACE = 12423; public const int VG_ALPHA_FORMAT = 12424; public const int HORIZONTAL_RESOLUTION = 12432; public const int VERTICAL_RESOLUTION = 12433; public const int PIXEL_ASPECT_RATIO = 12434; public const int SWAP_BEHAVIOR = 12435; public const int MULTISAMPLE_RESOLVE = 12441; public const int BACK_BUFFER = 12420; public const int SINGLE_BUFFER = 12421; public const int VG_COLORSPACE_sRGB = 12425; public const int VG_COLORSPACE_LINEAR = 12426; public const int VG_ALPHA_FORMAT_NONPRE = 12427; public const int VG_ALPHA_FORMAT_PRE = 12428; public const int DISPLAY_SCALING = 10000; public const int UNKNOWN = -1; public const int BUFFER_PRESERVED = 12436; public const int BUFFER_DESTROYED = 12437; public const int OPENVG_IMAGE = 12438; public const int CONTEXT_CLIENT_TYPE = 12439; public const int CONTEXT_CLIENT_VERSION = 12440; public const int MULTISAMPLE_RESOLVE_DEFAULT = 12442; public const int MULTISAMPLE_RESOLVE_BOX = 12443; public const int OPENGL_ES_API = 12448; public const int OPENVG_API = 12449; public const int OPENGL_API = 12450; public const int DRAW = 12377; public const int READ = 12378; public const int CORE_NATIVE_ENGINE = 12379; public const int COLORSPACE = VG_COLORSPACE; public const int ALPHA_FORMAT = VG_ALPHA_FORMAT; public const int COLORSPACE_sRGB = VG_COLORSPACE_sRGB; public const int COLORSPACE_LINEAR = VG_COLORSPACE_LINEAR; public const int ALPHA_FORMAT_NONPRE = VG_ALPHA_FORMAT_NONPRE; public const int ALPHA_FORMAT_PRE = VG_ALPHA_FORMAT_PRE; [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetError")] public static extern int GetError(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetDisplay")] public static extern EGLDisplay GetDisplay(EGLNativeDisplayType display_id); [DllImportAttribute("libEGL.dll", EntryPoint = "eglInitialize")] //[return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool Initialize(EGLDisplay dpy, out int major, out int minor); [DllImportAttribute("libEGL.dll", EntryPoint = "eglTerminate")] //[return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool Terminate(EGLDisplay dpy); [DllImportAttribute("libEGL.dll", EntryPoint = "eglQueryString")] public static extern IntPtr QueryString(EGLDisplay dpy, int name); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetConfigs")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool GetConfigs(EGLDisplay dpy, EGLConfig[] configs, int config_size, out int num_config); [DllImportAttribute("libEGL.dll", EntryPoint = "eglChooseConfig")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool ChooseConfig(EGLDisplay dpy, int[] attrib_list, [In, Out] EGLConfig[] configs, int config_size, out int num_config); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetConfigAttrib")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool GetConfigAttrib(EGLDisplay dpy, EGLConfig config, int attribute, out int value); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCreateWindowSurface")] public static extern EGLSurface CreateWindowSurface(EGLDisplay dpy, EGLConfig config, IntPtr win, int[] attrib_list); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCreatePbufferSurface")] public static extern EGLSurface CreatePbufferSurface(EGLDisplay dpy, EGLConfig config, int[] attrib_list); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCreatePixmapSurface")] public static extern EGLSurface CreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, int[] attrib_list); [DllImportAttribute("libEGL.dll", EntryPoint = "eglDestroySurface")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool DestroySurface(EGLDisplay dpy, EGLSurface surface); [DllImportAttribute("libEGL.dll", EntryPoint = "eglQuerySurface")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool QuerySurface(EGLDisplay dpy, EGLSurface surface, int attribute, out int value); [DllImportAttribute("libEGL.dll", EntryPoint = "eglBindAPI")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool BindAPI(int api); [DllImportAttribute("libEGL.dll", EntryPoint = "eglQueryAPI")] public static extern int QueryAPI(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglWaitClient")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool WaitClient(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglReleaseThread")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool ReleaseThread(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCreatePbufferFromClientBuffer")] public static extern EGLSurface CreatePbufferFromClientBuffer(EGLDisplay dpy, int buftype, EGLClientBuffer buffer, EGLConfig config, int[] attrib_list); [DllImportAttribute("libEGL.dll", EntryPoint = "eglSurfaceAttrib")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool SurfaceAttrib(EGLDisplay dpy, EGLSurface surface, int attribute, int value); [DllImportAttribute("libEGL.dll", EntryPoint = "eglBindTexImage")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool BindTexImage(EGLDisplay dpy, EGLSurface surface, int buffer); [DllImportAttribute("libEGL.dll", EntryPoint = "eglReleaseTexImage")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool ReleaseTexImage(EGLDisplay dpy, EGLSurface surface, int buffer); [DllImportAttribute("libEGL.dll", EntryPoint = "eglSwapInterval")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool SwapInterval(EGLDisplay dpy, int interval); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCreateContext")] static extern IntPtr eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, int[] attrib_list); public static EGLContext CreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, int[] attrib_list) { IntPtr ptr = eglCreateContext(dpy, config, share_context, attrib_list); if (ptr == IntPtr.Zero) throw new GraphicsContextException(String.Format("Failed to create EGL context, error: {0}.", Egl.GetError())); return ptr; } [DllImportAttribute("libEGL.dll", EntryPoint = "eglDestroyContext")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool DestroyContext(EGLDisplay dpy, EGLContext ctx); [DllImportAttribute("libEGL.dll", EntryPoint = "eglMakeCurrent")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool MakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetCurrentContext")] public static extern EGLContext GetCurrentContext(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetCurrentSurface")] public static extern EGLSurface GetCurrentSurface(int readdraw); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetCurrentDisplay")] public static extern EGLDisplay GetCurrentDisplay(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglQueryContext")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool QueryContext(EGLDisplay dpy, EGLContext ctx, int attribute, out int value); [DllImportAttribute("libEGL.dll", EntryPoint = "eglWaitGL")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool WaitGL(); [DllImportAttribute("libEGL.dll", EntryPoint = "eglWaitNative")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool WaitNative(int engine); [DllImportAttribute("libEGL.dll", EntryPoint = "eglSwapBuffers")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool SwapBuffers(EGLDisplay dpy, EGLSurface surface); [DllImportAttribute("libEGL.dll", EntryPoint = "eglCopyBuffers")] [return: MarshalAsAttribute(UnmanagedType.I1)] public static extern bool CopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target); [DllImportAttribute("libEGL.dll", EntryPoint = "eglGetProcAddress")] public static extern IntPtr GetProcAddress(string funcname); // Returns true if Egl drivers exist on the system. public static bool IsSupported { get { try { GetCurrentContext(); } catch (Exception) { return false; } return true; } } } #pragma warning restore 0169 }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace SampleWebAPIApp.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Console.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System { static public partial class Console { #region Methods and constructors public static void Beep(int frequency, int duration) { } public static void Beep() { } public static void Clear() { } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { } public static Stream OpenStandardError() { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static Stream OpenStandardError(int bufferSize) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static Stream OpenStandardInput() { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static Stream OpenStandardInput(int bufferSize) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static Stream OpenStandardOutput(int bufferSize) { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static Stream OpenStandardOutput() { Contract.Ensures(Contract.Result<System.IO.Stream>() != null); return default(Stream); } public static int Read() { return default(int); } public static ConsoleKeyInfo ReadKey(bool intercept) { return default(ConsoleKeyInfo); } public static ConsoleKeyInfo ReadKey() { return default(ConsoleKeyInfo); } public static string ReadLine() { return default(string); } public static void ResetColor() { } public static void SetBufferSize(int width, int height) { } public static void SetCursorPosition(int left, int top) { } public static void SetError(TextWriter newError) { } public static void SetIn(TextReader newIn) { } public static void SetOut(TextWriter newOut) { } public static void SetWindowPosition(int left, int top) { } public static void SetWindowSize(int width, int height) { } public static void Write(ulong value) { } public static void Write(long value) { } public static void Write(uint value) { } public static void Write(string format, Object arg0) { } public static void Write(string value) { } public static void Write(Object value) { } public static void Write(int value) { } public static void Write(string format, Object[] arg) { } public static void Write(bool value) { } public static void Write(string format, Object arg0, Object arg1, Object arg2, Object arg3) { } public static void Write(string format, Object arg0, Object arg1) { } public static void Write(string format, Object arg0, Object arg1, Object arg2) { } public static void Write(char value) { } public static void Write(Decimal value) { } public static void Write(float value) { } public static void Write(double value) { } public static void Write(char[] buffer) { } public static void Write(char[] buffer, int index, int count) { } public static void WriteLine(double value) { } public static void WriteLine(Decimal value) { } public static void WriteLine(int value) { } public static void WriteLine(float value) { } public static void WriteLine(char[] buffer, int index, int count) { } public static void WriteLine(bool value) { } public static void WriteLine() { } public static void WriteLine(char[] buffer) { } public static void WriteLine(char value) { } public static void WriteLine(uint value) { } public static void WriteLine(string format, Object arg0, Object arg1, Object arg2) { } public static void WriteLine(string format, Object arg0, Object arg1) { } public static void WriteLine(string format, Object[] arg) { } public static void WriteLine(string format, Object arg0, Object arg1, Object arg2, Object arg3) { } public static void WriteLine(string format, Object arg0) { } public static void WriteLine(ulong value) { } public static void WriteLine(long value) { } public static void WriteLine(string value) { } public static void WriteLine(Object value) { } #endregion #region Properties and indexers public static ConsoleColor BackgroundColor { get { return default(ConsoleColor); } set { } } public static int BufferHeight { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.BufferWidth); Contract.Ensures(System.Console.BufferWidth <= 32767); } } public static int BufferWidth { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.BufferHeight); Contract.Ensures(System.Console.BufferHeight <= 32767); } } public static bool CapsLock { get { return default(bool); } } public static int CursorLeft { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.CursorTop); Contract.Ensures(System.Console.CursorTop <= 32767); } } public static int CursorSize { get { return default(int); } set { } } public static int CursorTop { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.CursorLeft); Contract.Ensures(System.Console.CursorLeft <= 32767); } } public static bool CursorVisible { get { return default(bool); } set { } } public static TextWriter Error { get { Contract.Ensures(Contract.Result<System.IO.TextWriter>() != null); return default(TextWriter); } } public static ConsoleColor ForegroundColor { get { Contract.Ensures(((System.ConsoleColor)(0)) <= Contract.Result<System.ConsoleColor>()); Contract.Ensures(Contract.Result<System.ConsoleColor>() <= ((System.ConsoleColor)(15))); return default(ConsoleColor); } set { } } public static TextReader In { get { Contract.Ensures(Contract.Result<System.IO.TextReader>() != null); return default(TextReader); } } public static Encoding InputEncoding { get { Contract.Ensures(Contract.Result<System.Text.Encoding>() != null); return default(Encoding); } set { } } public static bool KeyAvailable { get { return default(bool); } } public static int LargestWindowHeight { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } } public static int LargestWindowWidth { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } } public static bool NumberLock { get { return default(bool); } } public static TextWriter Out { get { Contract.Ensures(Contract.Result<System.IO.TextWriter>() != null); return default(TextWriter); } } public static Encoding OutputEncoding { get { Contract.Ensures(Contract.Result<System.Text.Encoding>() != null); return default(Encoding); } set { } } public static string Title { get { Contract.Ensures(0 <= string.Empty.Length); return default(string); } set { Contract.Ensures(value.Length <= 24500); } } public static bool TreatControlCAsInput { get { return default(bool); } set { } } public static int WindowHeight { get { return default(int); } set { } } public static int WindowLeft { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.WindowTop); Contract.Ensures(System.Console.WindowTop <= 32767); } } public static int WindowTop { get { Contract.Ensures(-32768 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 32767); return default(int); } set { Contract.Ensures(-32768 <= System.Console.WindowLeft); Contract.Ensures(System.Console.WindowLeft <= 32767); } } public static int WindowWidth { get { return default(int); } set { } } #endregion #region Events public static event ConsoleCancelEventHandler CancelKeyPress { add { } remove { } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: TypeInfo ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Notion of a type definition ** ** =============================================================================*/ namespace System.Reflection { using System; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; //all today's runtime Type derivations derive now from TypeInfo //we make TypeInfo implement IRCT - simplifies work [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public abstract class TypeInfo:Type,IReflectableType { [FriendAccessAllowed] internal TypeInfo() { } TypeInfo IReflectableType.GetTypeInfo(){ return this; } public virtual Type AsType(){ return (Type)this; } public virtual Type[] GenericTypeParameters{ get{ if(IsGenericTypeDefinition){ return GetGenericArguments(); } else{ return Type.EmptyTypes; } } } //a re-implementation of ISAF from Type, skipping the use of UnderlyingType [Pure] public virtual bool IsAssignableFrom(TypeInfo typeInfo) { if (typeInfo == null) return false; if (this == typeInfo) return true; // If c is a subclass of this class, then c can be cast to this type. if (typeInfo.IsSubclassOf(this)) return true; if (this.IsInterface) { return typeInfo.ImplementInterface(this); } else if (IsGenericParameter) { Type[] constraints = GetGenericParameterConstraints(); for (int i = 0; i < constraints.Length; i++) if (!constraints[i].IsAssignableFrom(typeInfo)) return false; return true; } return false; } #region moved over from Type // Fields public virtual EventInfo GetDeclaredEvent(String name) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeEvent(GetFullNameForEtw(), name != null ? name : ""); } #endif EventInfo ei = GetEvent(name, Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeEvent(GetFullNameForEtw(), ei != null ? ei.GetFullNameForEtw() : ""); } #endif return ei; } public virtual FieldInfo GetDeclaredField(String name) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeField(GetFullNameForEtw(), name != null ? name : ""); } #endif FieldInfo fi = GetField(name, Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeField(GetFullNameForEtw(), fi != null ? fi.GetFullNameForEtw() : ""); } #endif return fi; } public virtual MethodInfo GetDeclaredMethod(String name) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeMethod(GetFullNameForEtw(), name != null ? name : ""); } #endif MethodInfo mi = GetMethod(name, Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeMethod(GetFullNameForEtw(), mi != null ? mi.GetFullNameForEtw() : ""); } #endif return mi; } public virtual IEnumerable<MethodInfo> GetDeclaredMethods(String name) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeMethods(GetFullNameForEtw()); } #endif foreach (MethodInfo method in GetMethods(Type.DeclaredOnlyLookup)) { if (method.Name == name) yield return method; } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeMethods(GetFullNameForEtw()); } #endif } public virtual System.Reflection.TypeInfo GetDeclaredNestedType(String name) { var nt=GetNestedType(name, Type.DeclaredOnlyLookup); if(nt == null){ return null; //the extension method GetTypeInfo throws for null }else{ return nt.GetTypeInfo(); } } public virtual PropertyInfo GetDeclaredProperty(String name) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeProperty(GetFullNameForEtw(), name != null ? name : ""); } #endif PropertyInfo pi = GetProperty(name, Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeProperty(GetFullNameForEtw(), pi != null ? pi.GetFullNameForEtw() : ""); } #endif return pi; } // Properties public virtual IEnumerable<ConstructorInfo> DeclaredConstructors { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeConstructors(GetFullNameForEtw()); } #endif IEnumerable<ConstructorInfo> constructors = GetConstructors(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeConstructors(GetFullNameForEtw()); } #endif return constructors; } } public virtual IEnumerable<EventInfo> DeclaredEvents { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeEvents(GetFullNameForEtw()); } #endif IEnumerable<EventInfo> events = GetEvents(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeEvents(GetFullNameForEtw()); } #endif return events; } } public virtual IEnumerable<FieldInfo> DeclaredFields { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeFields(GetFullNameForEtw()); } #endif IEnumerable<FieldInfo> fields = GetFields(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeFields(GetFullNameForEtw()); } #endif return fields; } } public virtual IEnumerable<MemberInfo> DeclaredMembers { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeMembers(GetFullNameForEtw()); } #endif IEnumerable<MemberInfo> members = GetMembers(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeMembers(GetFullNameForEtw()); } #endif return members; } } public virtual IEnumerable<MethodInfo> DeclaredMethods { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeMethods(GetFullNameForEtw()); } #endif IEnumerable<MethodInfo> methods = GetMethods(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeMethods(GetFullNameForEtw()); } #endif return methods; } } public virtual IEnumerable<System.Reflection.TypeInfo> DeclaredNestedTypes { get { foreach (var t in GetNestedTypes(Type.DeclaredOnlyLookup)){ yield return t.GetTypeInfo(); } } } public virtual IEnumerable<PropertyInfo> DeclaredProperties { get { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginGetRuntimeProperties(GetFullNameForEtw()); } #endif IEnumerable<PropertyInfo> properties = GetProperties(Type.DeclaredOnlyLookup); #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndGetRuntimeProperties(GetFullNameForEtw()); } #endif return properties; } } public virtual IEnumerable<Type> ImplementedInterfaces { get { return GetInterfaces(); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using FineBot.WepApi.Areas.HelpPage.Models; namespace FineBot.WepApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// BaseDocumenterConfig.cs - base XML documenter config class // Copyright (C) 2001 Kral Ferch, Jason Diamond // Parts Copyright (C) 2004 Kevin Downs // // 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 using System; using System.Collections; using System.ComponentModel; using System.Drawing.Design; using System.Reflection; using System.Windows.Forms.Design; using System.Diagnostics; using System.Xml; namespace NDoc.Core { /// <summary>Provides an abstract base class for documenter configurations.</summary> /// <remarks> /// This is a base class for NDoc Documenter Configs. /// It implements all the methods required by the <see cref="IDocumenterConfig"/> interface. /// It also provides some basic properties which are shared by all configs. /// </remarks> abstract public class BaseDocumenterConfig : IDocumenterConfig { private IDocumenterInfo _info; /// <summary>Initializes a new instance of the <see cref="BaseDocumenterConfig"/> class.</summary> protected BaseDocumenterConfig( IDocumenterInfo info ) { Debug.Assert( info != null ); _info = info; } private Project _Project; /// <summary> /// Gets the <see cref="Project"/> that this config is associated with, if any /// </summary> /// <value>The <see cref="Project"/> that this config is associated with, or a <see langword="null"/> if it is not associated with a project.</value> protected Project Project { get{return _Project;} } /// <summary> /// Creates an instance of a documenter <see cref="IDocumenterConfig.CreateDocumenter"/> /// </summary> /// <returns>IDocumenter instance</returns> public abstract IDocumenter CreateDocumenter(); /// <summary>Associates this config with a <see cref="Project"/>.</summary> /// <param name="project">A <see cref="Project"/> to associate with this config.</param> public void SetProject(Project project) { _Project = project; } /// <summary>Sets the <see cref="NDoc.Core.Project.IsDirty"/> property on the <see cref="Project"/>.</summary> protected void SetDirty() { if (_Project != null) { _Project.IsDirty = true; } } /// <summary> /// Gets the display name of the documenter. /// </summary> [Browsable(false)] public IDocumenterInfo DocumenterInfo { get { return _info;} } /// <summary>Gets an enumerable list of <see cref="PropertyInfo"/> objects representing the properties of this config.</summary> /// <remarks>properties are represented by <see cref="PropertyInfo"/> objects.</remarks> public IEnumerable GetProperties() { ArrayList properties = new ArrayList(); foreach (PropertyInfo property in GetType().GetProperties()) { object[] attr = property.GetCustomAttributes(typeof(BrowsableAttribute),true); if (attr.Length>0) { if( ((BrowsableAttribute)attr[0]).Browsable ) { properties.Add(property); } } else { properties.Add(property); } } return properties; } /// <summary> /// Sets the value of a named config property. /// </summary> /// <param name="name">The name of the property to set.</param> /// <param name="value">A string representation of the desired property value.</param> /// <remarks>Property name matching is case-insensitive.</remarks> public void SetValue(string name, string value) { name = name.ToLower(); foreach (PropertyInfo property in GetType().GetProperties()) { if (name == property.Name.ToLower()) { string result = ReadProperty(property.Name, value); if (result.Length>0) { System.Diagnostics.Trace.WriteLine(result); } } } } /// <summary>Writes the current state of the config to the specified <see cref="XmlWriter"/>.</summary> /// <param name="writer">An open <see cref="XmlWriter"/>.</param> /// <remarks> /// This method uses reflection to serialize the public properties in the config. /// <para> /// A property will <b>not</b> be persisted if, /// <list type="bullet"> /// <item>The value is equal to the default value, or</item> /// <item>The string representation of the value is an empty string, or</item> /// <item>The property has a Browsable(false) attribute, or</item> /// <item>The property has a NonPersisted attribute.</item> /// </list> /// </para> /// </remarks> public void Write(XmlWriter writer) { writer.WriteStartElement("documenter"); writer.WriteAttributeString("name", this.DocumenterInfo.Name ); PropertyInfo[] properties = GetType().GetProperties(); foreach (PropertyInfo property in properties) { if (!property.IsDefined(typeof(NonPersistedAttribute),true)) { object value = property.GetValue(this, null); if (value != null) { bool writeProperty = true; string value2 = Convert.ToString(value); if (value2 != null) { //see if the property has a default value object[] defaultValues=property.GetCustomAttributes(typeof(DefaultValueAttribute),true); if (defaultValues.Length > 0) { if(Convert.ToString(((DefaultValueAttribute)defaultValues[0]).Value)==value2) writeProperty=false; } else { if(value2=="") writeProperty=false; } } else { writeProperty=false; } //being lazy and assuming only one BrowsableAttribute... BrowsableAttribute[] browsableAttributes=(BrowsableAttribute[])property.GetCustomAttributes(typeof(BrowsableAttribute),true); if (browsableAttributes.Length>0 && !browsableAttributes[0].Browsable) { writeProperty=false; } if (writeProperty) { writer.WriteStartElement("property"); writer.WriteAttributeString("name", property.Name); writer.WriteAttributeString("value", value2); writer.WriteEndElement(); } } } } writer.WriteEndElement(); } /// <summary>Loads config details from the specified <see cref="XmlReader"/>.</summary> /// <param name="reader">An <see cref="XmlReader"/> positioned on a &lt;documenter&gt; element.</param> /// <remarks>Each property found in the XML is loaded into current config using <see cref="ReadProperty"/>.</remarks> public void Read(XmlReader reader) { // we don't want to set the project IsDirty flag during the read... _Project.SuspendDirtyCheck=true; string FailureMessages=""; while(!reader.EOF && !(reader.NodeType == XmlNodeType.EndElement && reader.Name == "documenter")) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "property") { FailureMessages += ReadProperty(reader["name"], reader["value"]); } reader.Read(); // Advance. } // Restore the project IsDirty checking. _Project.SuspendDirtyCheck=false; if (FailureMessages.Length > 0) throw new DocumenterPropertyFormatException(FailureMessages); } /// <summary> /// Sets the value of a named property. /// </summary> /// <param name="name">A property name.</param> /// <param name="value">A string respesentation of the desired property value.</param> /// <returns>A string containing any messages generated while attempting to set the property.</returns> protected string ReadProperty(string name, string value) { // if value is an empty string, do not bother with anything else if (value==null) return String.Empty; if (value.Length==0) return String.Empty; string FailureMessages=String.Empty; PropertyInfo property = GetType().GetProperty(name); if (property == null) { FailureMessages += HandleUnknownPropertyType(name, value); } else { bool ValueParsedOK = false; object value2 = null; // if the string in the project file is not a valid member // of the enum, or cannot be parsed into the property type // for some reason,we don't want to throw an exception and // ditch all the settings stored later in the file! // save the exception details, and we will throw a // single exception at the end.. try { if (property.PropertyType.IsEnum) { //parse is now case-insensitive... value2 = Enum.Parse(property.PropertyType, value, true); ValueParsedOK = true; } else { TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType); value2 = tc.ConvertFromString(value); ValueParsedOK = true; } } catch(System.ArgumentException) { Project.SuspendDirtyCheck=false; FailureMessages += HandleUnknownPropertyValue(property, value); Project.SuspendDirtyCheck=true; } catch(System.FormatException) { Project.SuspendDirtyCheck=false; FailureMessages += HandleUnknownPropertyValue(property, value); Project.SuspendDirtyCheck=true; } // any other exception will be thrown immediately if (property.CanWrite && ValueParsedOK) { property.SetValue(this, value2, null); } } return FailureMessages; } /// <summary> /// When overridden in a derived class, handles a property found by <see cref="Read"/> which does not /// correspond to any property in the config object. /// </summary> /// <param name="name">The unknown property name.</param> /// <param name="value">A string representation of the desired property value.</param> /// <returns>A string containing any messages generated by the handler.</returns> /// <remarks> /// As implemented in this class, no action is taken. /// <note type="inheritinfo"> /// <para>If a handler can translate the unknown property, it can call the protected method /// <see cref="ReadProperty"/> to process to translated name/value.</para> /// </note> /// </remarks> protected virtual string HandleUnknownPropertyType(string name, string value) { // As a default, we will ignore unknown property types return ""; } /// <summary> /// When overridden in a derived class, handles a unknown or invalid property value read by <see cref="Read"/>. /// </summary> /// <param name="property">A valid Property name.</param> /// <param name="value">A string representation of the desired property value.</param> /// <returns>A string containing any messages generated by the handler.</returns> /// <remarks> /// As implemented in this class, an error message is returned which details the /// property name, type and the invalid value. /// <note type="inheritinfo"> /// <para>If a handler can translate the unknown value, it can call the protected method <see cref="ReadProperty"/> to /// process to translated name/value.</para> /// </note> /// </remarks> protected virtual string HandleUnknownPropertyValue(PropertyInfo property, string value) { // we cannot handle this, so return an error message return String.Format(" Property '{0}' has an invalid value for type {1} ('{2}') \n", property.Name, property.PropertyType.ToString() ,value); } #region Documentation Main Settings private bool _CleanIntermediates = false; /// <summary>Gets or sets a value indicating whether to delete intermediate files after a successful build.</summary> /// <remarks> /// <value> /// <see langword="true"/> if intermediate files should be deleted after a successful build; /// otherwise, <see langword="false"/>. By default, the value of this property is <see langword="false"/>.</value> /// <para>For documenters that result in a compiled output, like the MSDN and VS.NET /// documenters, intermediate files include all of the HTML Help project files, as well as the generated /// HTML files.</para></remarks> [Category("Documentation Main Settings")] [Description("When true, intermediate files will be deleted after a successful build.")] [DefaultValue(false)] public bool CleanIntermediates { get { return _CleanIntermediates; } set { _CleanIntermediates = value; SetDirty(); } } #endregion } /// <summary> /// /// </summary> [AttributeUsage(AttributeTargets.Property)] public class NonPersistedAttribute : Attribute { } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Microsoft.CodeAnalysis.MSBuild { internal sealed partial class SolutionFile { private readonly IEnumerable<string> _headerLines; private readonly string _visualStudioVersionLineOpt; private readonly string _minimumVisualStudioVersionLineOpt; private readonly IEnumerable<ProjectBlock> _projectBlocks; private readonly IEnumerable<SectionBlock> _globalSectionBlocks; public SolutionFile( IEnumerable<string> headerLines, string visualStudioVersionLineOpt, string minimumVisualStudioVersionLineOpt, IEnumerable<ProjectBlock> projectBlocks, IEnumerable<SectionBlock> globalSectionBlocks) { if (headerLines == null) { throw new ArgumentNullException(nameof(headerLines)); } if (projectBlocks == null) { throw new ArgumentNullException(nameof(projectBlocks)); } if (globalSectionBlocks == null) { throw new ArgumentNullException(nameof(globalSectionBlocks)); } _headerLines = headerLines.ToList().AsReadOnly(); _visualStudioVersionLineOpt = visualStudioVersionLineOpt; _minimumVisualStudioVersionLineOpt = minimumVisualStudioVersionLineOpt; _projectBlocks = projectBlocks.ToList().AsReadOnly(); _globalSectionBlocks = globalSectionBlocks.ToList().AsReadOnly(); } public IEnumerable<string> HeaderLines { get { return _headerLines; } } public string VisualStudioVersionLineOpt { get { return _visualStudioVersionLineOpt; } } public string MinimumVisualStudioVersionLineOpt { get { return _minimumVisualStudioVersionLineOpt; } } public IEnumerable<ProjectBlock> ProjectBlocks { get { return _projectBlocks; } } public IEnumerable<SectionBlock> GlobalSectionBlocks { get { return _globalSectionBlocks; } } public string GetText() { var builder = new StringBuilder(); builder.AppendLine(); foreach (var headerLine in _headerLines) { builder.AppendLine(headerLine); } foreach (var block in _projectBlocks) { builder.Append(block.GetText()); } builder.AppendLine("Global"); foreach (var block in _globalSectionBlocks) { builder.Append(block.GetText(indent: 1)); } builder.AppendLine("EndGlobal"); return builder.ToString(); } public static SolutionFile Parse(TextReader reader) { var headerLines = new List<string>(); var headerLine1 = GetNextNonEmptyLine(reader); if (headerLine1 == null || !headerLine1.StartsWith("Microsoft Visual Studio Solution File", StringComparison.Ordinal)) { throw new Exception(string.Format(WorkspacesResources.Expected_header_colon_0, "Microsoft Visual Studio Solution File")); } headerLines.Add(headerLine1); // skip comment lines and empty lines while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek())) { headerLines.Add(reader.ReadLine()); } string visualStudioVersionLineOpt = null; if (reader.Peek() == 'V') { visualStudioVersionLineOpt = GetNextNonEmptyLine(reader); if (!visualStudioVersionLineOpt.StartsWith("VisualStudioVersion", StringComparison.Ordinal)) { throw new Exception(string.Format(WorkspacesResources.Expected_header_colon_0, "VisualStudioVersion")); } } string minimumVisualStudioVersionLineOpt = null; if (reader.Peek() == 'M') { minimumVisualStudioVersionLineOpt = GetNextNonEmptyLine(reader); if (!minimumVisualStudioVersionLineOpt.StartsWith("MinimumVisualStudioVersion", StringComparison.Ordinal)) { throw new Exception(string.Format(WorkspacesResources.Expected_header_colon_0, "MinimumVisualStudioVersion")); } } var projectBlocks = new List<ProjectBlock>(); // Parse project blocks while we have them while (reader.Peek() == 'P') { projectBlocks.Add(ProjectBlock.Parse(reader)); while (reader.Peek() != -1 && "#\r\n".Contains((char)reader.Peek())) { // Comments and Empty Lines between the Project Blocks are skipped reader.ReadLine(); } } // We now have a global block var globalSectionBlocks = ParseGlobal(reader); // We should now be at the end of the file if (reader.Peek() != -1) { throw new Exception(WorkspacesResources.Expected_end_of_file); } return new SolutionFile(headerLines, visualStudioVersionLineOpt, minimumVisualStudioVersionLineOpt, projectBlocks, globalSectionBlocks); } [SuppressMessage("", "RS0001")] // TODO: This suppression should be removed once we have rulesets in place for Roslyn.sln private static IEnumerable<SectionBlock> ParseGlobal(TextReader reader) { if (reader.Peek() == -1) { return Enumerable.Empty<SectionBlock>(); } if (GetNextNonEmptyLine(reader) != "Global") { throw new Exception(string.Format(WorkspacesResources.Expected_0_line, "Global")); } var globalSectionBlocks = new List<SectionBlock>(); // The blocks inside here are indented while (reader.Peek() != -1 && char.IsWhiteSpace((char)reader.Peek())) { globalSectionBlocks.Add(SectionBlock.Parse(reader)); } if (GetNextNonEmptyLine(reader) != "EndGlobal") { throw new Exception(string.Format(WorkspacesResources.Expected_0_line, "EndGlobal")); } // Consume potential empty lines at the end of the global block while (reader.Peek() != -1 && "\r\n".Contains((char)reader.Peek())) { reader.ReadLine(); } return globalSectionBlocks; } private static string GetNextNonEmptyLine(TextReader reader) { string line = null; do { line = reader.ReadLine(); } while (line != null && line.Trim() == string.Empty); return line; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aardvark.Base { public class Spectrum { public double FirstWaveLength; public double DeltaWaveLength; public double[] Data; public Spectrum(double firstWaveLength, double deltaWaveLength, double[] data) { FirstWaveLength = firstWaveLength; DeltaWaveLength = deltaWaveLength; Data = data; } public static readonly Spectrum CieXYZ31X = new Spectrum(360, 1, SpectralData.CieXYZ31_X_360_830_1nm); public static readonly Spectrum CieXYZ31Y = new Spectrum(360, 1, SpectralData.CieXYZ31_Y_360_830_1nm); public static readonly Spectrum CieXYZ31Z = new Spectrum(360, 1, SpectralData.CieXYZ31_Z_360_830_1nm); public static readonly Spectrum CieIlluminantA = new Spectrum(300, 1, SpectralData.CieIlluminantA_300_830_1nm); public static readonly Spectrum CieIlluminantD65 = new Spectrum(300, 1, SpectralData.CieIlluminantD65_300_830_1nm); } public static class SpectralData { #region CIE XYZ 1931 Color Matching Functions 360-830nm in 1nm steps public static readonly double[] CieXYZ31_X_360_830_1nm = { 0.0001299, 0.000145847, 0.000163802, 0.000184004, 0.00020669, 0.0002321, 0.000260728, 0.000293075, 0.000329388, 0.000369914, 0.0004149, 0.000464159, 0.000518986, 0.000581854, 0.000655235, 0.0007416, 0.00084503, 0.000964527, 0.001094949, 0.001231154, 0.001368, 0.00150205, 0.001642328, 0.001802382, 0.001995757, 0.002236, 0.002535385, 0.002892603, 0.003300829, 0.003753236, 0.004243, 0.004762389, 0.005330048, 0.005978712, 0.006741117, 0.00765, 0.008751373, 0.01002888, 0.0114217, 0.01286901, 0.01431, 0.01570443, 0.01714744, 0.01878122, 0.02074801, 0.02319, 0.02620736, 0.02978248, 0.03388092, 0.03846824, 0.04351, 0.0489956, 0.0550226, 0.0617188, 0.069212, 0.07763, 0.08695811, 0.09717672, 0.1084063, 0.1207672, 0.13438, 0.1493582, 0.1653957, 0.1819831, 0.198611, 0.21477, 0.2301868, 0.2448797, 0.2587773, 0.2718079, 0.2839, 0.2949438, 0.3048965, 0.3137873, 0.3216454, 0.3285, 0.3343513, 0.3392101, 0.3431213, 0.3461296, 0.34828, 0.3495999, 0.3501474, 0.350013, 0.349287, 0.34806, 0.3463733, 0.3442624, 0.3418088, 0.3390941, 0.3362, 0.3331977, 0.3300411, 0.3266357, 0.3228868, 0.3187, 0.3140251, 0.308884, 0.3032904, 0.2972579, 0.2908, 0.2839701, 0.2767214, 0.2689178, 0.2604227, 0.2511, 0.2408475, 0.2298512, 0.2184072, 0.2068115, 0.19536, 0.1842136, 0.1733273, 0.1626881, 0.1522833, 0.1421, 0.1321786, 0.1225696, 0.1132752, 0.1042979, 0.09564, 0.08729955, 0.07930804, 0.07171776, 0.06458099, 0.05795001, 0.05186211, 0.04628152, 0.04115088, 0.03641283, 0.03201, 0.0279172, 0.0241444, 0.020687, 0.0175404, 0.0147, 0.01216179, 0.00991996, 0.00796724, 0.006296346, 0.0049, 0.003777173, 0.00294532, 0.00242488, 0.002236293, 0.0024, 0.00292552, 0.00383656, 0.00517484, 0.00698208, 0.0093, 0.01214949, 0.01553588, 0.01947752, 0.02399277, 0.0291, 0.03481485, 0.04112016, 0.04798504, 0.05537861, 0.06327, 0.07163501, 0.08046224, 0.08973996, 0.09945645, 0.1096, 0.1201674, 0.1311145, 0.1423679, 0.1538542, 0.1655, 0.1772571, 0.18914, 0.2011694, 0.2133658, 0.2257499, 0.2383209, 0.2510668, 0.2639922, 0.2771017, 0.2904, 0.3038912, 0.3175726, 0.3314384, 0.3454828, 0.3597, 0.3740839, 0.3886396, 0.4033784, 0.4183115, 0.4334499, 0.4487953, 0.464336, 0.480064, 0.4959713, 0.5120501, 0.5282959, 0.5446916, 0.5612094, 0.5778215, 0.5945, 0.6112209, 0.6279758, 0.6447602, 0.6615697, 0.6784, 0.6952392, 0.7120586, 0.7288284, 0.7455188, 0.7621, 0.7785432, 0.7948256, 0.8109264, 0.8268248, 0.8425, 0.8579325, 0.8730816, 0.8878944, 0.9023181, 0.9163, 0.9297995, 0.9427984, 0.9552776, 0.9672179, 0.9786, 0.9893856, 0.9995488, 1.0090892, 1.0180064, 1.0263, 1.0339827, 1.040986, 1.047188, 1.0524667, 1.0567, 1.0597944, 1.0617992, 1.0628068, 1.0629096, 1.0622, 1.0607352, 1.0584436, 1.0552244, 1.0509768, 1.0456, 1.0390369, 1.0313608, 1.0226662, 1.0130477, 1.0026, 0.9913675, 0.9793314, 0.9664916, 0.9528479, 0.9384, 0.923194, 0.907244, 0.890502, 0.87292, 0.8544499, 0.835084, 0.814946, 0.794186, 0.772954, 0.7514, 0.7295836, 0.7075888, 0.6856022, 0.6638104, 0.6424, 0.6215149, 0.6011138, 0.5811052, 0.5613977, 0.5419, 0.5225995, 0.5035464, 0.4847436, 0.4661939, 0.4479, 0.4298613, 0.412098, 0.394644, 0.3775333, 0.3608, 0.3444563, 0.3285168, 0.3130192, 0.2980011, 0.2835, 0.2695448, 0.2561184, 0.2431896, 0.2307272, 0.2187, 0.2070971, 0.1959232, 0.1851708, 0.1748323, 0.1649, 0.1553667, 0.14623, 0.13749, 0.1291467, 0.1212, 0.1136397, 0.106465, 0.09969044, 0.09333061, 0.0874, 0.08190096, 0.07680428, 0.07207712, 0.06768664, 0.0636, 0.05980685, 0.05628216, 0.05297104, 0.04981861, 0.04677, 0.04378405, 0.04087536, 0.03807264, 0.03540461, 0.0329, 0.03056419, 0.02838056, 0.02634484, 0.02445275, 0.0227, 0.02108429, 0.01959988, 0.01823732, 0.01698717, 0.01584, 0.01479064, 0.01383132, 0.01294868, 0.0121292, 0.01135916, 0.01062935, 0.009938846, 0.009288422, 0.008678854, 0.008110916, 0.007582388, 0.007088746, 0.006627313, 0.006195408, 0.005790346, 0.005409826, 0.005052583, 0.004717512, 0.004403507, 0.004109457, 0.003833913, 0.003575748, 0.003334342, 0.003109075, 0.002899327, 0.002704348, 0.00252302, 0.002354168, 0.002196616, 0.00204919, 0.00191096, 0.001781438, 0.00166011, 0.001546459, 0.001439971, 0.001340042, 0.001246275, 0.001158471, 0.00107643, 0.000999949, 0.000928736, 0.000862433, 0.00080075, 0.000743396, 0.000690079, 0.000640516, 0.000594502, 0.000551865, 0.000512429, 0.000476021, 0.000442454, 0.000411512, 0.000382981, 0.000356649, 0.000332301, 0.000309759, 0.000288887, 0.000269539, 0.000251568, 0.000234826, 0.000219171, 0.000204526, 0.000190841, 0.000178065, 0.000166151, 0.000155024, 0.000144622, 0.00013491, 0.000125852, 0.000117413, 0.000109552, 0.000102225, 9.53945E-05, 8.90239E-05, 8.30753E-05, 7.75127E-05, 7.2313E-05, 6.74578E-05, 6.29284E-05, 5.87065E-05, 5.47703E-05, 5.10992E-05, 4.76765E-05, 4.44857E-05, 4.15099E-05, 3.87332E-05, 3.6142E-05, 3.37235E-05, 3.14649E-05, 2.93533E-05, 2.73757E-05, 2.55243E-05, 2.37938E-05, 2.21787E-05, 2.06738E-05, 1.92723E-05, 1.79664E-05, 1.67499E-05, 1.56165E-05, 1.45598E-05, 1.35739E-05, 1.26544E-05, 1.17972E-05, 1.09984E-05, 1.0254E-05, 9.55965E-06, 8.91204E-06, 8.30836E-06, 7.74577E-06, 7.22146E-06, 6.73248E-06, 6.27642E-06, 5.8513E-06, 5.45512E-06, 5.08587E-06, 4.74147E-06, 4.42024E-06, 4.12078E-06, 3.84172E-06, 3.58165E-06, 3.33913E-06, 3.11295E-06, 2.90212E-06, 2.70565E-06, 2.52253E-06, 2.35173E-06, 2.19242E-06, 2.0439E-06, 1.9055E-06, 1.77651E-06, 1.65622E-06, 1.54402E-06, 1.43944E-06, 1.34198E-06, 1.25114E-06 }; public static readonly double[] CieXYZ31_Y_360_830_1nm = { 0.000003917, 4.39358E-06, 4.9296E-06, 5.53214E-06, 6.20825E-06, 0.000006965, 7.81322E-06, 8.76734E-06, 9.83984E-06, 1.10432E-05, 0.00001239, 1.38864E-05, 1.55573E-05, 1.7443E-05, 1.95838E-05, 0.00002202, 2.48397E-05, 2.80413E-05, 3.1531E-05, 3.52152E-05, 0.000039, 4.28264E-05, 4.69146E-05, 5.15896E-05, 5.71764E-05, 0.000064, 7.23442E-05, 8.22122E-05, 9.35082E-05, 0.000106136, 0.00012, 0.000134984, 0.000151492, 0.000170208, 0.000191816, 0.000217, 0.000246907, 0.00028124, 0.00031852, 0.000357267, 0.000396, 0.000433715, 0.000473024, 0.000517876, 0.000572219, 0.00064, 0.00072456, 0.0008255, 0.00094116, 0.00106988, 0.00121, 0.001362091, 0.001530752, 0.001720368, 0.001935323, 0.00218, 0.0024548, 0.002764, 0.0031178, 0.0035264, 0.004, 0.00454624, 0.00515932, 0.00582928, 0.00654616, 0.0073, 0.008086507, 0.00890872, 0.00976768, 0.01066443, 0.0116, 0.01257317, 0.01358272, 0.01462968, 0.01571509, 0.01684, 0.01800736, 0.01921448, 0.02045392, 0.02171824, 0.023, 0.02429461, 0.02561024, 0.02695857, 0.02835125, 0.0298, 0.03131083, 0.03288368, 0.03452112, 0.03622571, 0.038, 0.03984667, 0.041768, 0.043766, 0.04584267, 0.048, 0.05024368, 0.05257304, 0.05498056, 0.05745872, 0.06, 0.06260197, 0.06527752, 0.06804208, 0.07091109, 0.0739, 0.077016, 0.0802664, 0.0836668, 0.0872328, 0.09098, 0.09491755, 0.09904584, 0.1033674, 0.1078846, 0.1126, 0.117532, 0.1226744, 0.1279928, 0.1334528, 0.13902, 0.1446764, 0.1504693, 0.1564619, 0.1627177, 0.1693, 0.1762431, 0.1835581, 0.1912735, 0.199418, 0.20802, 0.2171199, 0.2267345, 0.2368571, 0.2474812, 0.2586, 0.2701849, 0.2822939, 0.2950505, 0.308578, 0.323, 0.3384021, 0.3546858, 0.3716986, 0.3892875, 0.4073, 0.4256299, 0.4443096, 0.4633944, 0.4829395, 0.503, 0.5235693, 0.544512, 0.56569, 0.5869653, 0.6082, 0.6293456, 0.6503068, 0.6708752, 0.6908424, 0.71, 0.7281852, 0.7454636, 0.7619694, 0.7778368, 0.7932, 0.8081104, 0.8224962, 0.8363068, 0.8494916, 0.862, 0.8738108, 0.8849624, 0.8954936, 0.9054432, 0.9148501, 0.9237348, 0.9320924, 0.9399226, 0.9472252, 0.954, 0.9602561, 0.9660074, 0.9712606, 0.9760225, 0.9803, 0.9840924, 0.9874182, 0.9903128, 0.9928116, 0.9949501, 0.9967108, 0.9980983, 0.999112, 0.9997482, 1, 0.9998567, 0.9993046, 0.9983255, 0.9968987, 0.995, 0.9926005, 0.9897426, 0.9864444, 0.9827241, 0.9786, 0.9740837, 0.9691712, 0.9638568, 0.9581349, 0.952, 0.9454504, 0.9384992, 0.9311628, 0.9234576, 0.9154, 0.9070064, 0.8982772, 0.8892048, 0.8797816, 0.87, 0.8598613, 0.849392, 0.838622, 0.8275813, 0.8163, 0.8047947, 0.793082, 0.781192, 0.7691547, 0.757, 0.7447541, 0.7324224, 0.7200036, 0.7074965, 0.6949, 0.6822192, 0.6694716, 0.6566744, 0.6438448, 0.631, 0.6181555, 0.6053144, 0.5924756, 0.5796379, 0.5668, 0.5539611, 0.5411372, 0.5283528, 0.5156323, 0.503, 0.4904688, 0.4780304, 0.4656776, 0.4534032, 0.4412, 0.42908, 0.417036, 0.405032, 0.393032, 0.381, 0.3689184, 0.3568272, 0.3447768, 0.3328176, 0.321, 0.3093381, 0.2978504, 0.2865936, 0.2756245, 0.265, 0.2547632, 0.2448896, 0.2353344, 0.2260528, 0.217, 0.2081616, 0.1995488, 0.1911552, 0.1829744, 0.175, 0.1672235, 0.1596464, 0.1522776, 0.1451259, 0.1382, 0.1315003, 0.1250248, 0.1187792, 0.1127691, 0.107, 0.1014762, 0.09618864, 0.09112296, 0.08626485, 0.0816, 0.07712064, 0.07282552, 0.06871008, 0.06476976, 0.061, 0.05739621, 0.05395504, 0.05067376, 0.04754965, 0.04458, 0.04175872, 0.03908496, 0.03656384, 0.03420048, 0.032, 0.02996261, 0.02807664, 0.02632936, 0.02470805, 0.0232, 0.02180077, 0.02050112, 0.01928108, 0.01812069, 0.017, 0.01590379, 0.01483718, 0.01381068, 0.01283478, 0.01192, 0.01106831, 0.01027339, 0.009533311, 0.008846157, 0.00821, 0.007623781, 0.007085424, 0.006591476, 0.006138485, 0.005723, 0.005343059, 0.004995796, 0.004676404, 0.004380075, 0.004102, 0.003838453, 0.003589099, 0.003354219, 0.003134093, 0.002929, 0.002738139, 0.002559876, 0.002393244, 0.002237275, 0.002091, 0.001953587, 0.00182458, 0.00170358, 0.001590187, 0.001484, 0.001384496, 0.001291268, 0.001204092, 0.001122744, 0.001047, 0.00097659, 0.000911109, 0.000850133, 0.000793238, 0.00074, 0.000690083, 0.00064331, 0.000599496, 0.000558455, 0.00052, 0.000483914, 0.000450053, 0.000418345, 0.000388718, 0.0003611, 0.000335384, 0.00031144, 0.000289166, 0.000268454, 0.0002492, 0.000231302, 0.000214686, 0.000199288, 0.000185048, 0.0001719, 0.000159778, 0.000148604, 0.000138302, 0.000128793, 0.00012, 0.00011186, 0.000104322, 9.73356E-05, 9.08459E-05, 0.0000848, 7.91467E-05, 0.000073858, 0.000068916, 6.43027E-05, 0.00006, 5.59819E-05, 5.22256E-05, 4.87184E-05, 4.54475E-05, 0.0000424, 3.9561E-05, 3.69151E-05, 3.44487E-05, 3.21482E-05, 0.00003, 2.79913E-05, 2.61136E-05, 2.43602E-05, 2.27246E-05, 0.0000212, 1.97786E-05, 1.84529E-05, 1.72169E-05, 1.60646E-05, 0.00001499, 1.39873E-05, 1.30516E-05, 1.21782E-05, 1.13625E-05, 0.0000106, 9.88588E-06, 9.2173E-06, 8.59236E-06, 8.00913E-06, 7.4657E-06, 6.95957E-06, 6.488E-06, 6.0487E-06, 5.6394E-06, 5.2578E-06, 4.90177E-06, 4.56972E-06, 4.26019E-06, 3.97174E-06, 3.7029E-06, 3.45216E-06, 3.2183E-06, 3.0003E-06, 2.79714E-06, 2.6078E-06, 2.43122E-06, 2.26653E-06, 2.11301E-06, 1.96994E-06, 1.8366E-06, 1.71223E-06, 1.59623E-06, 1.48809E-06, 1.38731E-06, 1.2934E-06, 1.20582E-06, 1.12414E-06, 1.04801E-06, 9.77058E-07, 9.1093E-07, 8.49251E-07, 7.91721E-07, 7.3809E-07, 6.8811E-07, 6.4153E-07, 5.9809E-07, 5.57575E-07, 5.19808E-07, 4.84612E-07, 4.5181E-07 }; public static readonly double[] CieXYZ31_Z_360_830_1nm = { 0.0006061, 0.000680879, 0.000765146, 0.000860012, 0.000966593, 0.001086, 0.001220586, 0.001372729, 0.001543579, 0.001734286, 0.001946, 0.002177777, 0.002435809, 0.002731953, 0.003078064, 0.003486, 0.003975227, 0.00454088, 0.00515832, 0.005802907, 0.006450001, 0.007083216, 0.007745488, 0.008501152, 0.009414544, 0.01054999, 0.0119658, 0.01365587, 0.01558805, 0.01773015, 0.02005001, 0.02251136, 0.02520288, 0.02827972, 0.03189704, 0.03621, 0.04143771, 0.04750372, 0.05411988, 0.06099803, 0.06785001, 0.07448632, 0.08136156, 0.08915364, 0.09854048, 0.1102, 0.1246133, 0.1417017, 0.1613035, 0.1832568, 0.2074, 0.2336921, 0.2626114, 0.2947746, 0.3307985, 0.3713, 0.4162091, 0.4654642, 0.5196948, 0.5795303, 0.6456, 0.7184838, 0.7967133, 0.8778459, 0.959439, 1.0390501, 1.1153673, 1.1884971, 1.2581233, 1.3239296, 1.3856, 1.4426352, 1.4948035, 1.5421903, 1.5848807, 1.62296, 1.6564048, 1.6852959, 1.7098745, 1.7303821, 1.74706, 1.7600446, 1.7696233, 1.7762637, 1.7804334, 1.7826, 1.7829682, 1.7816998, 1.7791982, 1.7758671, 1.77211, 1.7682589, 1.764039, 1.7589438, 1.7524663, 1.7441, 1.7335595, 1.7208581, 1.7059369, 1.6887372, 1.6692, 1.6475287, 1.6234127, 1.5960223, 1.564528, 1.5281, 1.4861114, 1.4395215, 1.3898799, 1.3387362, 1.28764, 1.2374223, 1.1878243, 1.1387611, 1.090148, 1.0419, 0.9941976, 0.9473473, 0.9014531, 0.8566193, 0.8129501, 0.7705173, 0.7294448, 0.6899136, 0.6521049, 0.6162, 0.5823286, 0.5504162, 0.5203376, 0.4919673, 0.46518, 0.4399246, 0.4161836, 0.3938822, 0.3729459, 0.3533, 0.3348578, 0.3175521, 0.3013375, 0.2861686, 0.272, 0.2588171, 0.2464838, 0.2347718, 0.2234533, 0.2123, 0.2011692, 0.1901196, 0.1792254, 0.1685608, 0.1582, 0.1481383, 0.1383758, 0.1289942, 0.1200751, 0.1117, 0.1039048, 0.09666748, 0.08998272, 0.08384531, 0.07824999, 0.07320899, 0.06867816, 0.06456784, 0.06078835, 0.05725001, 0.05390435, 0.05074664, 0.04775276, 0.04489859, 0.04216, 0.03950728, 0.03693564, 0.03445836, 0.03208872, 0.02984, 0.02771181, 0.02569444, 0.02378716, 0.02198925, 0.0203, 0.01871805, 0.01724036, 0.01586364, 0.01458461, 0.0134, 0.01230723, 0.01130188, 0.01037792, 0.009529306, 0.008749999, 0.0080352, 0.0073816, 0.0067854, 0.0062428, 0.005749999, 0.0053036, 0.0048998, 0.0045342, 0.0042024, 0.0039, 0.0036232, 0.0033706, 0.0031414, 0.0029348, 0.002749999, 0.0025852, 0.0024386, 0.0023094, 0.0021968, 0.0021, 0.002017733, 0.0019482, 0.0018898, 0.001840933, 0.0018, 0.001766267, 0.0017378, 0.0017112, 0.001683067, 0.001650001, 0.001610133, 0.0015644, 0.0015136, 0.001458533, 0.0014, 0.001336667, 0.00127, 0.001205, 0.001146667, 0.0011, 0.0010688, 0.0010494, 0.0010356, 0.0010212, 0.001, 0.00096864, 0.00092992, 0.00088688, 0.00084256, 0.0008, 0.00076096, 0.00072368, 0.00068592, 0.00064544, 0.0006, 0.000547867, 0.0004916, 0.0004354, 0.000383467, 0.00034, 0.000307253, 0.00028316, 0.00026544, 0.000251813, 0.00024, 0.000229547, 0.00022064, 0.00021196, 0.000202187, 0.00019, 0.000174213, 0.00015564, 0.00013596, 0.000116853, 0.0001, 8.61333E-05, 0.0000746, 0.000065, 5.69333E-05, 5E-05, 0.00004416, 0.00003948, 0.00003572, 0.00003264, 0.00003, 2.76533E-05, 0.00002556, 0.00002364, 2.18133E-05, 0.00002, 1.81333E-05, 0.0000162, 0.0000142, 1.21333E-05, 0.00001, 7.73333E-06, 0.0000054, 0.0000032, 1.33333E-06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #endregion #region CIE Illuminant A Spectral Distribution 300-830nm in 1nm steps public static readonly double[] CieIlluminantA_300_830_1nm = { 0.930483, 0.967643, 1.00597, 1.04549, 1.08623, 1.12821, 1.17147, 1.21602, 1.26188, 1.3091, 1.35769, 1.40768, 1.4591, 1.51198, 1.56633, 1.62219, 1.67959, 1.73855, 1.7991, 1.86127, 1.92508, 1.99057, 2.05776, 2.12667, 2.19734, 2.2698, 2.34406, 2.42017, 2.49814, 2.57801, 2.65981, 2.74355, 2.82928, 2.91701, 3.00678, 3.09861, 3.19253, 3.28857, 3.38676, 3.48712, 3.58968, 3.69447, 3.80152, 3.91085, 4.0225, 4.13648, 4.25282, 4.37156, 4.49272, 4.61631, 4.74238, 4.87095, 5.00204, 5.13568, 5.27189, 5.4107, 5.55213, 5.69622, 5.84298, 5.99244, 6.14462, 6.29955, 6.45724, 6.61774, 6.78105, 6.9472, 7.11621, 7.28811, 7.46292, 7.64066, 7.82135, 8.00501, 8.19167, 8.38134, 8.57404, 8.7698, 8.96864, 9.17056, 9.37561, 9.58378, 9.7951, 10.0096, 10.2273, 10.4481, 10.6722, 10.8996, 11.1302, 11.364, 11.6012, 11.8416, 12.0853, 12.3324, 12.5828, 12.8366, 13.0938, 13.3543, 13.6182, 13.8855, 14.1563, 14.4304, 14.708, 14.9891, 15.2736, 15.5616, 15.853, 16.148, 16.4464, 16.7484, 17.0538, 17.3628, 17.6753, 17.9913, 18.3108, 18.6339, 18.9605, 19.2907, 19.6244, 19.9617, 20.3026, 20.647, 20.995, 21.3465, 21.7016, 22.0603, 22.4225, 22.7883, 23.1577, 23.5307, 23.9072, 24.2873, 24.6709, 25.0581, 25.4489, 25.8432, 26.2411, 26.6425, 27.0475, 27.456, 27.8681, 28.2836, 28.7027, 29.1253, 29.5515, 29.9811, 30.4142, 30.8508, 31.2909, 31.7345, 32.1815, 32.632, 33.0859, 33.5432, 34.004, 34.4682, 34.9358, 35.4068, 35.8811, 36.3588, 36.8399, 37.3243, 37.8121, 38.3031, 38.7975, 39.2951, 39.796, 40.3002, 40.8076, 41.3182, 41.832, 42.3491, 42.8693, 43.3926, 43.9192, 44.4488, 44.9816, 45.5174, 46.0563, 46.5983, 47.1433, 47.6913, 48.2423, 48.7963, 49.3533, 49.9132, 50.476, 51.0418, 51.6104, 52.1818, 52.7561, 53.3332, 53.9132, 54.4958, 55.0813, 55.6694, 56.2603, 56.8539, 57.4501, 58.0489, 58.6504, 59.2545, 59.8611, 60.4703, 61.082, 61.6962, 62.3128, 62.932, 63.5535, 64.1775, 64.8038, 65.4325, 66.0635, 66.6968, 67.3324, 67.9702, 68.6102, 69.2525, 69.8969, 70.5435, 71.1922, 71.843, 72.4959, 73.1508, 73.8077, 74.4666, 75.1275, 75.7903, 76.4551, 77.1217, 77.7902, 78.4605, 79.1326, 79.8065, 80.4821, 81.1595, 81.8386, 82.5193, 83.2017, 83.8856, 84.5712, 85.2584, 85.947, 86.6372, 87.3288, 88.0219, 88.7165, 89.4124, 90.1097, 90.8083, 91.5082, 92.2095, 92.912, 93.6157, 94.3206, 95.0267, 95.7339, 96.4423, 97.1518, 97.8623, 98.5739, 99.2864, 100, 100.715, 101.43, 102.146, 102.864, 103.582, 104.301, 105.02, 105.741, 106.462, 107.184, 107.906, 108.63, 109.354, 110.078, 110.803, 111.529, 112.255, 112.982, 113.709, 114.436, 115.164, 115.893, 116.622, 117.351, 118.08, 118.81, 119.54, 120.27, 121.001, 121.731, 122.462, 123.193, 123.924, 124.655, 125.386, 126.118, 126.849, 127.58, 128.312, 129.043, 129.774, 130.505, 131.236, 131.966, 132.697, 133.427, 134.157, 134.887, 135.617, 136.346, 137.075, 137.804, 138.532, 139.26, 139.988, 140.715, 141.441, 142.167, 142.893, 143.618, 144.343, 145.067, 145.79, 146.513, 147.235, 147.957, 148.678, 149.398, 150.117, 150.836, 151.554, 152.271, 152.988, 153.704, 154.418, 155.132, 155.845, 156.558, 157.269, 157.979, 158.689, 159.397, 160.104, 160.811, 161.516, 162.221, 162.924, 163.626, 164.327, 165.028, 165.726, 166.424, 167.121, 167.816, 168.51, 169.203, 169.895, 170.586, 171.275, 171.963, 172.65, 173.335, 174.019, 174.702, 175.383, 176.063, 176.741, 177.419, 178.094, 178.769, 179.441, 180.113, 180.783, 181.451, 182.118, 182.783, 183.447, 184.109, 184.77, 185.429, 186.087, 186.743, 187.397, 188.05, 188.701, 189.35, 189.998, 190.644, 191.288, 191.931, 192.572, 193.211, 193.849, 194.484, 195.118, 195.75, 196.381, 197.009, 197.636, 198.261, 198.884, 199.506, 200.125, 200.743, 201.359, 201.972, 202.584, 203.195, 203.803, 204.409, 205.013, 205.616, 206.216, 206.815, 207.411, 208.006, 208.599, 209.189, 209.778, 210.365, 210.949, 211.532, 212.112, 212.691, 213.268, 213.842, 214.415, 214.985, 215.553, 216.12, 216.684, 217.246, 217.806, 218.364, 218.92, 219.473, 220.025, 220.574, 221.122, 221.667, 222.21, 222.751, 223.29, 223.826, 224.361, 224.893, 225.423, 225.951, 226.477, 227, 227.522, 228.041, 228.558, 229.073, 229.585, 230.096, 230.604, 231.11, 231.614, 232.115, 232.615, 233.112, 233.606, 234.099, 234.589, 235.078, 235.564, 236.047, 236.529, 237.008, 237.485, 237.959, 238.432, 238.902, 239.37, 239.836, 240.299, 240.76, 241.219, 241.675, 242.13, 242.582, 243.031, 243.479, 243.924, 244.367, 244.808, 245.246, 245.682, 246.116, 246.548, 246.977, 247.404, 247.829, 248.251, 248.671, 249.089, 249.505, 249.918, 250.329, 250.738, 251.144, 251.548, 251.95, 252.35, 252.747, 253.142, 253.535, 253.925, 254.314, 254.7, 255.083, 255.465, 255.844, 256.221, 256.595, 256.968, 257.338, 257.706, 258.071, 258.434, 258.795, 259.154, 259.511, 259.865, 260.217, 260.567, 260.914, 261.259, 261.602 }; #endregion #region CIE Illuminant D65 Spectral Distribution 300-830nm in 1nm steps public static readonly double[] CieIlluminantD65_300_830_1nm = { 0.0341, 0.36014, 0.68618, 1.01222, 1.33826, 1.6643, 1.99034, 2.31638, 2.64242, 2.96846, 3.2945, 4.98865, 6.6828, 8.37695, 10.0711, 11.7652, 13.4594, 15.1535, 16.8477, 18.5418, 20.236, 21.9177, 23.5995, 25.2812, 26.963, 28.6447, 30.3265, 32.0082, 33.69, 35.3717, 37.0535, 37.343, 37.6326, 37.9221, 38.2116, 38.5011, 38.7907, 39.0802, 39.3697, 39.6593, 39.9488, 40.4451, 40.9414, 41.4377, 41.934, 42.4302, 42.9265, 43.4228, 43.9191, 44.4154, 44.9117, 45.0844, 45.257, 45.4297, 45.6023, 45.775, 45.9477, 46.1203, 46.293, 46.4656, 46.6383, 47.1834, 47.7285, 48.2735, 48.8186, 49.3637, 49.9088, 50.4539, 50.9989, 51.544, 52.0891, 51.8777, 51.6664, 51.455, 51.2437, 51.0323, 50.8209, 50.6096, 50.3982, 50.1869, 49.9755, 50.4428, 50.91, 51.3773, 51.8446, 52.3118, 52.7791, 53.2464, 53.7137, 54.1809, 54.6482, 57.4589, 60.2695, 63.0802, 65.8909, 68.7015, 71.5122, 74.3229, 77.1336, 79.9442, 82.7549, 83.628, 84.5011, 85.3742, 86.2473, 87.1204, 87.9936, 88.8667, 89.7398, 90.6129, 91.486, 91.6806, 91.8752, 92.0697, 92.2643, 92.4589, 92.6535, 92.8481, 93.0426, 93.2372, 93.4318, 92.7568, 92.0819, 91.4069, 90.732, 90.057, 89.3821, 88.7071, 88.0322, 87.3572, 86.6823, 88.5006, 90.3188, 92.1371, 93.9554, 95.7736, 97.5919, 99.4102, 101.228, 103.047, 104.865, 106.079, 107.294, 108.508, 109.722, 110.936, 112.151, 113.365, 114.579, 115.794, 117.008, 117.088, 117.169, 117.249, 117.33, 117.41, 117.49, 117.571, 117.651, 117.732, 117.812, 117.517, 117.222, 116.927, 116.632, 116.336, 116.041, 115.746, 115.451, 115.156, 114.861, 114.967, 115.073, 115.18, 115.286, 115.392, 115.498, 115.604, 115.711, 115.817, 115.923, 115.212, 114.501, 113.789, 113.078, 112.367, 111.656, 110.945, 110.233, 109.522, 108.811, 108.865, 108.92, 108.974, 109.028, 109.082, 109.137, 109.191, 109.245, 109.3, 109.354, 109.199, 109.044, 108.888, 108.733, 108.578, 108.423, 108.268, 108.112, 107.957, 107.802, 107.501, 107.2, 106.898, 106.597, 106.296, 105.995, 105.694, 105.392, 105.091, 104.79, 105.08, 105.37, 105.66, 105.95, 106.239, 106.529, 106.819, 107.109, 107.399, 107.689, 107.361, 107.032, 106.704, 106.375, 106.047, 105.719, 105.39, 105.062, 104.733, 104.405, 104.369, 104.333, 104.297, 104.261, 104.225, 104.19, 104.154, 104.118, 104.082, 104.046, 103.641, 103.237, 102.832, 102.428, 102.023, 101.618, 101.214, 100.809, 100.405, 100, 99.6334, 99.2668, 98.9003, 98.5337, 98.1671, 97.8005, 97.4339, 97.0674, 96.7008, 96.3342, 96.2796, 96.225, 96.1703, 96.1157, 96.0611, 96.0065, 95.9519, 95.8972, 95.8426, 95.788, 95.0778, 94.3675, 93.6573, 92.947, 92.2368, 91.5266, 90.8163, 90.1061, 89.3958, 88.6856, 88.8177, 88.9497, 89.0818, 89.2138, 89.3459, 89.478, 89.61, 89.7421, 89.8741, 90.0062, 89.9655, 89.9248, 89.8841, 89.8434, 89.8026, 89.7619, 89.7212, 89.6805, 89.6398, 89.5991, 89.4091, 89.219, 89.029, 88.8389, 88.6489, 88.4589, 88.2688, 88.0788, 87.8887, 87.6987, 87.2577, 86.8167, 86.3757, 85.9347, 85.4936, 85.0526, 84.6116, 84.1706, 83.7296, 83.2886, 83.3297, 83.3707, 83.4118, 83.4528, 83.4939, 83.535, 83.576, 83.6171, 83.6581, 83.6992, 83.332, 82.9647, 82.5975, 82.2302, 81.863, 81.4958, 81.1285, 80.7613, 80.394, 80.0268, 80.0456, 80.0644, 80.0831, 80.1019, 80.1207, 80.1395, 80.1583, 80.177, 80.1958, 80.2146, 80.4209, 80.6272, 80.8336, 81.0399, 81.2462, 81.4525, 81.6588, 81.8652, 82.0715, 82.2778, 81.8784, 81.4791, 81.0797, 80.6804, 80.281, 79.8816, 79.4823, 79.0829, 78.6836, 78.2842, 77.4279, 76.5716, 75.7153, 74.859, 74.0027, 73.1465, 72.2902, 71.4339, 70.5776, 69.7213, 69.9101, 70.0989, 70.2876, 70.4764, 70.6652, 70.854, 71.0428, 71.2315, 71.4203, 71.6091, 71.8831, 72.1571, 72.4311, 72.7051, 72.979, 73.253, 73.527, 73.801, 74.075, 74.349, 73.0745, 71.8, 70.5255, 69.251, 67.9765, 66.702, 65.4275, 64.153, 62.8785, 61.604, 62.4322, 63.2603, 64.0885, 64.9166, 65.7448, 66.573, 67.4011, 68.2293, 69.0574, 69.8856, 70.4057, 70.9259, 71.446, 71.9662, 72.4863, 73.0064, 73.5266, 74.0467, 74.5669, 75.087, 73.9376, 72.7881, 71.6387, 70.4893, 69.3398, 68.1904, 67.041, 65.8916, 64.7421, 63.5927, 61.8752, 60.1578, 58.4403, 56.7229, 55.0054, 53.288, 51.5705, 49.8531, 48.1356, 46.4182, 48.4569, 50.4956, 52.5344, 54.5731, 56.6118, 58.6505, 60.6892, 62.728, 64.7667, 66.8054, 66.4631, 66.1209, 65.7786, 65.4364, 65.0941, 64.7518, 64.4096, 64.0673, 63.7251, 63.3828, 63.4749, 63.567, 63.6592, 63.7513, 63.8434, 63.9355, 64.0276, 64.1198, 64.2119, 64.304, 63.8188, 63.3336, 62.8484, 62.3632, 61.8779, 61.3927, 60.9075, 60.4223, 59.9371, 59.4519, 58.7026, 57.9533, 57.204, 56.4547, 55.7054, 54.9562, 54.2069, 53.4576, 52.7083, 51.959, 52.5072, 53.0553, 53.6035, 54.1516, 54.6998, 55.248, 55.7961, 56.3443, 56.8924, 57.4406, 57.7278, 58.015, 58.3022, 58.5894, 58.8765, 59.1637, 59.4509, 59.7381, 60.0253, 60.3125 }; #endregion #region Preetham Sky Spectrum to XYZ Conversion /// <summary> /// sun color spectrum S0 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS0_380_780_10nm = { 63.4, 65.8, 94.8, 104.8, 105.9, 96.8, 113.9, 125.6, 125.5, 121.3, 121.3, 113.5, 113.1, 110.8, 106.5, 108.8, 105.3, 104.4, 100.0, 96.0, 95.1, 89.1, 90.5, 90.3, 88.4, 84.0, 85.1, 81.9, 82.6, 84.9, 81.3, 71.9, 74.3, 76.4, 63.3, 71.7, 77.0, 65.2, 47.7, 68.6, 65.0 }; /// <summary> /// sun color spectrum S1 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS1_380_780_10nm = { 38.5, 35.0, 43.4, 46.3, 43.9, 37.1, 36.7, 35.9, 32.6, 27.9, 24.3, 20.1, 16.2, 13.2, 8.6, 6.1, 4.2, 1.9, 0.0, -1.6, -3.5, -3.5, -5.8, -7.2, -8.6, -9.5, -10.9, -10.7, -12.0, -14.0, -13.6, -12.0, -13.3, -12.9, -10.6, -11.6, -12.2, -10.2, -7.8, -11.2, -10.4 }; /// <summary> /// sun color spectrum S2 from 380 - 780nm in 10nm steps (taken from preetham Table 2) /// </summary> public static readonly double[] SpecS2_380_780_10nm = { 3.0, 1.2, -1.1, -0.5, -0.7, -1.2, -2.6, -2.9, -2.8, -2.6, -2.6, -1.8, -1.5, -1.3, -1.2, -1.0, -0.5, -0.3, 0.0, 0.2, 0.5, 2.1, 3.2, 4.1, 4.7, 5.1, 6.7, 7.3, 8.6, 9.8, 10.2, 8.3, 9.6, 8.5, 7.0, 7.6, 8.0, 6.7, 5.2, 7.4, 6.8 }; /// <summary> /// CIE XYZ standard observer sensitivity function X in 10mn steps. /// </summary> public static readonly double[] Ciexyz31X_380_780_10nm = { 0.001368000000, 0.004243000000, 0.014310000000, 0.043510000000, 0.134380000000, 0.283900000000, 0.348280000000, 0.336200000000, 0.290800000000, 0.195360000000, 0.095640000000, 0.032010000000, 0.004900000000, 0.009300000000, 0.063270000000, 0.165500000000, 0.290400000000, 0.433449900000, 0.594500000000, 0.762100000000, 0.916300000000, 1.026300000000, 1.062200000000, 1.002600000000, 0.854449900000, 0.642400000000, 0.447900000000, 0.283500000000, 0.164900000000, 0.087400000000, 0.046770000000, 0.022700000000, 0.011359160000, 0.005790346000, 0.002899327000, 0.001439971000, 0.000690078600, 0.000332301100, 0.000166150500, 0.000083075270, 0.000041509940 }; /// <summary> /// CIE XYZ standard observer sensitivity function Y in 10mn steps. /// </summary> public static readonly double[] Ciexyz31Y_380_780_10nm = { 0.000039000000, 0.000120000000, 0.000396000000, 0.001210000000, 0.004000000000, 0.011600000000, 0.023000000000, 0.038000000000, 0.060000000000, 0.090980000000, 0.139020000000, 0.208020000000, 0.323000000000, 0.503000000000, 0.710000000000, 0.862000000000, 0.954000000000, 0.994950100000, 0.995000000000, 0.952000000000, 0.870000000000, 0.757000000000, 0.631000000000, 0.503000000000, 0.381000000000, 0.265000000000, 0.175000000000, 0.107000000000, 0.061000000000, 0.032000000000, 0.017000000000, 0.008210000000, 0.004102000000, 0.002091000000, 0.001047000000, 0.000520000000, 0.000249200000, 0.000120000000, 0.000060000000, 0.000030000000, 0.000014990000 }; /// <summary> /// CIE XYZ standard observer sensitivity function Z in 10mn steps. /// </summary> public static readonly double[] Ciexyz31Z_380_780_10nm = { 0.006450001000, 0.020050010000, 0.067850010000, 0.207400000000, 0.645600000000, 1.385600000000, 1.747060000000, 1.772110000000, 1.669200000000, 1.287640000000, 0.812950100000, 0.465180000000, 0.272000000000, 0.158200000000, 0.078249990000, 0.042160000000, 0.020300000000, 0.008749999000, 0.003900000000, 0.002100000000, 0.001650001000, 0.001100000000, 0.000800000000, 0.000340000000, 0.000190000000, 0.000049999990, 0.000020000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000, 0.000000000000 }; #endregion } }
/* * This is a part of the BugTrap package. * Copyright (c) 2005-2009 IntelleSoft. * All rights reserved. * * Description: Service installer. * Author: Maksim Pyatkovskiy. * * This source code is only intended as a supplement to the * BugTrap package reference and related electronic documentation * provided with the product. See these sources for detailed * information regarding the BugTrap package. */ using System; using System.IO; using System.Runtime.InteropServices; using System.ComponentModel; using System.ServiceProcess; using System.Reflection; using System.Security.Permissions; namespace IntelleSoft.Services { public class ServiceInstaller { #region Constants Declarations private const uint STANDARD_RIGHTS_REQUIRED = 0xF0000; private const uint SC_MANAGER_CONNECT = 0x00001; private const uint SC_MANAGER_CREATE_SERVICE = 0x00002; private const uint SC_MANAGER_ENUMERATE_SERVICE = 0x00004; private const uint SC_MANAGER_LOCK = 0x00008; private const uint SC_MANAGER_QUERY_LOCK_STATUS = 0x00010; private const uint SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00020; private const uint SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG); private const uint SERVICE_WIN32_OWN_PROCESS = 0x00000010; private const uint SERVICE_WIN32_SHARE_PROCESS = 0x00000020; private const uint SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS); private const uint SERVICE_INTERACTIVE_PROCESS = 0x00000100; private const uint SERVICE_ERROR_IGNORE = 0x00000000; private const uint SERVICE_ERROR_NORMAL = 0x00000001; private const uint SERVICE_ERROR_SEVERE = 0x00000002; private const uint SERVICE_ERROR_CRITICAL = 0x00000003; private const uint SERVICE_AUTO_START = 0x00000002; private const uint SERVICE_DEMAND_START = 0x00000003; private const uint SERVICE_DISABLED = 0x00000004; private const uint SERVICE_QUERY_CONFIG = 0x0001; private const uint SERVICE_CHANGE_CONFIG = 0x0002; private const uint SERVICE_QUERY_STATUS = 0x0004; private const uint SERVICE_ENUMERATE_DEPENDENTS = 0x0008; private const uint SERVICE_START = 0x0010; private const uint SERVICE_STOP = 0x0020; private const uint SERVICE_PAUSE_CONTINUE = 0x0040; private const uint SERVICE_INTERROGATE = 0x0080; private const uint SERVICE_USER_DEFINED_CONTROL = 0x0100; private const uint SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL); #endregion #region DLL Imports [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr OpenSCManager([In] string lpMachineName, [In] string lpDatabaseName, [In] uint dwDesiredAccess); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr CreateService([In] IntPtr hSCManager, [In] string lpServiceName, [In] string lpDisplayName, [In] uint dwDesiredAccess, [In] uint dwServiceType, [In] uint dwStartType, [In] uint dwErrorControl, [In] string lpBinaryPathName, [In] string lpLoadOrderGroup, [In] UIntPtr lpdwTagId, [In] string lpDependencies, [In] string lpServiceStartName, [In] string lpPassword); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern void CloseServiceHandle(IntPtr hSCObject); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int StartService([In] IntPtr hService, [In] uint dwNumServiceArgs, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] lpServiceArgVectors); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr OpenService([In] IntPtr hSCManager, [In] string lpServiceName, [In] uint dwDesiredAccess); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DeleteService([In] IntPtr hService); #endregion public class ServiceAccountDescriptor { public ServiceAccountDescriptor() { this.AccountType = ServiceAccount.LocalSystem; } public ServiceAccountDescriptor(ServiceAccount accountType) { this.AccountType = accountType; } public ServiceAccountDescriptor(string accountName, string password) { this.AccountType = ServiceAccount.User; this.AccountName = accountName; this.Password = password; } public ServiceAccountDescriptor(System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller) { this.AccountType = serviceProcessInstaller.Account; this.AccountName = serviceProcessInstaller.Username; this.Password = serviceProcessInstaller.Password; } public ServiceAccount AccountType; public string AccountName; public string Password; }; private static uint GetSratModeFlag(ServiceStartMode startMode) { switch (startMode) { case ServiceStartMode.Automatic: return SERVICE_AUTO_START; case ServiceStartMode.Manual: return SERVICE_DEMAND_START; case ServiceStartMode.Disabled: return SERVICE_DISABLED; default: throw new InvalidEnumArgumentException(); } } private static void GetAccountFields(ServiceAccountDescriptor accountDescriptor, out string accountName, out string password) { switch (accountDescriptor.AccountType) { case ServiceAccount.LocalSystem: accountName = null; password = null; break; case ServiceAccount.LocalService: accountName = @"NT AUTHORITY\LocalService"; password = string.Empty; break; case ServiceAccount.NetworkService: accountName = @"NT AUTHORITY\NetworkService"; password = string.Empty; break; case ServiceAccount.User: accountName = accountDescriptor.AccountName.IndexOf('\\') >= 0 ? accountDescriptor.AccountName : ".\\" + accountDescriptor.AccountName; password = accountDescriptor.Password; break; default: throw new InvalidEnumArgumentException(); } } [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void InstallService(string serviceName, string displayName, string servicePath, ServiceStartMode startMode, ServiceAccountDescriptor accountDescriptor) { uint startModeFlag = GetSratModeFlag(startMode); string accountName, password; GetAccountFields(accountDescriptor, out accountName, out password); if (accountDescriptor.AccountType == ServiceAccount.User) AccountRights.SetRights(accountDescriptor.AccountName, "SeServiceLogonRight", true); IntPtr hSCMHandle = IntPtr.Zero, hServHandle = IntPtr.Zero; try { hSCMHandle = OpenSCManager(null, null, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if (hSCMHandle == IntPtr.Zero) throw new Win32Exception(); hServHandle = CreateService(hSCMHandle, serviceName, displayName, SC_MANAGER_CREATE_SERVICE, SERVICE_WIN32_OWN_PROCESS, startModeFlag, SERVICE_ERROR_NORMAL, servicePath, null, UIntPtr.Zero, null, accountName, password); if (hServHandle == IntPtr.Zero) throw new Win32Exception(); } finally { if (hServHandle != IntPtr.Zero) CloseServiceHandle(hServHandle); if (hSCMHandle != IntPtr.Zero) CloseServiceHandle(hSCMHandle); } } [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void UninstallService(string serviceName) { IntPtr hSCMHandle = IntPtr.Zero, hServHandle = IntPtr.Zero; try { hSCMHandle = OpenSCManager(null, null, SC_MANAGER_CONNECT); if (hSCMHandle == IntPtr.Zero) throw new Win32Exception(); hServHandle = OpenService(hSCMHandle, serviceName, STANDARD_RIGHTS_REQUIRED); if (hServHandle == IntPtr.Zero) throw new Win32Exception(); if (DeleteService(hServHandle) == 0) throw new Win32Exception(); } finally { if (hServHandle != IntPtr.Zero) CloseServiceHandle(hServHandle); if (hSCMHandle != IntPtr.Zero) CloseServiceHandle(hSCMHandle); } } public static void InstallService(string serviceName, string displayName, ServiceStartMode startMode, ServiceAccountDescriptor accountDescriptor) { string servicePath = Assembly.GetExecutingAssembly().Location; InstallService(serviceName, displayName, servicePath, startMode, accountDescriptor); } private static void FindInstallers(System.Configuration.Install.Installer installer, out System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller, out System.ServiceProcess.ServiceInstaller serviceInstaller) { serviceProcessInstaller = null; serviceInstaller = null; foreach (System.Configuration.Install.Installer nestedInstaller in installer.Installers) { if (nestedInstaller is System.ServiceProcess.ServiceProcessInstaller) serviceProcessInstaller = (System.ServiceProcess.ServiceProcessInstaller)nestedInstaller; else if (nestedInstaller is System.ServiceProcess.ServiceInstaller) serviceInstaller = (System.ServiceProcess.ServiceInstaller)nestedInstaller; if (serviceProcessInstaller != null && serviceInstaller != null) break; } if (serviceProcessInstaller == null || serviceInstaller == null) throw new ArgumentException(); } public static void InstallService(System.Configuration.Install.Installer installer) { System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller; System.ServiceProcess.ServiceInstaller serviceInstaller; FindInstallers(installer, out serviceProcessInstaller, out serviceInstaller); ServiceAccountDescriptor accountDescriptor = new ServiceAccountDescriptor(serviceProcessInstaller); InstallService(serviceInstaller.ServiceName, serviceInstaller.DisplayName, serviceInstaller.StartType, accountDescriptor); } public static void UninstallService(System.Configuration.Install.Installer installer) { System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller; System.ServiceProcess.ServiceInstaller serviceInstaller; FindInstallers(installer, out serviceProcessInstaller, out serviceInstaller); UninstallService(serviceInstaller.ServiceName); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using System.Text; using Encog.App.Generate.Program; using Encog.ML; using Encog.ML.Data; using Encog.Persist; using Encog.Util.CSV; using Encog.Util.Simple; namespace Encog.App.Generate.Generators.Java { /// <summary> /// Generate Java. /// </summary> public class GenerateEncogJava : AbstractGenerator { private bool embed; private void EmbedNetwork(EncogProgramNode node) { AddBreak(); var methodFile = (FileInfo) node.Args[0].Value; var method = (IMLMethod) EncogDirectoryPersistence .LoadObject(methodFile); if (!(method is IMLFactory)) { throw new EncogError("Code generation not yet supported for: " + method.GetType().Name); } var factoryMethod = (IMLFactory) method; String methodName = factoryMethod.FactoryType; String methodArchitecture = factoryMethod.FactoryArchitecture; // header AddInclude("org.encog.ml.MLMethod"); AddInclude("org.encog.persist.EncogDirectoryPersistence"); var line = new StringBuilder(); line.Append("public static MLMethod "); line.Append(node.Name); line.Append("() {"); IndentLine(line.ToString()); // create factory line.Length = 0; AddInclude("org.encog.ml.factory.MLMethodFactory"); line.Append("MLMethodFactory methodFactory = new MLMethodFactory();"); AddLine(line.ToString()); // factory create line.Length = 0; line.Append("MLMethod result = "); line.Append("methodFactory.create("); line.Append("\""); line.Append(methodName); line.Append("\""); line.Append(","); line.Append("\""); line.Append(methodArchitecture); line.Append("\""); line.Append(", 0, 0);"); AddLine(line.ToString()); line.Length = 0; AddInclude("org.encog.ml.MLEncodable"); line.Append("((MLEncodable)result).decodeFromArray(WEIGHTS);"); AddLine(line.ToString()); // return AddLine("return result;"); UnIndentLine("}"); } private void EmbedTraining(EncogProgramNode node) { var dataFile = (FileInfo) node.Args[0].Value; IMLDataSet data = EncogUtility.LoadEGB2Memory(dataFile); // generate the input data IndentLine("public static final double[][] INPUT_DATA = {"); foreach (IMLDataPair pair in data) { IMLData item = pair.Input; var line = new StringBuilder(); NumberList.ToList(CSVFormat.EgFormat, line, item); line.Insert(0, "{ "); line.Append(" },"); AddLine(line.ToString()); } UnIndentLine("};"); AddBreak(); // generate the ideal data IndentLine("public static final double[][] IDEAL_DATA = {"); foreach (IMLDataPair pair in data) { IMLData item = pair.Ideal; var line = new StringBuilder(); NumberList.ToList(CSVFormat.EgFormat, line, item); line.Insert(0, "{ "); line.Append(" },"); AddLine(line.ToString()); } UnIndentLine("};"); } public override void Generate(EncogGenProgram program, bool shouldEmbed) { embed = shouldEmbed; GenerateForChildren(program); GenerateImports(program); } private void GenerateArrayInit(EncogProgramNode node) { var line = new StringBuilder(); line.Append("public static final double[] "); line.Append(node.Name); line.Append(" = {"); IndentLine(line.ToString()); var a = (double[]) node.Args[0].Value; line.Length = 0; int lineCount = 0; for (int i = 0; i < a.Length; i++) { line.Append(CSVFormat.EgFormat.Format(a[i], EncogFramework.DefaultPrecision)); if (i < (a.Length - 1)) { line.Append(","); } lineCount++; if (lineCount >= 10) { AddLine(line.ToString()); line.Length = 0; lineCount = 0; } } if (line.Length > 0) { AddLine(line.ToString()); line.Length = 0; } UnIndentLine("};"); } private void GenerateClass(EncogProgramNode node) { AddBreak(); IndentLine("public class " + node.Name + " {"); GenerateForChildren(node); UnIndentLine("}"); } private void GenerateComment(EncogProgramNode commentNode) { AddLine("// " + commentNode.Name); } private void GenerateConst(EncogProgramNode node) { var line = new StringBuilder(); line.Append("public static final "); line.Append(node.Args[1].Value); line.Append(" "); line.Append(node.Name); line.Append(" = \""); line.Append(node.Args[0].Value); line.Append("\";"); AddLine(line.ToString()); } private void GenerateCreateNetwork(EncogProgramNode node) { if (embed) { EmbedNetwork(node); } else { LinkNetwork(node); } } private void GenerateEmbedTraining(EncogProgramNode node) { if (embed) { EmbedTraining(node); } } private void GenerateForChildren(EncogTreeNode parent) { foreach (EncogProgramNode node in parent.Children) { GenerateNode(node); } } private void GenerateFunction(EncogProgramNode node) { AddBreak(); var line = new StringBuilder(); line.Append("public static void "); line.Append(node.Name); line.Append("() {"); IndentLine(line.ToString()); GenerateForChildren(node); UnIndentLine("}"); } private void GenerateFunctionCall(EncogProgramNode node) { AddBreak(); var line = new StringBuilder(); if (node.Args[0].Value.ToString().Length > 0) { line.Append(node.Args[0].Value); line.Append(" "); line.Append(node.Args[1].Value); line.Append(" = "); } line.Append(node.Name); line.Append("();"); AddLine(line.ToString()); } private void GenerateImports(EncogGenProgram program) { var imports = new StringBuilder(); foreach (String str in Includes) { imports.Append("import "); imports.Append(str); imports.Append(";\n"); } imports.Append("\n"); AddToBeginning(imports.ToString()); } private void GenerateLoadTraining(EncogProgramNode node) { AddBreak(); var methodFile = (FileInfo) node.Args[0].Value; AddInclude("org.encog.ml.data.MLDataSet"); var line = new StringBuilder(); line.Append("public static MLDataSet createTraining() {"); IndentLine(line.ToString()); line.Length = 0; if (embed) { AddInclude("org.encog.ml.data.basic.BasicMLDataSet"); line.Append("MLDataSet result = new BasicMLDataSet(INPUT_DATA,IDEAL_DATA);"); } else { AddInclude("org.encog.util.simple.EncogUtility"); line.Append("MLDataSet result = EncogUtility.loadEGB2Memory(new File(\""); line.Append(methodFile); line.Append("\"));"); } AddLine(line.ToString()); // return AddLine("return result;"); UnIndentLine("}"); } private void GenerateMainFunction(EncogProgramNode node) { AddBreak(); IndentLine("public static void main(String[] args) {"); GenerateForChildren(node); UnIndentLine("}"); } private void GenerateNode(EncogProgramNode node) { switch (node.Type) { case NodeType.Comment: GenerateComment(node); break; case NodeType.Class: GenerateClass(node); break; case NodeType.MainFunction: GenerateMainFunction(node); break; case NodeType.Const: GenerateConst(node); break; case NodeType.StaticFunction: GenerateFunction(node); break; case NodeType.FunctionCall: GenerateFunctionCall(node); break; case NodeType.CreateNetwork: GenerateCreateNetwork(node); break; case NodeType.InitArray: GenerateArrayInit(node); break; case NodeType.EmbedTraining: GenerateEmbedTraining(node); break; case NodeType.LoadTraining: GenerateLoadTraining(node); break; } } private void LinkNetwork(EncogProgramNode node) { AddBreak(); var methodFile = (FileInfo) node.Args[0].Value; AddInclude("org.encog.ml.MLMethod"); var line = new StringBuilder(); line.Append("public static MLMethod "); line.Append(node.Name); line.Append("() {"); IndentLine(line.ToString()); line.Length = 0; line.Append("MLMethod result = (MLMethod)EncogDirectoryPersistence.loadObject(new File(\""); line.Append(methodFile); line.Append("\"));"); AddLine(line.ToString()); // return AddLine("return result;"); UnIndentLine("}"); } } }
using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { using System.Collections; internal class XLRows : XLStylizedBase, IXLRows, IXLStylized { private readonly List<XLRow> _rowsCollection = new List<XLRow>(); private readonly XLWorksheet _worksheet; private bool IsMaterialized => _lazyEnumerable == null; private IEnumerable<XLRow> _lazyEnumerable; private IEnumerable<XLRow> Rows => _lazyEnumerable ?? _rowsCollection.AsEnumerable(); /// <summary> /// Create a new instance of <see cref="XLRows"/>. /// </summary> /// <param name="worksheet">If worksheet is specified it means that the created instance represents /// all rows on a worksheet so changing its height will affect all rows.</param> /// <param name="defaultStyle">Default style to use when initializing child entries.</param> /// <param name="lazyEnumerable">A predefined enumerator of <see cref="XLRow"/> to support lazy initialization.</param> public XLRows(XLWorksheet worksheet, XLStyleValue defaultStyle = null, IEnumerable<XLRow> lazyEnumerable = null) : base(defaultStyle) { _worksheet = worksheet; _lazyEnumerable = lazyEnumerable; } #region IXLRows Members public IEnumerator<IXLRow> GetEnumerator() { return Rows.Cast<IXLRow>().OrderBy(r => r.RowNumber()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public double Height { set { Rows.ForEach(c => c.Height = value); if (_worksheet == null) return; _worksheet.RowHeight = value; _worksheet.Internals.RowsCollection.ForEach(r => r.Value.Height = value); } } public void Delete() { if (_worksheet != null) { _worksheet.Internals.RowsCollection.Clear(); _worksheet.Internals.CellsCollection.Clear(); } else { var toDelete = new Dictionary<IXLWorksheet, List<Int32>>(); foreach (XLRow r in Rows) { if (!toDelete.TryGetValue(r.Worksheet, out List<Int32> list)) { list = new List<Int32>(); toDelete.Add(r.Worksheet, list); } list.Add(r.RowNumber()); } foreach (KeyValuePair<IXLWorksheet, List<int>> kp in toDelete) { foreach (int r in kp.Value.OrderByDescending(r => r)) kp.Key.Row(r).Delete(); } } } public IXLRows AdjustToContents() { Rows.ForEach(r => r.AdjustToContents()); return this; } public IXLRows AdjustToContents(Int32 startColumn) { Rows.ForEach(r => r.AdjustToContents(startColumn)); return this; } public IXLRows AdjustToContents(Int32 startColumn, Int32 endColumn) { Rows.ForEach(r => r.AdjustToContents(startColumn, endColumn)); return this; } public IXLRows AdjustToContents(Double minHeight, Double maxHeight) { Rows.ForEach(r => r.AdjustToContents(minHeight, maxHeight)); return this; } public IXLRows AdjustToContents(Int32 startColumn, Double minHeight, Double maxHeight) { Rows.ForEach(r => r.AdjustToContents(startColumn, minHeight, maxHeight)); return this; } public IXLRows AdjustToContents(Int32 startColumn, Int32 endColumn, Double minHeight, Double maxHeight) { Rows.ForEach(r => r.AdjustToContents(startColumn, endColumn, minHeight, maxHeight)); return this; } public void Hide() { Rows.ForEach(r => r.Hide()); } public void Unhide() { Rows.ForEach(r => r.Unhide()); } public void Group() { Group(false); } public void Group(Int32 outlineLevel) { Group(outlineLevel, false); } public void Ungroup() { Ungroup(false); } public void Group(Boolean collapse) { Rows.ForEach(r => r.Group(collapse)); } public void Group(Int32 outlineLevel, Boolean collapse) { Rows.ForEach(r => r.Group(outlineLevel, collapse)); } public void Ungroup(Boolean ungroupFromAll) { Rows.ForEach(r => r.Ungroup(ungroupFromAll)); } public void Collapse() { Rows.ForEach(r => r.Collapse()); } public void Expand() { Rows.ForEach(r => r.Expand()); } public IXLCells Cells() { var cells = new XLCells(false, XLCellsUsedOptions.AllContents); foreach (XLRow container in Rows) cells.Add(container.RangeAddress); return cells; } public IXLCells CellsUsed() { var cells = new XLCells(true, XLCellsUsedOptions.AllContents); foreach (XLRow container in Rows) cells.Add(container.RangeAddress); return cells; } [Obsolete("Use the overload with XLCellsUsedOptions")] public IXLCells CellsUsed(Boolean includeFormats) { return CellsUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents); } public IXLCells CellsUsed(XLCellsUsedOptions options) { var cells = new XLCells(true, options); foreach (XLRow container in Rows) cells.Add(container.RangeAddress); return cells; } public IXLRows AddHorizontalPageBreaks() { foreach (XLRow row in Rows) row.Worksheet.PageSetup.AddHorizontalPageBreak(row.RowNumber()); return this; } public IXLRows SetDataType(XLDataType dataType) { Rows.ForEach(c => c.DataType = dataType); return this; } #endregion IXLRows Members #region IXLStylized Members protected override IEnumerable<XLStylizedBase> Children { get { if (_worksheet != null) yield return _worksheet; else { foreach (XLRow row in Rows) yield return row; } } } public override IEnumerable<IXLStyle> Styles { get { yield return Style; if (_worksheet != null) yield return _worksheet.Style; else { foreach (IXLStyle s in Rows.SelectMany(row => row.Styles)) { yield return s; } } } } public override IXLRanges RangesUsed { get { var retVal = new XLRanges(); this.ForEach(c => retVal.Add(c.AsRange())); return retVal; } } #endregion IXLStylized Members public void Add(XLRow row) { Materialize(); _rowsCollection.Add(row); } public IXLRows Clear(XLClearOptions clearOptions = XLClearOptions.All) { Rows.ForEach(c => c.Clear(clearOptions)); return this; } public void Select() { foreach (var range in this) range.Select(); } private void Materialize() { if (IsMaterialized) return; _rowsCollection.AddRange(Rows); _lazyEnumerable = null; } } }
// // 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.Collections.Generic; namespace Encog.App.Finance.Indicators { /// <summary> /// A set of financial / technical indicators. /// </summary> public class TechnicalIndicators { /// <summary> /// Our predicted closing values which will be used by the network to predict the forward indicator. /// </summary> internal double[] _closes; private double _fitNess = 0; private double _forwardOscillator; internal List<double> _movingAverageSeries; /// <summary> /// Gets or sets the fitness score. /// </summary> /// <value> /// The fitness score (netprofit / drawdown) * winning percentage.. /// </value> internal double FitNessScore { get { return _fitNess; } } public double NetProfit { get; set; } private double Drawdown { get; set; } private double WinningPercentage { get; set; } /// <summary> /// Gets or sets the moving average length /// </summary> /// <value> /// The moving average length. /// </value> private int MovingAverageLenght { get; set; } /// <summary> /// Gets or sets the forward lookup value. /// This is the number of bars (or closes) we are looking into the future. /// </summary> /// <value> /// The forward lookup value. /// </value> private int ForwardLookupValue { get; set; } /// <value>the beginningIndex to set</value> public int BeginningIndex { get; set; } /// <value>the endingIndex to set.</value> public int EndingIndex { get; set; } /// <summary> /// returns the current fitness score. /// </summary> /// <returns></returns> public static double GetFitNess(int numberofWins, int NumbeofLosses, double netprofit, double drawdown) { return (netprofit/drawdown)*CalculateWinningPercentage(numberofWins, NumbeofLosses); } /// <summary> /// Calculates the winning percentage. /// </summary> /// <param name="numberofWins">The number of wins.</param> /// <param name="numberofLosses">The numberof losses.</param> /// <returns></returns> public static double CalculateWinningPercentage(double numberofWins, double numberofLosses) { double add = numberofWins + numberofLosses; return (numberofWins/add); } /// <summary> /// Calculates the drawdown. /// Need to enter Min equity value, max equity value and the equity series. /// </summary> /// <param name="equity">The equity</param> /// <param name="minValue">The min value.</param> /// <param name="maxValue">The max value.</param> /// <returns></returns> public static double DrawDown(double[] equity, out double minValue, out double maxValue) { maxValue = double.MinValue; minValue = double.MaxValue; foreach (double t in equity) { if (t > maxValue) maxValue = t; if (t < minValue) minValue = t; } return maxValue - minValue; } /// <summary> /// Sets the moving average lenght. /// </summary> /// <param name="Lenght">The lenght.</param> public void SetMovingAverageLenght(int Lenght) { MovingAverageLenght = Lenght; } /// Sets the number of look forward values. /// </summary> /// <param name="valuesToLookForwardInto">The values to look forward into.</param> public void SetNumberOfLookForwardValues(int valuesToLookForwardInto) { ForwardLookupValue = valuesToLookForwardInto; } /// <summary> /// Calculates the forward oscillator. /// Which is :Close N - Average(Close , X); /// Where N is number of bars into the future and X is the length of our moving average. /// if this indicator is positive , then we are in bullish mode else we are in bearish mode. /// See Neural networks in the capital markets by John paul. /// </summary> /// <returns>double</returns> public static double SimpleForwardOscillator(double predictedClose, int length, double currentClose) { double result = predictedClose - Avg(currentClose, length); return result; } /// <summary> /// Frequencies the specified lenght. /// THe frequency used to calculate Phase indicators. /// E.G one day is 1. /// but 10 day Frequency is 1/10 = 0.10. /// </summary> /// <param name="lenght">The lenght.</param> /// <returns></returns> public static double Frequency(int lenght) { return 1/lenght; } /// <summary> /// Calculates the forward oscillator. /// Which is :Close N - Average(Close , X); /// Where N is number of bars into the future and X is the length of our moving average. /// if this indicator is positive , then we are in bullish mode else we are in bearish mode. /// See Neural networks in the capital markets by John paul. /// </summary> /// <returns>double</returns> public static double PhaseOscillator(double predictedClose, int length, double currentClose) { double result = predictedClose - Avg(currentClose, length); return result; } private static double Avg(double a, double b) { return (a + b)/2; } /// <summary> /// Gets the moving average serie. /// </summary> /// <returns></returns> public double[] GetMovingAverageSerie() { if (_movingAverageSeries != null) { return _movingAverageSeries.ToArray(); } return null; } /// <summary> /// Adds a double to the moving average series. /// </summary> /// <param name="close"></param> public void AddCloseToMovingAverage(double close) { _movingAverageSeries.Add(close); } /// <summary> /// Calculate this indicator. /// </summary> /// <param name="data">The data to use.</param> /// <param name="length">The length to calculate over.</param> public void CalculateMovingAverageOfDoubleSerie(double[] data, int length) { if (data != null) { SetMovingAverageLenght(length); double[] close = data; if (_movingAverageSeries == null) _movingAverageSeries = new List<double>(); int lookbackTotal = (MovingAverageLenght - 1); int start = lookbackTotal; if (start > (MovingAverageLenght - 1)) { return; } double periodTotal = 0; int trailingIdx = start - lookbackTotal; int i = trailingIdx; if (MovingAverageLenght > 1) { while (i < start) { periodTotal += close[i++]; } } int outIdx = MovingAverageLenght - 1; do { periodTotal += close[i++]; double t = periodTotal; periodTotal -= close[trailingIdx++]; _movingAverageSeries[outIdx++] = t/MovingAverageLenght; } while (i < close.Length); BeginningIndex = MovingAverageLenght - 1; EndingIndex = _movingAverageSeries.Count - 1; for (i = 0; i < MovingAverageLenght - 1; i++) { _movingAverageSeries[i] = 0; } return; } return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class GroupJoinTests : EnumerableTests { public struct CustomerRec { public string name; public int? custID; } public struct OrderRec { public int? orderID; public int? custID; public int? total; } public struct AnagramRec { public string name; public int? orderID; public int? total; } public struct JoinRec : IEquatable<JoinRec> { public string name; public int?[] orderID; public int?[] total; public override int GetHashCode() { // Not great, but it'll serve. return name.GetHashCode() ^ orderID.Length ^ (total.Length * 31); } public bool Equals(JoinRec other) { if (!string.Equals(name, other.name)) return false; if (orderID == null) { if (other.orderID != null) return false; } else { if (other.orderID == null) return false; if (orderID.Length != other.orderID.Length) return false; for (int i = 0; i != other.orderID.Length; ++i) if (orderID[i] != other.orderID[i]) return false; } if (total == null) { if (other.total != null) return false; } else { if (other.total == null) return false; if (total.Length != other.total.Length) return false; for (int i = 0; i != other.total.Length; ++i) if (total[i] != other.total[i]) return false; } return true; } public override bool Equals(object obj) { return obj is JoinRec && Equals((JoinRec)obj); } } public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<OrderRec> orIE) { return new JoinRec { name = cr.name, orderID = orIE.Select(o => o.orderID).ToArray(), total = orIE.Select(o => o.total).ToArray(), }; } public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<AnagramRec> arIE) { return new JoinRec { name = cr.name, orderID = arIE.Select(o => o.orderID).ToArray(), total = arIE.Select(o => o.total).ToArray(), }; } [Fact] public void OuterEmptyInnerNonEmpty() { CustomerRec[] outer = { }; OrderRec[] inner = new [] { new OrderRec{ orderID = 45321, custID = 98022, total = 50 }, new OrderRec{ orderID = 97865, custID = 32103, total = 25 } }; Assert.Empty(outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void CustomComparer() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new [] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 93489 }, total = new int?[]{ 45 } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterNull() { CustomerRec[] outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = null; AssertExtensions.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void OuterKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void InnerKeySelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null, new AnagramEqualityComparer())); } [Fact] public void OuterNullNoComparer() { CustomerRec[] outer = null; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec)); } [Fact] public void InnerNullNoComparer() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = null; AssertExtensions.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec)); } [Fact] public void OuterKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec)); } [Fact] public void InnerKeySelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec)); } [Fact] public void ResultSelectorNullNoComparer() { CustomerRec[] outer = new CustomerRec[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new AnagramRec[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null)); } [Fact] public void OuterInnerBothSingleNullElement() { string[] outer = new string[] { null }; string[] inner = new string[] { null }; string[] expected = new string[] { null }; Assert.Equal(expected, outer.GroupJoin(inner, e => e, e => e, (x, y) => x, EqualityComparer<string>.Default)); } [Fact] public void OuterNonEmptyInnerEmpty() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 }, new CustomerRec{ name = "Bob", custID = 34093 } }; OrderRec[] inner = { }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 43434, total = 25 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SingleElementEachAndDoesntMatch() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 49434, total = 25 } }; JoinRec[] expected = new JoinRec[] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void SelectorsReturnNull() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = null }, new CustomerRec{ name = "Bob", custID = null } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = null, total = 25 }, new OrderRec{ orderID = 34390, custID = null, total = 19 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void InnerSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 } }; OrderRec[] inner = new[] { new OrderRec{ orderID = 97865, custID = 1234, total = 25 }, new OrderRec{ orderID = 34390, custID = 1234, total = 19 }, new OrderRec{ orderID = 34390, custID = 9865, total = 19 } }; JoinRec[] expected = new[] { new JoinRec { name = "Tim", orderID = new int?[]{ 97865, 34390 }, total = new int?[] { 25, 19 } }, new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void InnerSameKeyMoreThanOneElementAndMatchesRunOnce() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 } }; OrderRec[] inner = new[] { new OrderRec{ orderID = 97865, custID = 1234, total = 25 }, new OrderRec{ orderID = 34390, custID = 1234, total = 19 }, new OrderRec{ orderID = 34390, custID = 9865, total = 19 } }; JoinRec[] expected = new[] { new JoinRec { name = "Tim", orderID = new int?[]{ 97865, 34390 }, total = new int?[] { 25, 19 } }, new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.RunOnce().GroupJoin(inner.RunOnce(), e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void OuterSameKeyMoreThanOneElementAndMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9865 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 1234, total = 25 }, new OrderRec{ orderID = 34390, custID = 9865, total = 19 } }; JoinRec[] expected = new [] { new JoinRec { name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } }, new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } }, new JoinRec { name = "Robert", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NoMatches() { CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 2334, total = 25 }, new OrderRec{ orderID = 34390, custID = 9065, total = 19 } }; JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ }, total = new int?[]{ } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec)); } [Fact] public void NullComparer() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new[] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, null)); } [Fact] public void NullComparerRunOnce() { CustomerRec[] outer = new[] { new CustomerRec{ name = "Tim", custID = 1234 }, new CustomerRec{ name = "Bob", custID = 9865 }, new CustomerRec{ name = "Robert", custID = 9895 } }; AnagramRec[] inner = new[] { new AnagramRec{ name = "Robert", orderID = 93483, total = 19 }, new AnagramRec{ name = "miT", orderID = 93489, total = 45 } }; JoinRec[] expected = new[] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }, new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } } }; Assert.Equal(expected, outer.RunOnce().GroupJoin(inner.RunOnce(), e => e.name, e => e.name, createJoinRec, null)); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).GroupJoin(Enumerable.Empty<int>(), i => i, i => i, (o, i) => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<IEnumerable<int>>; Assert.False(en != null && en.MoveNext()); } } }
/* * IndentedTextWriter.cs - Implementation of the * System.CodeDom.Compiler.IndentedTextWriter class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.CodeDom.Compiler { #if CONFIG_CODEDOM using System.IO; using System.Text; public class IndentedTextWriter : TextWriter { // Internal state. private TextWriter writer; private String tabString; private int indent; private bool atLineStart; // The default string to use for tabbing. public const String DefaultTabString = " "; // Constructors. public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) { // Nothing to do here. } public IndentedTextWriter(TextWriter writer, String tabString) { this.writer = writer; this.tabString = tabString; this.indent = 0; this.atLineStart = true; } // Get the encoding in use by the underlying text writer. public override Encoding Encoding { get { return writer.Encoding; } } // Get or set the current indent level. public int Indent { get { return indent; } set { if(value >= 0) { indent = value; } else { indent = 0; } } } // Get the writer underlying this object. public TextWriter InnerWriter { get { return writer; } } // Get or set the newline string. public override String NewLine { get { return writer.NewLine; } set { writer.NewLine = value; } } // Close this writer. public override void Close() { writer.Close(); } // Flush this writer. public override void Flush() { writer.Flush(); } // Output tabs at the start of a line if necessary. protected virtual void OutputTabs() { if(atLineStart) { int level = indent; while(level > 0) { writer.Write(tabString); --level; } atLineStart = false; } } // Write values of various types. public override void Write(bool value) { OutputTabs(); writer.Write(value); } public override void Write(char value) { OutputTabs(); writer.Write(value); } public override void Write(char[] value) { OutputTabs(); writer.Write(value); } public override void Write(double value) { OutputTabs(); writer.Write(value); } public override void Write(int value) { OutputTabs(); writer.Write(value); } public override void Write(long value) { OutputTabs(); writer.Write(value); } public override void Write(Object value) { OutputTabs(); writer.Write(value); } public override void Write(float value) { OutputTabs(); writer.Write(value); } public override void Write(String value) { OutputTabs(); writer.Write(value); } public override void Write(String value, Object arg0) { OutputTabs(); writer.Write(value, arg0); } public override void Write(String value, Object arg0, Object arg1) { OutputTabs(); writer.Write(value, arg0, arg1); } public override void Write(String value, params Object[] args) { OutputTabs(); writer.Write(value, args); } public override void Write(char[] value, int index, int count) { OutputTabs(); writer.Write(value, index, count); } // Write values of various types followed by a newline. public override void WriteLine() { OutputTabs(); writer.WriteLine(); atLineStart = true; } public override void WriteLine(bool value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(char value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(char[] value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(double value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(int value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(long value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(Object value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(float value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(String value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } public override void WriteLine(String value, Object arg0) { OutputTabs(); writer.WriteLine(value, arg0); atLineStart = true; } public override void WriteLine(String value, Object arg0, Object arg1) { OutputTabs(); writer.WriteLine(value, arg0, arg1); atLineStart = true; } public override void WriteLine(String value, params Object[] args) { OutputTabs(); writer.WriteLine(value, args); atLineStart = true; } public override void WriteLine(char[] value, int index, int count) { OutputTabs(); writer.WriteLine(value, index, count); atLineStart = true; } [CLSCompliant(false)] public override void WriteLine(uint value) { OutputTabs(); writer.WriteLine(value); atLineStart = true; } // Write a string with no tab processing. public void WriteLineNoTabs(String s) { writer.WriteLine(s); } }; // class IndentedTextWriter #endif // CONFIG_CODEDOM }; // namespace System.CodeDom.Compiler