context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // System.Xml.XmlTextWriterTests // // Author: Kral Ferch <[email protected]> // Author: Martin Willemoes Hansen <[email protected]> // // (C) 2002 Kral Ferch // (C) 2003 Martin Willemoes Hansen // using System; using System.Xml; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XmlCharacterDataTests : Assertion { XmlDocument document; XmlComment comment; bool changed; bool changing; [SetUp] public void GetReady () { document = new XmlDocument (); document.NodeChanged += new XmlNodeChangedEventHandler (this.EventNodeChanged); document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChanging); comment = document.CreateComment ("foo"); } private void EventNodeChanged(Object sender, XmlNodeChangedEventArgs e) { changed = true; } private void EventNodeChanging (Object sender, XmlNodeChangedEventArgs e) { changing = true; } [Test] public void AppendData () { changed = false; changing = false; comment.AppendData ("bar"); Assert (changed); Assert (changing); AssertEquals ("foobar", comment.Data); comment.Value = "foo"; comment.AppendData (null); AssertEquals ("foo", comment.Data); } [Test] public void DeleteData () { comment.Value = "bar"; changed = false; changing = false; comment.DeleteData (1, 1); Assert (changed); Assert (changing); AssertEquals ("br", comment.Data); try { comment.Value = "foo"; comment.DeleteData(-1, 1); Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (ArgumentOutOfRangeException) {} comment.Value = "foo"; comment.DeleteData(1, 5); AssertEquals("f", comment.Data); comment.Value = "foo"; comment.DeleteData(3, 10); AssertEquals("foo", comment.Data); } [Test] public void InsertData () { comment.Value = "foobaz"; changed = false; changing = false; comment.InsertData (3, "bar"); Assert (changed); Assert (changing); AssertEquals ("foobarbaz", comment.Data); try { comment.Value = "foo"; comment.InsertData (-1, "bar"); Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (ArgumentOutOfRangeException) {} comment.Value = "foo"; comment.InsertData (3, "bar"); AssertEquals ("foobar", comment.Data); try { comment.Value = "foo"; comment.InsertData (4, "bar"); Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (ArgumentOutOfRangeException) {} try { comment.Value = "foo"; comment.InsertData (1, null); Fail ("Expected an ArgumentNullException to be thrown."); } catch (ArgumentNullException) {} } [Test] public void ReplaceData () { changed = false; changing = false; comment.ReplaceData (0, 3, "bar"); Assert (changed); Assert (changing); AssertEquals ("bar", comment.Data); comment.Value = "foo"; comment.ReplaceData (2, 3, "bar"); AssertEquals ("fobar", comment.Data); comment.Value = "foo"; comment.ReplaceData (3, 3, "bar"); AssertEquals ("foobar", comment.Data); try { comment.Value = "foo"; comment.ReplaceData (4, 3, "bar"); Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (ArgumentOutOfRangeException) {} try { comment.Value = "foo"; comment.ReplaceData (-1, 3, "bar"); Fail ("Expected an ArgumentOutOfRangeException to be thrown."); } catch (ArgumentOutOfRangeException) {} comment.Value = "foo"; comment.ReplaceData (0, 2, "bar"); AssertEquals ("baro", comment.Data); comment.Value = "foo"; comment.ReplaceData (0, 5, "bar"); AssertEquals ("bar", comment.Data); try { comment.Value = "foo"; comment.ReplaceData (1, 1, null); Fail ("Expected an ArgumentNullException to be thrown."); } catch (ArgumentNullException) {} } [Test] public void Substring () { comment.Value = "test string"; AssertEquals ("test string", comment.Substring (0, 50)); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void SubstringStartOutOfRange () { comment.Value = "test string"; comment.Substring (-5, 10); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void SubstringCountOutOfRange () { comment.Value = "test string"; comment.Substring (10, -5); } } }
// 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; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Security; using System.Runtime.CompilerServices; using System.Threading; using Internal.Runtime.Augments; namespace System.Runtime.InteropServices.WindowsRuntime { #if ENABLE_WINRT // Helper functions to manually marshal data between .NET and WinRT public static class WindowsRuntimeMarshal { // Add an event handler to a Windows Runtime style event, such that it can be removed via a delegate // lookup at a later time. This method adds the handler to the add method using the supplied // delegate. It then stores the corresponding token in a dictionary for easy access by RemoveEventHandler // later. Note that the dictionary is indexed by the remove method that will be used for RemoveEventHandler // so the removeMethod given here must match the remove method supplied there exactly. public static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) { if (addMethod == null) throw new ArgumentNullException(nameof(addMethod)); if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); // Managed code allows adding a null event handler, the effect is a no-op. To match this behavior // for WinRT events, we simply ignore attempts to add null. if (handler == null) { return; } // Delegate to managed event registration implementation or native event registration implementation // They have completely different implementation because native side has its own unique problem to solve - // Managed events are implemented using ConditionalWeakTable which is based on the weak reference of the event itself. // Since the managed event will be alive till the event is used. This is OK. // On the other hand native and static events can't follow the same model as managed object. Since the native event might be alive but the managed __ComObject might // die, a different __ComObject instance might reference the same native event. Or same __ComObject instance might mean a different native event. // and hence they both have different implementations. #if !RHTESTCL object target = removeMethod.Target; if (target == null || target is __ComObject) NativeOrStaticEventRegistrationImpl.AddEventHandler<T>(addMethod, removeMethod, handler); else #endif ManagedEventRegistrationImpl.AddEventHandler<T>(addMethod, removeMethod, handler); } // Remove the delegate handler from the Windows Runtime style event registration by looking for // its token, previously stored via AddEventHandler<T> public static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); // Managed code allows removing a null event handler, the effect is a no-op. To match this behavior // for WinRT events, we simply ignore attempts to remove null. if (handler == null) { return; } // Delegate to managed event registration implementation or native event registration implementation // They have completely different implementation because native side has its own unique problem to solve - // there could be more than one RCW for the same COM object // it would be more confusing and less-performant if we were to merge them together #if !RHTESTCL object target = removeMethod.Target; if (target == null || target is __ComObject) NativeOrStaticEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); else #endif ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); } public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); // Delegate to managed event registration implementation or native event registration implementation // They have completely different implementation because native side has its own unique problem to solve - // there could be more than one RCW for the same COM object // it would be more confusing and less-performant if we were to merge them together #if !RHTESTCL object target = removeMethod.Target; if (target == null || target is __ComObject) NativeOrStaticEventRegistrationImpl.RemoveAllEventHandlers(removeMethod); else #endif ManagedEventRegistrationImpl.RemoveAllEventHandlers(removeMethod); } #if !RHTESTCL // Returns the total cache size // Used by test only to verify we don't leak event cache internal static int GetRegistrationTokenCacheSize() { int count = 0; if (ManagedEventRegistrationImpl.s_eventRegistrations != null) { try { ManagedEventRegistrationImpl.s_eventRegistrationsLock.Acquire(); foreach (var item in ManagedEventRegistrationImpl.s_eventRegistrations) count++; } finally { ManagedEventRegistrationImpl.s_eventRegistrationsLock.Release(); } } if (NativeOrStaticEventRegistrationImpl.s_eventRegistrations != null) { try { NativeOrStaticEventRegistrationImpl.s_eventRegistrationsLock.Acquire(); count += NativeOrStaticEventRegistrationImpl.s_eventRegistrations.Count; } finally { NativeOrStaticEventRegistrationImpl.s_eventRegistrationsLock.Release(); } } return count; } #endif // // Optimized version of List of EventRegistrationToken // It is made a struct to reduce overhead // internal struct EventRegistrationTokenList { private EventRegistrationToken firstToken; // Optimization for common case where there is only one token private System.Collections.Generic.Internal.List<EventRegistrationToken> restTokens; // Rest of the tokens internal EventRegistrationTokenList(EventRegistrationToken token) { firstToken = token; restTokens = null; } internal EventRegistrationTokenList(EventRegistrationTokenList list) { firstToken = list.firstToken; restTokens = list.restTokens; } // Push a new token into this list // Returns true if you need to copy back this list into the dictionary (so that you // don't lose change outside the dictionary). false otherwise. public bool Push(EventRegistrationToken token) { bool needCopy = false; if (restTokens == null) { restTokens = new System.Collections.Generic.Internal.List<EventRegistrationToken>(); needCopy = true; } restTokens.Add(token); return needCopy; } // Pops the last token // Returns false if no more tokens left, true otherwise public bool Pop(out EventRegistrationToken token) { // Only 1 token in this list and we just removed the last token if (restTokens == null || restTokens.Count == 0) { token = firstToken; return false; } int last = restTokens.Count - 1; token = restTokens[last]; restTokens.RemoveAt(last); return true; } public void CopyTo(System.Collections.Generic.Internal.List<EventRegistrationToken> tokens) { tokens.Add(firstToken); if (restTokens != null) { for (int i = 0; i < restTokens.Count; i++) { tokens.Add(restTokens[i]); } } } } // // Event registration support for managed objects events & static events // internal static class ManagedEventRegistrationImpl { // Mappings of delegates registered for events -> their registration tokens. // These mappings are stored indexed by the remove method which can be used to undo the registrations. // // The full structure of this table is: // object the event is being registered on -> // Table [RemoveMethod] -> // Table [Handler] -> Token // // Note: There are a couple of optimizations I didn't do here because they don't make sense for managed events: // 1. Flatten the event cache (see EventCacheKey in native WinRT event implementation below) // // This is because managed events use ConditionalWeakTable to hold Objects->(Event->(Handler->Tokens)), // and when object goes away everything else will be nicely cleaned up. If I flatten it like native WinRT events, // I'll have to use Dictionary (as ConditionalWeakTable won't work - nobody will hold the new key alive anymore) // instead, and that means I'll have to add more code from native WinRT events into managed WinRT event to support // self-cleanup in the finalization, as well as reader/writer lock to protect against races in the finalization, // which adds a lot more complexity and doesn't really worth it. // // 2. Use conditionalWeakTable to hold Handler->Tokens. // // The reason is very simple - managed object use dictionary (see EventRegistrationTokenTable) to hold delegates alive. // If the delegates aren't alive, it means either they have been unsubscribed, or the object itself is gone, // and in either case, they've been already taken care of. // internal static ConditionalWeakTable<object, System.Collections.Generic.Internal.Dictionary<IntPtr, System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations = new ConditionalWeakTable<object, System.Collections.Generic.Internal.Dictionary<IntPtr, System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList>>>(); internal static Lock s_eventRegistrationsLock = new Lock(); internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) { Debug.Assert(addMethod != null); Debug.Assert(removeMethod != null); // Add the method, and make a note of the token -> delegate mapping. object instance = removeMethod.Target; #if !RHTESTCL Debug.Assert(instance != null && !(instance is __ComObject)); #endif System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); EventRegistrationToken token = addMethod(handler); try { registrationTokens.LockAcquire(); EventRegistrationTokenList tokens; if (!registrationTokens.TryGetValue(handler, out tokens)) { tokens = new EventRegistrationTokenList(token); registrationTokens[handler] = tokens; } else { bool needCopy = tokens.Push(token); // You need to copy back this list into the dictionary (so that you don't lose change outside dictionary) if (needCopy) registrationTokens[handler] = tokens; } #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for managed instance = " + instance + ", handler = " + handler + "\n"); #endif } finally { registrationTokens.LockRelease(); } } // Get the event registration token table for an event. These are indexed by the remove method of the event. private static System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList> GetEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> removeMethod) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); Debug.Assert(s_eventRegistrations != null); try { s_eventRegistrationsLock.Acquire(); System.Collections.Generic.Internal.Dictionary<IntPtr, System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList>> instanceMap = null; if (!s_eventRegistrations.TryGetValue(instance, out instanceMap)) { instanceMap = new System.Collections.Generic.Internal.Dictionary<IntPtr, System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList>>(); s_eventRegistrations.Add(instance, instanceMap); } System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList> tokens = null; // Because this code already is tied to a specific instance, the type handle associated with the // delegate is not needed. RuntimeTypeHandle thDummy; if (!instanceMap.TryGetValue(removeMethod.GetFunctionPointer(out thDummy), out tokens)) { tokens = new System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList>(true); instanceMap.Add(removeMethod.GetFunctionPointer(out thDummy), tokens); } return tokens; } finally { s_eventRegistrationsLock.Release(); } } internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { Debug.Assert(removeMethod != null); object instance = removeMethod.Target; // // Temporary static event support - this is bad for a couple of reasons: // 1. This will leak the event delegates. Our real implementation fixes that // 2. We need the type itself, but we don't have delegate.Method.DeclaringType ( // but I don't know what is the best replacement). Perhaps this isn't too bad // 3. Unsubscription doesn't work due to ConditionalWeakTable work on reference equality. // I can fix this but I figured it is easier to keep this broken so that we know we'll fix // this (rather than using the slower value equality version which we might forget to fix // later // @TODO - Remove this and replace with real static support (that was #ifdef-ed out) // if (instance == null) { // Because this code only operates for delegates to static methods, the output typehandle of GetFunctionPointer is not used RuntimeTypeHandle thDummy; instance = removeMethod.GetFunctionPointer(out thDummy); } System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); EventRegistrationToken token; try { registrationTokens.LockAcquire(); EventRegistrationTokenList tokens; // Failure to find a registration for a token is not an error - it's simply a no-op. if (!registrationTokens.TryGetValue(handler, out tokens)) { #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n"); #endif return; } // Select a registration token to unregister // We don't care which one but I'm returning the last registered token to be consistent // with native event registration implementation bool moreItems = tokens.Pop(out token); if (!moreItems) { // Remove it from cache if this list become empty // This must be done because EventRegistrationTokenList now becomes invalid // (mostly because there is no safe default value for EventRegistrationToken to express 'no token') // NOTE: We should try to remove registrationTokens itself from cache if it is empty, otherwise // we could run into a race condition where one thread removes it from cache and another thread adds // into the empty registrationToken table registrationTokens.Remove(handler); } } finally { registrationTokens.LockRelease(); } removeMethod(token); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n"); #endif } internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { Debug.Assert(removeMethod != null); object instance = removeMethod.Target; System.Collections.Generic.Internal.Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); System.Collections.Generic.Internal.List<EventRegistrationToken> tokensToRemove = new System.Collections.Generic.Internal.List<EventRegistrationToken>(); try { registrationTokens.LockAcquire(); // Copy all tokens to tokensToRemove array which later we'll call removeMethod on // outside this lock foreach (EventRegistrationTokenList tokens in registrationTokens.Values) { tokens.CopyTo(tokensToRemove); } // Clear the dictionary - at this point all event handlers are no longer in the cache // but they are not removed yet registrationTokens.Clear(); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instance + "\n"); #endif } finally { registrationTokens.LockRelease(); } // // Remove all handlers outside the lock // #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instance + "\n"); #endif CallRemoveMethods(removeMethod, tokensToRemove); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n"); #endif } } #if !RHTESTCL // // WinRT event registration implementation code // internal static class NativeOrStaticEventRegistrationImpl { // // Key = (target object, event) // We use a key of object+event to save an extra dictionary // internal struct EventCacheKey { internal object target; internal object method; public override string ToString() { return "(" + target + ", " + method + ")"; } } internal class EventCacheKeyEqualityComparer : IEqualityComparer<EventCacheKey> { public bool Equals(EventCacheKey lhs, EventCacheKey rhs) { return (Object.Equals(lhs.target, rhs.target) && Object.Equals(lhs.method, rhs.method)); } public int GetHashCode(EventCacheKey key) { return key.target.GetHashCode() ^ key.method.GetHashCode(); } } // // EventRegistrationTokenListWithCount // // A list of EventRegistrationTokens that maintains a count // // The reason this needs to be a separate class is that we need a finalizer for this class // If the delegate is collected, it will take this list away with it (due to dependent handles), // and we need to remove the PerInstancEntry from cache // See ~EventRegistrationTokenListWithCount for more details // internal class EventRegistrationTokenListWithCount { private TokenListCount _tokenListCount; EventRegistrationTokenList _tokenList; internal EventRegistrationTokenListWithCount(TokenListCount tokenListCount, EventRegistrationToken token) { _tokenListCount = tokenListCount; _tokenListCount.Inc(); _tokenList = new EventRegistrationTokenList(token); } ~EventRegistrationTokenListWithCount() { // Decrement token list count // This is need to correctly keep trace of number of tokens for EventCacheKey // and remove it from cache when the token count drop to 0 // we don't need to take locks for decrement the count - we only need to take a global // lock when we decide to destroy cache for the IUnknown */type instance #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n"); #endif _tokenListCount.Dec(); } public void Push(EventRegistrationToken token) { // Since EventRegistrationTokenListWithCount is a reference type, there is no need // to copy back. Ignore the return value _tokenList.Push(token); } public bool Pop(out EventRegistrationToken token) { return _tokenList.Pop(out token); } public void CopyTo(System.Collections.Generic.Internal.List<EventRegistrationToken> tokens) { _tokenList.CopyTo(tokens); } } // // Maintains the number of tokens for a particular EventCacheKey // TokenListCount is a class for two reasons: // 1. Efficient update in the Dictionary to avoid lookup twice to update the value // 2. Update token count without taking a global lock. Only takes a global lock when drop to 0 // internal class TokenListCount { private int _count; private EventCacheKey _key; internal TokenListCount(EventCacheKey key) { _key = key; } internal EventCacheKey Key { get { return _key; } } internal void Inc() { int newCount = Interlocked.Increment(ref _count); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); #endif } internal void Dec() { // Avoid racing with Add/Remove event entries into the cache // You don't want this removing the key in the middle of a Add/Remove s_eventCacheRWLock.EnterWriteLock(); try { int newCount = Interlocked.Decrement(ref _count); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); #endif if (newCount == 0) CleanupCache(); } finally { s_eventCacheRWLock.ExitWriteLock(); } } private void CleanupCache() { // Time to destroy cache for this IUnknown */type instance // because the total token list count has dropped to 0 and we don't have any events subscribed Debug.Assert(s_eventRegistrations != null); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n"); #endif s_eventRegistrations.Remove(_key); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] s_eventRegistrations size = " + s_eventRegistrations.Count + "\n"); #endif } } internal class EventCacheEntry { // [Handler] -> Token internal ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTable; // Maintains current total count for the EventRegistrationTokenListWithCount for this event cache key internal TokenListCount tokenListCount; // Lock for registrationTable + tokenListCount, much faster than locking ConditionalWeakTable itself internal Lock _lock; internal void LockAcquire() { _lock.Acquire(); } internal void LockRelease() { _lock.Release(); } } // Mappings of delegates registered for events -> their registration tokens. // These mappings are stored indexed by the remove method which can be used to undo the registrations. // // The full structure of this table is: // EventCacheKey (instanceKey, eventMethod) -> EventCacheEntry (Handler->tokens) // // A InstanceKey is the IUnknown * or static type instance // // Couple of things to note: // 1. We need to use IUnknown* because we want to be able to unscribe to the event for another RCW // based on the same COM object. For example: // m_canvas.GetAt(0).Event += Func; // m_canvas.GetAt(0).Event -= Func; // GetAt(0) might create a new RCW // // 2. Handler->Token is a ConditionalWeakTable because we don't want to keep the delegate alive // and we want EventRegistrationTokenListWithCount to be finalized after the delegate is no longer alive // 3. It is possible another COM object is created at the same address // before the entry in cache is destroyed. More specifically, // a. The same delegate is being unsubscribed. In this case we'll give them a // stale token - unlikely to be a problem // b. The same delegate is subscribed then unsubscribed. We need to make sure give // them the latest token in this case. This is guaranteed by always giving the last token and always use equality to // add/remove event handlers internal static System.Collections.Generic.Internal.Dictionary<EventCacheKey, EventCacheEntry> s_eventRegistrations = new System.Collections.Generic.Internal.Dictionary<EventCacheKey, EventCacheEntry>(new EventCacheKeyEqualityComparer()); internal static Lock s_eventRegistrationsLock = new Lock(); // Prevent add/remove handler code to run at the same with with cache cleanup code private static ReaderWriterLockSlim s_eventCacheRWLock = new ReaderWriterLockSlim(); private static Object s_dummyStaticEventKey = new Object(); // Get InstanceKey to use in the cache private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod) { object target = removeMethod.Target; Debug.Assert(target == null || target is __ComObject, "Must be an RCW"); if (target == null) { // In .NET Native there is no good way to go from the static event to the declaring type, the instanceKey used for // static events in desktop. Since the declaring type is only a way to organize the list of static events, we have // chosen to use the dummyObject instead here.It flattens the hierarchy of static events but does not impact the functionality. return s_dummyStaticEventKey; } // Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context __ComObject comObject = target as __ComObject; return (object)comObject.BaseIUnknown_UnsafeNoAddRef; } private static object FindEquivalentKeyUnsafe(ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTable, object handler, out EventRegistrationTokenListWithCount tokens) { foreach (KeyValuePair<object, EventRegistrationTokenListWithCount> item in registrationTable) { if (Object.Equals(item.Key, handler)) { tokens = item.Value; return item.Key; } } tokens = null; return null; } internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod, Action<EventRegistrationToken> removeMethod, T handler) { // The instanceKey will be IUnknown * of the target object object instanceKey = GetInstanceKey(removeMethod); // Call addMethod outside of RW lock // At this point we don't need to worry about race conditions and we can avoid deadlocks // if addMethod waits on finalizer thread // If we later throw we need to remove the method EventRegistrationToken token = addMethod(handler); bool tokenAdded = false; try { EventRegistrationTokenListWithCount tokens; // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time // s_eventCacheRWLock.EnterReadLock(); try { // Add the method, and make a note of the delegate -> token mapping. EventCacheEntry registrationTokens = GetOrCreateEventRegistrationTokenTable(instanceKey, removeMethod); try { registrationTokens.LockAcquire(); // // We need to find the key that equals to this handler // Suppose we have 3 handlers A, B, C that are equal (refer to the same object and method), // the first handler (let's say A) will be used as the key and holds all the tokens. // We don't need to hold onto B and C, because the COM object itself will keep them alive, // and they won't die anyway unless the COM object dies or they get unsubscribed. // It may appear that it is fine to hold A, B, C, and add them and their corresponding tokens // into registrationTokens table. However, this is very dangerous, because this COM object // may die, but A, B, C might not get collected yet, and another COM object comes into life // with the same IUnknown address, and we subscribe event B. In this case, the right token // will be added into B's token list, but once we unsubscribe B, we might end up removing // the last token in C, and that may lead to crash. // object key = FindEquivalentKeyUnsafe(registrationTokens.registrationTable, handler, out tokens); if (key == null) { tokens = new EventRegistrationTokenListWithCount(registrationTokens.tokenListCount, token); registrationTokens.registrationTable.Add(handler, tokens); } else { tokens.Push(token); } tokenAdded = true; } finally { registrationTokens.LockRelease(); } } finally { s_eventCacheRWLock.ExitReadLock(); } #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n"); #endif } catch (Exception) { // If we've already added the token and go there, we don't need to "UNDO" anything if (!tokenAdded) { // Otherwise, "Undo" addMethod if any exception occurs // There is no need to cleanup our data structure as we haven't added the token yet removeMethod(token); } throw; } } private static EventCacheEntry GetEventRegistrationTokenTableNoCreate(object instance, Action<EventRegistrationToken> removeMethod) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); return GetEventRegistrationTokenTableInternal(instance, removeMethod, /* createIfNotFound = */ false); } private static EventCacheEntry GetOrCreateEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> removeMethod) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); return GetEventRegistrationTokenTableInternal(instance, removeMethod, /* createIfNotFound = */ true); } // Get the event registration token table for an event. These are indexed by the remove method of the event. private static EventCacheEntry GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> removeMethod, bool createIfNotFound) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); Debug.Assert(s_eventRegistrations != null); EventCacheKey eventCacheKey; eventCacheKey.target = instance; #if false eventCacheKey.method = removeMethod.Method; #endif RuntimeTypeHandle thDummy; eventCacheKey.method = removeMethod.GetFunctionPointer(out thDummy); try { s_eventRegistrationsLock.Acquire(); EventCacheEntry eventCacheEntry; if (!s_eventRegistrations.TryGetValue(eventCacheKey, out eventCacheEntry)) { if (!createIfNotFound) { // No need to create an entry in this case return null; } #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Adding (" + instance + "," + removeMethod.Method + ") into cache" + "\n"); #endif eventCacheEntry = new EventCacheEntry(); eventCacheEntry.registrationTable = new ConditionalWeakTable<object, EventRegistrationTokenListWithCount>(); eventCacheEntry.tokenListCount = new TokenListCount(eventCacheKey); eventCacheEntry._lock = new Lock(); s_eventRegistrations.Add(eventCacheKey, eventCacheEntry); } return eventCacheEntry; } finally { s_eventRegistrationsLock.Release(); } } internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { object instanceKey = GetInstanceKey(removeMethod); EventRegistrationToken token; // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time // s_eventCacheRWLock.EnterReadLock(); try { EventCacheEntry registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod); if (registrationTokens == null) { // We have no information regarding this particular instance (IUnknown*/type) - just return // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n"); #endif return; } try { registrationTokens.LockAcquire(); EventRegistrationTokenListWithCount tokens; // Note: // When unsubscribing events, we allow subscribing the event using a different delegate // (but with the same object/method), so we need to find the first delegate that matches // and unsubscribe it // It actually doesn't matter which delegate - as long as it matches // Note that inside TryGetValueWithValueEquality we assumes that any delegate // with the same value equality would have the same hash code object key = FindEquivalentKeyUnsafe(registrationTokens.registrationTable, handler, out tokens); Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), "key and tokens must be both null or non-null"); if (tokens == null) { // Failure to find a registration for a token is not an error - it's simply a no-op. #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n"); #endif return; } // Select a registration token to unregister // Note that we need to always get the last token just in case another COM object // is created at the same address before the entry for the old one goes away. // See comments above s_eventRegistrations for more details bool moreItems = tokens.Pop(out token); // If the last token is removed from token list, we need to remove it from the cache // otherwise FindEquivalentKeyUnsafe may found this empty token list even though there could be other // equivalent keys in there with non-0 token list if (!moreItems) { // Remove it from (handler)->(tokens) // NOTE: We should not check whether registrationTokens has 0 entries and remove it from the cache // (just like managed event implementation), because this might race with the finalizer of // EventRegistrationTokenList registrationTokens.registrationTable.Remove(key); } #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.m_value + "\n"); #endif } finally { registrationTokens.LockRelease(); } } finally { s_eventCacheRWLock.ExitReadLock(); } // Call removeMethod outside of RW lock // At this point we don't need to worry about race conditions and we can avoid deadlocks // if removeMethod waits on finalizer thread removeMethod(token); } internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { object instanceKey = GetInstanceKey(removeMethod); System.Collections.Generic.Internal.List<EventRegistrationToken> tokensToRemove = new System.Collections.Generic.Internal.List<EventRegistrationToken>(); // // The whole add/remove code has to be protected by a reader/writer lock // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time // s_eventCacheRWLock.EnterReadLock(); try { EventCacheEntry registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod); if (registrationTokens == null) { // We have no information regarding this particular instance (IUnknown*/type) - just return // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance return; } try { registrationTokens.LockAcquire(); // Copy all tokens to tokensToRemove array which later we'll call removeMethod on // outside this lock foreach (KeyValuePair<object, EventRegistrationTokenListWithCount> item in registrationTokens.registrationTable) { item.Value.CopyTo(tokensToRemove); } // Clear the table - at this point all event handlers are no longer in the cache // but they are not removed yet registrationTokens.registrationTable.Clear(); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n"); #endif } finally { registrationTokens.LockRelease(); } } finally { s_eventCacheRWLock.ExitReadLock(); } // // Remove all handlers outside the lock // #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n"); #endif CallRemoveMethods(removeMethod, tokensToRemove); #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n"); #endif } } #endif // // Call removeMethod on each token and aggregate all exceptions thrown from removeMethod into one in case of failure // internal static void CallRemoveMethods(Action<EventRegistrationToken> removeMethod, System.Collections.Generic.Internal.List<EventRegistrationToken> tokensToRemove) { System.Collections.Generic.Internal.List<Exception> exceptions = new System.Collections.Generic.Internal.List<Exception>(); for (int i = 0; i < tokensToRemove.Count; i++) { try { removeMethod(tokensToRemove[i]); } catch (Exception ex) { exceptions.Add(ex); } #if false BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for token = " + token.m_value + "\n"); #endif } if (exceptions.Count > 0) #if false throw new AggregateException(exceptions.ToArray()); #else throw exceptions[0]; #endif } public static IntPtr StringToHString(string s) { return McgMarshal.StringToHString(s).handle; } public static void FreeHString(IntPtr ptr) { McgMarshal.FreeHString(ptr); } public static string PtrToStringHString(IntPtr ptr) { return McgMarshal.HStringToString(ptr); } /// <summary> /// Returns the activation factory without using the cache. Avoiding cache behavior is important /// for app that use this API because they need to deal with crashing broker scenarios where cached /// factories would be stale (pointing to a bad proxy) /// </summary> public static IActivationFactory GetActivationFactory(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); __ComObject factory = FactoryCache.Get().GetActivationFactory( type.FullName, InternalTypes.IUnknown, skipCache: true); return (IActivationFactory) factory; } } #endif }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using DiscUtils.Internal; namespace DiscUtils { /// <summary> /// Provides the base class for both <see cref="DiscFileInfo"/> and <see cref="DiscDirectoryInfo"/> objects. /// </summary> public class DiscFileSystemInfo { internal DiscFileSystemInfo(DiscFileSystem fileSystem, string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } FileSystem = fileSystem; Path = path.Trim('\\'); } /// <summary> /// Gets or sets the <see cref="System.IO.FileAttributes"/> of the current <see cref="DiscFileSystemInfo"/> object. /// </summary> public virtual FileAttributes Attributes { get { return FileSystem.GetAttributes(Path); } set { FileSystem.SetAttributes(Path, value); } } /// <summary> /// Gets or sets the creation time (in local time) of the current <see cref="DiscFileSystemInfo"/> object. /// </summary> public virtual DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } set { CreationTimeUtc = value.ToUniversalTime(); } } /// <summary> /// Gets or sets the creation time (in UTC) of the current <see cref="DiscFileSystemInfo"/> object. /// </summary> public virtual DateTime CreationTimeUtc { get { return FileSystem.GetCreationTimeUtc(Path); } set { FileSystem.SetCreationTimeUtc(Path, value); } } /// <summary> /// Gets a value indicating whether the file system object exists. /// </summary> public virtual bool Exists { get { return FileSystem.Exists(Path); } } /// <summary> /// Gets the extension part of the file or directory name. /// </summary> public virtual string Extension { get { string name = Name; int sepIdx = name.LastIndexOf('.'); if (sepIdx >= 0) { return name.Substring(sepIdx + 1); } return string.Empty; } } /// <summary> /// Gets the file system the referenced file or directory exists on. /// </summary> public DiscFileSystem FileSystem { get; } /// <summary> /// Gets the full path of the file or directory. /// </summary> public virtual string FullName { get { return Path; } } /// <summary> /// Gets or sets the last time (in local time) the file or directory was accessed. /// </summary> /// <remarks>Read-only file systems will never update this value, it will remain at a fixed value.</remarks> public virtual DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } set { LastAccessTimeUtc = value.ToUniversalTime(); } } /// <summary> /// Gets or sets the last time (in UTC) the file or directory was accessed. /// </summary> /// <remarks>Read-only file systems will never update this value, it will remain at a fixed value.</remarks> public virtual DateTime LastAccessTimeUtc { get { return FileSystem.GetLastAccessTimeUtc(Path); } set { FileSystem.SetLastAccessTimeUtc(Path, value); } } /// <summary> /// Gets or sets the last time (in local time) the file or directory was written to. /// </summary> public virtual DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } set { LastWriteTimeUtc = value.ToUniversalTime(); } } /// <summary> /// Gets or sets the last time (in UTC) the file or directory was written to. /// </summary> public virtual DateTime LastWriteTimeUtc { get { return FileSystem.GetLastWriteTimeUtc(Path); } set { FileSystem.SetLastWriteTimeUtc(Path, value); } } /// <summary> /// Gets the name of the file or directory. /// </summary> public virtual string Name { get { return Utilities.GetFileFromPath(Path); } } /// <summary> /// Gets the <see cref="DiscDirectoryInfo"/> of the directory containing the current <see cref="DiscFileSystemInfo"/> object. /// </summary> public virtual DiscDirectoryInfo Parent { get { if (string.IsNullOrEmpty(Path)) { return null; } return new DiscDirectoryInfo(FileSystem, Utilities.GetDirectoryFromPath(Path)); } } /// <summary> /// Gets the path to the referenced file. /// </summary> protected string Path { get; } /// <summary> /// Deletes a file or directory. /// </summary> public virtual void Delete() { if ((Attributes & FileAttributes.Directory) != 0) { FileSystem.DeleteDirectory(Path); } else { FileSystem.DeleteFile(Path); } } /// <summary> /// Indicates if <paramref name="obj"/> is equivalent to this object. /// </summary> /// <param name="obj">The object to compare.</param> /// <returns><c>true</c> if <paramref name="obj"/> is equivalent, else <c>false</c>.</returns> public override bool Equals(object obj) { DiscFileSystemInfo asInfo = obj as DiscFileSystemInfo; if (obj == null) { return false; } return string.Compare(Path, asInfo.Path, StringComparison.Ordinal) == 0 && Equals(FileSystem, asInfo.FileSystem); } /// <summary> /// Gets the hash code for this object. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return Path.GetHashCode() ^ FileSystem.GetHashCode(); } } }
// Copyright 2009-2012 Matvei Stefarov <[email protected]> using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using JetBrains.Annotations; using System.IO; using System.Linq; namespace fCraft { /// <summary> Object representing persistent state ("record") of a player, online or offline. /// There is exactly one PlayerInfo object for each known Minecraft account. All data is stored in the PlayerDB. </summary> public sealed partial class PlayerInfo : IClassy { public const int MinFieldCount = 24; ///<summary> Player's amount of bits.</summary> [CanBeNull] public int Money = 0; ///<summary> Support for mojang accounts.</summary> [CanBeNull] public string MojangAccount; /// <summary> Player's Minecraft account name. </summary> [NotNull] public string Name { get; internal set; } /// <summary> If set, replaces Name when printing name in chat. </summary> [CanBeNull] public string DisplayedName; /// <summary> If set, overrides both DisplayedName and Name. Used for temp name changes like gamemodes or /impersonation. </summary> [CanBeNull] public string tempDisplayedName; /// <summary>Player's title.</summary> [CanBeNull] public string TitleName; /// <summary> Player's unique numeric ID. Issued on first join. </summary> public int ID; /// <summary> /// Block currently being held by the player /// </summary> public Block HeldBlock; /// <summary> First time the player ever logged in, UTC. /// May be DateTime.MinValue if player has never been online. </summary> public DateTime FirstLoginDate; /// <summary> Most recent time the player logged in, UTC. /// May be DateTime.MinValue if player has never been online. </summary> public DateTime LastLoginDate; /// <summary> Last time the player has been seen online (last logout), UTC. /// May be DateTime.MinValue if player has never been online. </summary> public DateTime LastSeen; /// <summary> Reason for leaving the server last time. </summary> public LeaveReason LeaveReason; public int PromoCount; //dummy public string LeaveMsg = "left the server"; public string oldDisplayedName = null; //TempRank public bool isTempRanked = false; public TimeSpan tempRankTime = TimeSpan.FromSeconds(0); //For CoolDown Timers public DateTime LastUsedSlap; public DateTime LastUsedKill; public DateTime LastUsedInsult; public DateTime LastUsedHug; public DateTime LastUsedBeatDown; public DateTime LastUsedBarf; public DateTime LastUsedThrow; //bromode public string oldname; public bool changedName = false; public bool HasVoted = false; //TeamDeathMatch public bool isPlayingTD = false; public bool isOnBlueTeam = false; public bool isOnRedTeam = false; public int totalKillsTDM = 0; public int totalDeathsTDM = 0; public int gameKills = 0; public int gameDeaths = 0; //FFA public bool isPlayingFFA = false; public int totalKillsFFA = 0; public int totalDeathsFFA = 0; public int gameKillsFFA = 0; public int gameDeathsFFA = 0; //Infection public bool isPlayingInfection = false; public bool isInfected = false; //Capture The Flag public bool isPlayingCTF = false; public bool hasBlueFlag = false; public bool hasRedFlag = false; public bool CTFRedTeam = false; public bool CTFBlueTeam = false; public short CTFKills = 0; public short CTFCaptures = 0; public bool placingRedFlag = false; public bool placingBlueFlag = false; public bool gunDisarmed = false; public bool stabDisarmed = false; public bool stabAnywhere = false; public bool strengthened = false; public DateTime strengthTime; public bool canDodge = false; public DateTime dodgeTime; //Door public bool isDoorChecking = false; public DateTime doorCheckTime = DateTime.MaxValue; /// <summary> Health var used in several gamemodes </summary> public short Health = 100; #region Rank /// <summary> Player's current rank. </summary> [NotNull] public Rank Rank { get; internal set; } /// <summary> Player's previous rank. /// May be null if player has never been promoted/demoted before. </summary> [CanBeNull] public Rank PreviousRank; /// <summary> Date of the most recent promotion/demotion, UTC. /// May be DateTime.MinValue if player has never been promoted/demoted before. </summary> public DateTime RankChangeDate; /// <summary> Name of the entity that most recently promoted/demoted this player. May be empty. </summary> [CanBeNull] public string RankChangedBy; [NotNull] public string RankChangedByClassy { get { return PlayerDB.FindExactClassyName(RankChangedBy); } } /// <summary> Reason given for the most recent promotion/demotion. May be empty. </summary> [CanBeNull] public string RankChangeReason; /// <summary> Type of the most recent promotion/demotion. </summary> public RankChangeType RankChangeType; #endregion #region Bans /// <summary> Player's current BanStatus: Banned, NotBanned, or Exempt. </summary> public BanStatus BanStatus; /// <summary> Returns whether player is name-banned or not. </summary> public bool IsBanned { get { return BanStatus == BanStatus.Banned; } } /// <summary> Date of most recent ban, UTC. May be DateTime.MinValue if player was never banned. </summary> public DateTime BanDate; /// <summary> Name of the entity responsible for most recent ban. May be empty. </summary> [CanBeNull] public string BannedBy; [NotNull] public string BannedByClassy { get { return PlayerDB.FindExactClassyName(BannedBy); } } public bool IsWarned; public string WarnedBy = ""; public DateTime WarnedOn; public bool IsTempbanned { get { return DateTime.UtcNow < MutedUntil; } } public bool UnWarn() { if (IsWarned) { IsWarned = false; return true; } else { return false; } } public bool Warn(string by) { if (by == null) throw new ArgumentNullException("by"); if (!IsWarned) { IsWarned = true; WarnedOn = DateTime.UtcNow; WarnedBy = by; return true; } else { return false; } } public bool Tempban(string by, TimeSpan timespan) { if (by == null) throw new ArgumentNullException("by"); if (timespan <= TimeSpan.Zero) { throw new ArgumentException("Tempban duration must be longer than 0", "timespan"); } DateTime newBannedUntil = DateTime.UtcNow.Add(timespan); if (newBannedUntil > BannedUntil) { BannedUntil = newBannedUntil; BannedBy = by; LastModified = DateTime.UtcNow; return true; } else { return false; } } /// <summary> Reason given for the most recent ban. May be empty. </summary> [CanBeNull] public string BanReason; /// <summary> Date of most recent unban, UTC. May be DateTime.MinValue if player was never unbanned. </summary> public DateTime UnbanDate; /// <summary> Name of the entity responsible for most recent unban. May be empty. </summary> [CanBeNull] public string UnbannedBy; [NotNull] public string UnbannedByClassy { get { return PlayerDB.FindExactClassyName(UnbannedBy); } } /// <summary> Reason given for the most recent unban. May be empty. </summary> [CanBeNull] public string UnbanReason; /// <summary> Date of most recent failed attempt to log in, UTC. </summary> public DateTime LastFailedLoginDate; /// <summary> IP from which player most recently tried (and failed) to log in, UTC. </summary> [NotNull] public IPAddress LastFailedLoginIP = IPAddress.None; #endregion #region Stats ///<summary>In the state of 'jelly'.</summary> public bool isJelly; ///<summary>In the state of 'MADNESS'.</summary> public bool isMad; /// <summary> Total amount of time the player spent on this server. </summary> public TimeSpan TotalTime; /// <summary> Total number of blocks manually built or painted by the player. </summary> public int BlocksBuilt; /// <summary> Total number of blocks manually deleted by the player. </summary> public int BlocksDeleted; /// <summary> Total number of blocks modified using draw and copy/paste commands. </summary> public long BlocksDrawn; /// <summary> Number of sessions/logins. </summary> public int TimesVisited; /// <summary> Total number of messages written. </summary> public int MessagesWritten; /// <summary> Number of kicks issues by this player. </summary> public int TimesKickedOthers; /// <summary> Number of bans issued by this player. </summary> public int TimesBannedOthers; #endregion #region Kicks /// <summary> Number of times that this player has been manually kicked. </summary> public int TimesKicked; /// <summary> Date of the most recent kick. /// May be DateTime.MinValue if the player has never been kicked. </summary> public DateTime LastKickDate; /// <summary> Name of the entity that most recently kicked this player. May be empty. </summary> [CanBeNull] public string LastKickBy; [NotNull] public string LastKickByClassy { get { return PlayerDB.FindExactClassyName(LastKickBy); } } /// <summary> Reason given for the most recent kick. May be empty. </summary> [CanBeNull] public string LastKickReason; #endregion #region Freeze And Mute /// <summary> Whether this player is currently frozen. </summary> public bool IsFrozen; /// <summary> Date of the most recent freezing. /// May be DateTime.MinValue of the player has never been frozen. </summary> public DateTime FrozenOn; /// <summary> Name of the entity that most recently froze this player. May be empty. </summary> [CanBeNull] public string FrozenBy; [NotNull] public string FrozenByClassy { get { return PlayerDB.FindExactClassyName(FrozenBy); } } /// <summary> Whether this player is currently muted. </summary> public bool IsMuted { get { return DateTime.UtcNow < MutedUntil; } } /// <summary> Date until which the player is muted. If the date is in the past, player is NOT muted. </summary> public DateTime MutedUntil; /// <summary> Name of the entity that most recently muted this player. May be empty. </summary> [CanBeNull] public string MutedBy; [NotNull] public string MutedByClassy { get { return PlayerDB.FindExactClassyName(MutedBy); } } #endregion /// <summary> Whether the player is currently online. /// Another way to check online status is to check if PlayerObject is null. </summary> public bool IsOnline { get; private set; } /// <summary> If player is online, Player object associated with the session. /// If player is offline, null. </summary> [CanBeNull] public Player PlayerObject { get; private set; } /// <summary> Whether the player is currently hidden. /// Use Player.CanSee() method to check visibility to specific observers. </summary> public bool IsHidden; /// <summary> For offline players, last IP used to succesfully log in. /// For online players, current IP. </summary> [NotNull] public IPAddress LastIP; #region Constructors and Serialization internal PlayerInfo(int id) { ID = id; } PlayerInfo() { // reset everything to defaults LastIP = IPAddress.None; RankChangeDate = DateTime.MinValue; BanDate = DateTime.MinValue; UnbanDate = DateTime.MinValue; LastFailedLoginDate = DateTime.MinValue; FirstLoginDate = DateTime.MinValue; LastLoginDate = DateTime.MinValue; TotalTime = TimeSpan.Zero; RankChangeType = RankChangeType.Default; LastKickDate = DateTime.MinValue; LastSeen = DateTime.MinValue; BannedUntil = DateTime.MinValue; FrozenOn = DateTime.MinValue; MutedUntil = DateTime.MinValue; BandwidthUseMode = BandwidthUseMode.Default; LastModified = DateTime.UtcNow; } // fabricate info for an unrecognized player public PlayerInfo([NotNull] string name, [NotNull] Rank rank, bool setLoginDate, RankChangeType rankChangeType) : this() { if (name == null) throw new ArgumentNullException("name"); if (rank == null) throw new ArgumentNullException("rank"); Name = name; Rank = rank; if (setLoginDate) { FirstLoginDate = DateTime.UtcNow; LastLoginDate = FirstLoginDate; LastSeen = FirstLoginDate; TimesVisited = 1; } RankChangeType = rankChangeType; } // generate blank info for a new player public PlayerInfo([NotNull] string name, [NotNull] IPAddress lastIP, [NotNull] Rank startingRank) : this() { if (name == null) throw new ArgumentNullException("name"); if (lastIP == null) throw new ArgumentNullException("lastIP"); if (startingRank == null) throw new ArgumentNullException("startingRank"); FirstLoginDate = DateTime.UtcNow; LastSeen = DateTime.UtcNow; LastLoginDate = DateTime.UtcNow; Rank = startingRank; Name = name; ID = PlayerDB.GetNextID(); LastIP = lastIP; } #endregion #region Loading internal static PlayerInfo LoadFormat2(string[] fields) { PlayerInfo info = new PlayerInfo { Name = fields[0] }; if (fields[1].Length == 0 || !IPAddress.TryParse(fields[1], out info.LastIP)) { info.LastIP = IPAddress.None; } info.Rank = Rank.Parse(fields[2]) ?? RankManager.DefaultRank; fields[3].ToDateTime(ref info.RankChangeDate); if (fields[4].Length > 0) info.RankChangedBy = fields[4]; switch (fields[5]) { case "b": info.BanStatus = BanStatus.Banned; break; case "x": info.BanStatus = BanStatus.IPBanExempt; break; default: info.BanStatus = BanStatus.NotBanned; break; } // ban information if (fields[6].ToDateTime(ref info.BanDate)) { if (fields[7].Length > 0) info.BannedBy = Unescape(fields[7]); if (fields[10].Length > 0) info.BanReason = Unescape(fields[10]); } // unban information if (fields[8].ToDateTime(ref info.UnbanDate)) { if (fields[9].Length > 0) info.UnbannedBy = Unescape(fields[9]); if (fields[11].Length > 0) info.UnbanReason = Unescape(fields[11]); } // failed logins fields[12].ToDateTime(ref info.LastFailedLoginDate); if (fields[13].Length > 1 || !IPAddress.TryParse(fields[13], out info.LastFailedLoginIP)) { // LEGACY info.LastFailedLoginIP = IPAddress.None; } if (fields[14].Length > 0) Int32.TryParse(fields[14], out info.Money); fields[15].ToDateTime(ref info.FirstLoginDate); // login/logout times fields[16].ToDateTime(ref info.LastLoginDate); fields[17].ToTimeSpan(out info.TotalTime); // stats if (fields[18].Length > 0) Int32.TryParse(fields[18], out info.BlocksBuilt); if (fields[19].Length > 0) Int32.TryParse(fields[19], out info.BlocksDeleted); Int32.TryParse(fields[20], out info.TimesVisited); if (fields[20].Length > 0) Int32.TryParse(fields[21], out info.MessagesWritten); Int32.TryParse(fields[22], out info.PromoCount); if (fields[23].Length > 0) info.MojangAccount = fields[23].ToString(); if (fields[24].Length > 0) info.PreviousRank = Rank.Parse(fields[24]); if (fields[25].Length > 0) info.RankChangeReason = Unescape(fields[25]); Int32.TryParse(fields[26], out info.TimesKicked); Int32.TryParse(fields[27], out info.TimesKickedOthers); Int32.TryParse(fields[28], out info.TimesBannedOthers); info.ID = Int32.Parse(fields[29]); if (info.ID < 256) info.ID = PlayerDB.GetNextID(); byte rankChangeTypeCode; if (Byte.TryParse(fields[30], out rankChangeTypeCode)) { info.RankChangeType = (RankChangeType)rankChangeTypeCode; if (!Enum.IsDefined(typeof(RankChangeType), rankChangeTypeCode)) { info.GuessRankChangeType(); } } else { info.GuessRankChangeType(); } fields[31].ToDateTime(ref info.LastKickDate); if (!fields[32].ToDateTime(ref info.LastSeen) || info.LastSeen < info.LastLoginDate) { info.LastSeen = info.LastLoginDate; } Int64.TryParse(fields[33], out info.BlocksDrawn); if (fields[34].Length > 0) info.LastKickBy = Unescape(fields[34]); if (fields[35].Length > 0) info.LastKickReason = Unescape(fields[35]); fields[36].ToDateTime(ref info.BannedUntil); info.IsFrozen = (fields[37] == "f"); if (fields[38].Length > 0) info.FrozenBy = Unescape(fields[38]); fields[39].ToDateTime(ref info.FrozenOn); fields[40].ToDateTime(ref info.MutedUntil); if (fields[41].Length > 0) info.MutedBy = Unescape(fields[41]); info.Password = Unescape(fields[42]); // fields[43] is "online", and is ignored byte bandwidthUseModeCode; if (Byte.TryParse(fields[44], out bandwidthUseModeCode)) { info.BandwidthUseMode = (BandwidthUseMode)bandwidthUseModeCode; if (!Enum.IsDefined(typeof(BandwidthUseMode), bandwidthUseModeCode)) { info.BandwidthUseMode = BandwidthUseMode.Default; } } else { info.BandwidthUseMode = BandwidthUseMode.Default; } if (fields.Length > 45) { if (fields[45].Length == 0) { info.IsHidden = false; } else { info.IsHidden = info.Rank.Can(Permission.Hide); } } if (fields.Length > 46) { fields[46].ToDateTime(ref info.LastModified); } if (fields.Length > 47 && fields[47].Length > 0) { info.DisplayedName = Unescape(fields[47]); } if (info.LastSeen < info.FirstLoginDate) { info.LastSeen = info.FirstLoginDate; } if (info.LastLoginDate < info.FirstLoginDate) { info.LastLoginDate = info.FirstLoginDate; } if (fields.Length > 48) { if (fields[48].Length > 0) Int32.TryParse(fields[48], out info.totalKillsTDM); if (fields[49].Length > 0) Int32.TryParse(fields[49], out info.totalDeathsTDM); } if (fields.Length > 50) { if (fields[50].Length > 0) Int32.TryParse(fields[50], out info.totalKillsFFA); if (fields[51].Length > 0) Int32.TryParse(fields[51], out info.totalDeathsFFA); } return info; } internal static PlayerInfo LoadFormat1(string[] fields) { PlayerInfo info = new PlayerInfo { Name = fields[0] }; if (fields[1].Length == 0 || !IPAddress.TryParse(fields[1], out info.LastIP)) { info.LastIP = IPAddress.None; } info.Rank = Rank.Parse(fields[2]) ?? RankManager.DefaultRank; fields[3].ToDateTimeLegacy(ref info.RankChangeDate); if (fields[4].Length > 0) info.RankChangedBy = fields[4]; switch (fields[5]) { case "b": info.BanStatus = BanStatus.Banned; break; case "x": info.BanStatus = BanStatus.IPBanExempt; break; default: info.BanStatus = BanStatus.NotBanned; break; } // ban information if (fields[6].ToDateTimeLegacy(ref info.BanDate)) { if (fields[7].Length > 0) info.BannedBy = Unescape(fields[7]); if (fields[10].Length > 0) info.BanReason = Unescape(fields[10]); } // unban information if (fields[8].ToDateTimeLegacy(ref info.UnbanDate)) { if (fields[9].Length > 0) info.UnbannedBy = Unescape(fields[9]); if (fields[11].Length > 0) info.UnbanReason = Unescape(fields[11]); } // failed logins fields[12].ToDateTimeLegacy(ref info.LastFailedLoginDate); if (fields[13].Length > 1 || !IPAddress.TryParse(fields[13], out info.LastFailedLoginIP)) { // LEGACY info.LastFailedLoginIP = IPAddress.None; } // skip 14 fields[15].ToDateTimeLegacy(ref info.FirstLoginDate); // login/logout times fields[16].ToDateTimeLegacy(ref info.LastLoginDate); fields[17].ToTimeSpanLegacy(ref info.TotalTime); // stats if (fields[18].Length > 0) Int32.TryParse(fields[18], out info.BlocksBuilt); if (fields[19].Length > 0) Int32.TryParse(fields[19], out info.BlocksDeleted); Int32.TryParse(fields[20], out info.TimesVisited); if (fields[20].Length > 0) Int32.TryParse(fields[21], out info.MessagesWritten); // fields 22-23 are no longer in use if (fields[24].Length > 0) info.PreviousRank = Rank.Parse(fields[24]); if (fields[25].Length > 0) info.RankChangeReason = Unescape(fields[25]); Int32.TryParse(fields[26], out info.TimesKicked); Int32.TryParse(fields[27], out info.TimesKickedOthers); Int32.TryParse(fields[28], out info.TimesBannedOthers); info.ID = Int32.Parse(fields[29]); if (info.ID < 256) info.ID = PlayerDB.GetNextID(); byte rankChangeTypeCode; if (Byte.TryParse(fields[30], out rankChangeTypeCode)) { info.RankChangeType = (RankChangeType)rankChangeTypeCode; if (!Enum.IsDefined(typeof(RankChangeType), rankChangeTypeCode)) { info.GuessRankChangeType(); } } else { info.GuessRankChangeType(); } fields[31].ToDateTimeLegacy(ref info.LastKickDate); if (!fields[32].ToDateTimeLegacy(ref info.LastSeen) || info.LastSeen < info.LastLoginDate) { info.LastSeen = info.LastLoginDate; } Int64.TryParse(fields[33], out info.BlocksDrawn); if (fields[34].Length > 0) info.LastKickBy = Unescape(fields[34]); if (fields[34].Length > 0) info.LastKickReason = Unescape(fields[35]); fields[36].ToDateTimeLegacy(ref info.BannedUntil); info.IsFrozen = (fields[37] == "f"); if (fields[38].Length > 0) info.FrozenBy = Unescape(fields[38]); fields[39].ToDateTimeLegacy(ref info.FrozenOn); fields[40].ToDateTimeLegacy(ref info.MutedUntil); if (fields[41].Length > 0) info.MutedBy = Unescape(fields[41]); info.Password = Unescape(fields[42]); // fields[43] is "online", and is ignored byte bandwidthUseModeCode; if (Byte.TryParse(fields[44], out bandwidthUseModeCode)) { info.BandwidthUseMode = (BandwidthUseMode)bandwidthUseModeCode; if (!Enum.IsDefined(typeof(BandwidthUseMode), bandwidthUseModeCode)) { info.BandwidthUseMode = BandwidthUseMode.Default; } } else { info.BandwidthUseMode = BandwidthUseMode.Default; } if (fields.Length > 45) { if (fields[45].Length == 0) { info.IsHidden = false; } else { info.IsHidden = info.Rank.Can(Permission.Hide); } } if (info.LastSeen < info.FirstLoginDate) { info.LastSeen = info.FirstLoginDate; } if (info.LastLoginDate < info.FirstLoginDate) { info.LastLoginDate = info.FirstLoginDate; } if (fields.Length > 48) { if (fields[48].Length > 0) Int32.TryParse(fields[48], out info.totalKillsTDM); if (fields[49].Length > 0) Int32.TryParse(fields[49], out info.totalDeathsTDM); } if (fields.Length > 50) { if (fields[50].Length > 0) Int32.TryParse(fields[50], out info.totalKillsFFA); if (fields[51].Length > 0) Int32.TryParse(fields[51], out info.totalDeathsFFA); } return info; } internal static PlayerInfo LoadFormat0(string[] fields, bool convertDatesToUtc) { PlayerInfo info = new PlayerInfo { Name = fields[0] }; if (fields[1].Length == 0 || !IPAddress.TryParse(fields[1], out info.LastIP)) { info.LastIP = IPAddress.None; } info.Rank = Rank.Parse(fields[2]) ?? RankManager.DefaultRank; DateTimeUtil.TryParseLocalDate(fields[3], out info.RankChangeDate); if (fields[4].Length > 0) { info.RankChangedBy = fields[4]; if (info.RankChangedBy == "-") info.RankChangedBy = null; } switch (fields[5]) { case "b": info.BanStatus = BanStatus.Banned; break; case "x": info.BanStatus = BanStatus.IPBanExempt; break; default: info.BanStatus = BanStatus.NotBanned; break; } // ban information if (DateTimeUtil.TryParseLocalDate(fields[6], out info.BanDate)) { if (fields[7].Length > 0) info.BannedBy = fields[7]; if (fields[10].Length > 0) { info.BanReason = UnescapeOldFormat(fields[10]); if (info.BanReason == "-") info.BanReason = null; } } // unban information if (DateTimeUtil.TryParseLocalDate(fields[8], out info.UnbanDate)) { if (fields[9].Length > 0) info.UnbannedBy = fields[9]; if (fields[11].Length > 0) { info.UnbanReason = UnescapeOldFormat(fields[11]); if (info.UnbanReason == "-") info.UnbanReason = null; } } // failed logins if (fields[12].Length > 1) { DateTimeUtil.TryParseLocalDate(fields[12], out info.LastFailedLoginDate); } if (fields[13].Length > 1 || !IPAddress.TryParse(fields[13], out info.LastFailedLoginIP)) { // LEGACY info.LastFailedLoginIP = IPAddress.None; } // skip 14 // login/logout times DateTimeUtil.TryParseLocalDate(fields[15], out info.FirstLoginDate); DateTimeUtil.TryParseLocalDate(fields[16], out info.LastLoginDate); TimeSpan.TryParse(fields[17], out info.TotalTime); // stats if (fields[18].Length > 0) Int32.TryParse(fields[18], out info.BlocksBuilt); if (fields[19].Length > 0) Int32.TryParse(fields[19], out info.BlocksDeleted); Int32.TryParse(fields[20], out info.TimesVisited); if (fields[20].Length > 0) Int32.TryParse(fields[21], out info.MessagesWritten); // fields 22-23 are no longer in use if (fields.Length > MinFieldCount) { if (fields[24].Length > 0) info.PreviousRank = Rank.Parse(fields[24]); if (fields[25].Length > 0) info.RankChangeReason = UnescapeOldFormat(fields[25]); Int32.TryParse(fields[26], out info.TimesKicked); Int32.TryParse(fields[27], out info.TimesKickedOthers); Int32.TryParse(fields[28], out info.TimesBannedOthers); if (fields.Length > 29) { info.ID = Int32.Parse(fields[29]); if (info.ID < 256) info.ID = PlayerDB.GetNextID(); byte rankChangeTypeCode; if (Byte.TryParse(fields[30], out rankChangeTypeCode)) { info.RankChangeType = (RankChangeType)rankChangeTypeCode; if (!Enum.IsDefined(typeof(RankChangeType), rankChangeTypeCode)) { info.GuessRankChangeType(); } } else { info.GuessRankChangeType(); } DateTimeUtil.TryParseLocalDate(fields[31], out info.LastKickDate); if (!DateTimeUtil.TryParseLocalDate(fields[32], out info.LastSeen) || info.LastSeen < info.LastLoginDate) { info.LastSeen = info.LastLoginDate; } Int64.TryParse(fields[33], out info.BlocksDrawn); if (fields[34].Length > 0) info.LastKickBy = UnescapeOldFormat(fields[34]); if (fields[35].Length > 0) info.LastKickReason = UnescapeOldFormat(fields[35]); } else { info.ID = PlayerDB.GetNextID(); info.GuessRankChangeType(); info.LastSeen = info.LastLoginDate; } if (fields.Length > 36) { DateTimeUtil.TryParseLocalDate(fields[36], out info.BannedUntil); info.IsFrozen = (fields[37] == "f"); if (fields[38].Length > 0) info.FrozenBy = UnescapeOldFormat(fields[38]); DateTimeUtil.TryParseLocalDate(fields[39], out info.FrozenOn); DateTimeUtil.TryParseLocalDate(fields[40], out info.MutedUntil); if (fields[41].Length > 0) info.MutedBy = UnescapeOldFormat(fields[41]); info.Password = UnescapeOldFormat(fields[42]); // fields[43] is "online", and is ignored } if (fields.Length > 44) { if (fields[44].Length != 0) { info.BandwidthUseMode = (BandwidthUseMode)Int32.Parse(fields[44]); } } } if (info.LastSeen < info.FirstLoginDate) { info.LastSeen = info.FirstLoginDate; } if (info.LastLoginDate < info.FirstLoginDate) { info.LastLoginDate = info.FirstLoginDate; } if (fields.Length > 48) { if (fields[48].Length > 0) Int32.TryParse(fields[48], out info.totalKillsTDM); if (fields[49].Length > 0) Int32.TryParse(fields[49], out info.totalDeathsTDM); } if (fields.Length > 50) { if (fields[50].Length > 0) Int32.TryParse(fields[50], out info.totalKillsFFA); if (fields[51].Length > 0) Int32.TryParse(fields[51], out info.totalDeathsFFA); } if (convertDatesToUtc) { if (info.RankChangeDate != DateTime.MinValue) info.RankChangeDate = info.RankChangeDate.ToUniversalTime(); if (info.BanDate != DateTime.MinValue) info.BanDate = info.BanDate.ToUniversalTime(); if (info.UnbanDate != DateTime.MinValue) info.UnbanDate = info.UnbanDate.ToUniversalTime(); if (info.LastFailedLoginDate != DateTime.MinValue) info.LastFailedLoginDate = info.LastFailedLoginDate.ToUniversalTime(); if (info.FirstLoginDate != DateTime.MinValue) info.FirstLoginDate = info.FirstLoginDate.ToUniversalTime(); if (info.LastLoginDate != DateTime.MinValue) info.LastLoginDate = info.LastLoginDate.ToUniversalTime(); if (info.LastKickDate != DateTime.MinValue) info.LastKickDate = info.LastKickDate.ToUniversalTime(); if (info.LastSeen != DateTime.MinValue) info.LastSeen = info.LastSeen.ToUniversalTime(); if (info.BannedUntil != DateTime.MinValue) info.BannedUntil = info.BannedUntil.ToUniversalTime(); if (info.FrozenOn != DateTime.MinValue) info.FrozenOn = info.FrozenOn.ToUniversalTime(); if (info.MutedUntil != DateTime.MinValue) info.MutedUntil = info.MutedUntil.ToUniversalTime(); } return info; } void GuessRankChangeType() { if (PreviousRank != null) { if (RankChangeReason == "~AutoRank" || RankChangeReason == "~AutoRankAll" || RankChangeReason == "~MassRank") { if (PreviousRank > Rank) { RankChangeType = RankChangeType.AutoDemoted; } else if (PreviousRank < Rank) { RankChangeType = RankChangeType.AutoPromoted; } } else { if (PreviousRank > Rank) { RankChangeType = RankChangeType.Demoted; } else if (PreviousRank < Rank) { RankChangeType = RankChangeType.Promoted; } } } else { RankChangeType = RankChangeType.Default; } } internal static PlayerInfo LoadBinaryFormat0([NotNull] BinaryReader reader) { if (reader == null) throw new ArgumentNullException("reader"); // ReSharper disable UseObjectOrCollectionInitializer PlayerInfo info = new PlayerInfo(); // ReSharper restore UseObjectOrCollectionInitializer // General info.Name = reader.ReadString(); info.DisplayedName = ReadString(reader); info.ID = Read7BitEncodedInt(reader); info.LastSeen = DateTimeUtil.ToDateTime(reader.ReadUInt32()); // Rank int rankIndex = Read7BitEncodedInt(reader); info.Rank = PlayerDB.GetRankByIndex(rankIndex); { bool hasPrevRank = reader.ReadBoolean(); if (hasPrevRank) { int prevRankIndex = Read7BitEncodedInt(reader); info.Rank = PlayerDB.GetRankByIndex(prevRankIndex); } } info.RankChangeType = (RankChangeType)reader.ReadByte(); if (info.RankChangeType != RankChangeType.Default) { info.RankChangeDate = ReadDate(reader); info.RankChangedBy = ReadString(reader); info.RankChangeReason = ReadString(reader); } // Bans info.BanStatus = (BanStatus)reader.ReadByte(); info.BanDate = ReadDate(reader); info.BannedBy = ReadString(reader); info.BanReason = ReadString(reader); if (info.BanStatus == BanStatus.Banned) { info.BannedUntil = ReadDate(reader); info.LastFailedLoginDate = ReadDate(reader); info.LastFailedLoginIP = new IPAddress(reader.ReadBytes(4)); } else { info.UnbanDate = ReadDate(reader); info.UnbannedBy = ReadString(reader); info.UnbanReason = ReadString(reader); } // Stats info.FirstLoginDate = DateTimeUtil.ToDateTime(reader.ReadUInt32()); info.LastLoginDate = DateTimeUtil.ToDateTime(reader.ReadUInt32()); info.TotalTime = new TimeSpan(reader.ReadUInt32() * TimeSpan.TicksPerSecond); info.BlocksBuilt = Read7BitEncodedInt(reader); info.BlocksDeleted = Read7BitEncodedInt(reader); if (reader.ReadBoolean()) { info.BlocksDrawn = reader.ReadInt64(); } info.TimesVisited = Read7BitEncodedInt(reader); info.MessagesWritten = Read7BitEncodedInt(reader); info.TimesKickedOthers = Read7BitEncodedInt(reader); info.TimesBannedOthers = Read7BitEncodedInt(reader); // Kicks info.TimesKicked = Read7BitEncodedInt(reader); if (info.TimesKicked > 0) { info.LastKickDate = ReadDate(reader); info.LastKickBy = ReadString(reader); info.LastKickReason = ReadString(reader); } // Freeze/Mute info.IsFrozen = reader.ReadBoolean(); if (info.IsFrozen) { info.FrozenOn = ReadDate(reader); info.FrozenBy = ReadString(reader); } info.MutedUntil = ReadDate(reader); if (info.MutedUntil != DateTime.MinValue) { info.MutedBy = ReadString(reader); } // Misc info.Password = ReadString(reader); info.LastModified = DateTimeUtil.ToDateTime(reader.ReadUInt32()); info.IsOnline = reader.ReadBoolean(); info.IsHidden = reader.ReadBoolean(); info.LastIP = new IPAddress(reader.ReadBytes(4)); info.LeaveReason = (LeaveReason)reader.ReadByte(); info.BandwidthUseMode = (BandwidthUseMode)reader.ReadByte(); return info; } static DateTime ReadDate([NotNull] BinaryReader reader) { if (reader.ReadBoolean()) { return DateTimeUtil.ToDateTime(reader.ReadUInt32()); } else { return DateTime.MinValue; } } static string ReadString([NotNull] BinaryReader reader) { if (reader.ReadBoolean()) { return reader.ReadString(); } else { return null; } } static int Read7BitEncodedInt([NotNull] BinaryReader reader) { byte num3; int num = 0; int num2 = 0; do { if (num2 == 0x23) { throw new FormatException("Invalid 7bit encoded integer."); } num3 = reader.ReadByte(); num |= (num3 & 0x7f) << num2; num2 += 7; } while ((num3 & 0x80) != 0); return num; } #endregion #region Saving internal void Serialize(StringBuilder sb) { sb.Append(Name).Append(','); // 0 if (!LastIP.Equals(IPAddress.None)) sb.Append(LastIP); // 1 sb.Append(','); sb.Append(Rank.FullName).Append(','); // 2 RankChangeDate.ToUnixTimeString(sb).Append(','); // 3 sb.AppendEscaped(RankChangedBy).Append(','); // 4 switch (BanStatus) { case BanStatus.Banned: sb.Append('b'); break; case BanStatus.IPBanExempt: sb.Append('x'); break; } sb.Append(','); // 5 BanDate.ToUnixTimeString(sb).Append(','); // 6 sb.AppendEscaped(BannedBy).Append(','); // 7 UnbanDate.ToUnixTimeString(sb).Append(','); // 8 sb.AppendEscaped(UnbannedBy).Append(','); // 9 sb.AppendEscaped(BanReason).Append(','); // 10 sb.AppendEscaped(UnbanReason).Append(','); // 11 LastFailedLoginDate.ToUnixTimeString(sb).Append(','); // 12 if (!LastFailedLoginIP.Equals(IPAddress.None)) sb.Append(LastFailedLoginIP.ToString()); // 13 sb.Append(','); if (Money > 0) sb.Digits(Money); // 14 sb.Append(','); FirstLoginDate.ToUnixTimeString(sb).Append(','); // 15 LastLoginDate.ToUnixTimeString(sb).Append(','); // 16 Player pObject = PlayerObject; if (pObject != null) { (TotalTime.Add(TimeSinceLastLogin)).ToTickString(sb).Append(','); // 17 } else { TotalTime.ToTickString(sb).Append(','); // 17 } if (BlocksBuilt > 0) sb.Digits(BlocksBuilt); // 18 sb.Append(','); if (BlocksDeleted > 0) sb.Digits(BlocksDeleted); // 19 sb.Append(','); sb.Append(TimesVisited).Append(','); // 20 if (MessagesWritten > 0) sb.Digits(MessagesWritten); // 21 sb.Append(','); if (PromoCount > 0) sb.Digits(PromoCount); //22 sb.Append(','); sb.Append(MojangAccount); //23 sb.Append(','); if (PreviousRank != null) sb.Append(PreviousRank.FullName); // 24 sb.Append(','); sb.AppendEscaped(RankChangeReason).Append(','); // 25 if (TimesKicked > 0) sb.Digits(TimesKicked); // 26 sb.Append(','); if (TimesKickedOthers > 0) sb.Digits(TimesKickedOthers); // 27 sb.Append(','); if (TimesBannedOthers > 0) sb.Digits(TimesBannedOthers); // 28 sb.Append(','); sb.Digits(ID).Append(','); // 29 sb.Digits((int)RankChangeType).Append(','); // 30 LastKickDate.ToUnixTimeString(sb).Append(','); // 31 if (IsOnline) DateTime.UtcNow.ToUnixTimeString(sb); // 32 else LastSeen.ToUnixTimeString(sb); sb.Append(','); if (BlocksDrawn > 0) sb.Append(BlocksDrawn); // 33 sb.Append(','); sb.AppendEscaped(LastKickBy).Append(','); // 34 sb.AppendEscaped(LastKickReason).Append(','); // 35 BannedUntil.ToUnixTimeString(sb); // 36 if (IsFrozen) { sb.Append(',').Append('f').Append(','); // 37 sb.AppendEscaped(FrozenBy).Append(','); // 38 FrozenOn.ToUnixTimeString(sb).Append(','); // 39 } else { sb.Append(',', 4); // 37-39 } if (MutedUntil > DateTime.UtcNow) { MutedUntil.ToUnixTimeString(sb).Append(','); // 40 sb.AppendEscaped(MutedBy).Append(','); // 41 } else { sb.Append(',', 2); // 40-41 } sb.AppendEscaped(Password).Append(','); // 42 if (IsOnline) sb.Append('o'); // 43 sb.Append(','); if (BandwidthUseMode != BandwidthUseMode.Default) sb.Append((int)BandwidthUseMode); // 44 sb.Append(','); if (IsHidden) sb.Append('h'); // 45 sb.Append(','); LastModified.ToUnixTimeString(sb); // 46 sb.Append(','); sb.AppendEscaped(DisplayedName); // 47 sb.Append(','); if (totalKillsTDM > 0) sb.Digits(totalKillsTDM); // 48 sb.Append(','); if (totalDeathsTDM > 0) sb.Digits(totalDeathsTDM); // 49 sb.Append(','); if (totalKillsFFA > 0) sb.Digits(totalKillsFFA); // 50 sb.Append(','); if (totalDeathsFFA > 0) sb.Digits(totalDeathsFFA); // 51 } internal void Serialize([NotNull] BinaryWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); // General writer.Write(Name); // 0 WriteString(writer, DisplayedName); // 1 Write7BitEncodedInt(writer, ID); // 2 if (IsOnline) { writer.Write((uint)DateTime.UtcNow.ToUnixTime()); // 5 } else { writer.Write((uint)LastSeen.ToUnixTime()); // 5 } // Rank Write7BitEncodedInt(writer, Rank.Index); // 7 { bool hasPrevRank = (PreviousRank != null); writer.Write(hasPrevRank); if (hasPrevRank) { Write7BitEncodedInt(writer, PreviousRank.Index); // 8 } } writer.Write((byte)RankChangeType); // 12 if (RankChangeType != RankChangeType.Default) { WriteDate(writer, RankChangeDate); // 9 WriteString(writer, RankChangedBy); // 10 WriteString(writer, RankChangeReason); // 11 } // Bans writer.Write((byte)BanStatus); // 13 WriteDate(writer, BanDate); // 14 WriteString(writer, BannedBy); // 15 WriteString(writer, BanReason); // 16 if (BanStatus == BanStatus.Banned) { WriteDate(writer, BannedUntil); // 14 WriteDate(writer, LastFailedLoginDate); // 20 writer.Write(LastFailedLoginIP.GetAddressBytes()); // 21 } else { WriteDate(writer, UnbanDate); // 17 WriteString(writer, UnbannedBy); // 18 WriteString(writer, UnbanReason); // 18 } // Stats writer.Write((uint)FirstLoginDate.ToUnixTime()); // 3 writer.Write((uint)LastLoginDate.ToUnixTime()); // 4 if (IsOnline) { writer.Write((uint)TotalTime.Add(TimeSinceLastLogin).ToSeconds()); // 22 } else { writer.Write((uint)TotalTime.ToSeconds()); // 22 } Write7BitEncodedInt(writer, Money); // field 14 Write7BitEncodedInt(writer, BlocksBuilt); // 23 Write7BitEncodedInt(writer, BlocksDeleted); // 24 writer.Write(BlocksDrawn > 0); if (BlocksDrawn > 0) writer.Write(BlocksDrawn); // 25 Write7BitEncodedInt(writer, TimesVisited); // 26 Write7BitEncodedInt(writer, MessagesWritten); // 27 Write7BitEncodedInt(writer, PromoCount); //22 (?) WriteString(writer, MojangAccount); //23 Good enough Write7BitEncodedInt(writer, TimesKickedOthers); // 28 Write7BitEncodedInt(writer, TimesBannedOthers); // 29 // Kicks Write7BitEncodedInt(writer, TimesKicked); // 30 if (TimesKicked > 0) { WriteDate(writer, LastKickDate); // 31 WriteString(writer, LastKickBy); // 32 WriteString(writer, LastKickReason); // 33 } // Freeze/Mute writer.Write(IsFrozen); // 34 if (IsFrozen) { WriteDate(writer, FrozenOn); // 35 WriteString(writer, FrozenBy); // 36 } WriteDate(writer, MutedUntil); // 37 if (MutedUntil != DateTime.MinValue) { WriteString(writer, MutedBy); // 38 } // Misc WriteString(writer, Password); writer.Write((uint)LastModified.ToUnixTime()); writer.Write(IsOnline); // 39 writer.Write(IsHidden); // 40 writer.Write(LastIP.GetAddressBytes()); // 41 writer.Write((byte)LeaveReason); // 6 writer.Write((byte)BandwidthUseMode); // 6 //TDM Stats Write7BitEncodedInt(writer, totalKillsTDM); // 48 Write7BitEncodedInt(writer, totalDeathsTDM); // 49 //FFA Stats Write7BitEncodedInt(writer, totalKillsFFA); // 50 Write7BitEncodedInt(writer, totalDeathsFFA); // 51 } static void WriteDate([NotNull] BinaryWriter writer, DateTime dateTime) { bool hasDate = (dateTime != DateTime.MinValue); writer.Write(hasDate); if (hasDate) { writer.Write((uint)dateTime.ToUnixTime()); } } static void WriteString([NotNull] BinaryWriter writer, [CanBeNull] string str) { bool hasString = (str != null); writer.Write(hasString); if (hasString) { writer.Write(str); } } static void Write7BitEncodedInt([NotNull] BinaryWriter writer, int value) { uint num = (uint)value; while (num >= 0x80) { writer.Write((byte)(num | 0x80)); num = num >> 7; } writer.Write((byte)num); } #endregion #region Update Handlers public void ProcessMessageWritten() { Interlocked.Increment(ref MessagesWritten); LastModified = DateTime.UtcNow; } public void ProcessLogin([NotNull] Player player) { if (player == null) throw new ArgumentNullException("player"); LastIP = player.IP; LastLoginDate = DateTime.UtcNow; LastSeen = DateTime.UtcNow; Interlocked.Increment(ref TimesVisited); IsOnline = true; PlayerObject = player; LastModified = DateTime.UtcNow; } public void ProcessFailedLogin([NotNull] Player player) { if (player == null) throw new ArgumentNullException("player"); LastFailedLoginDate = DateTime.UtcNow; LastFailedLoginIP = player.IP; LastModified = DateTime.UtcNow; } public void ProcessLogout([NotNull] Player player) { if (player == null) throw new ArgumentNullException("player"); TotalTime += player.LastActiveTime.Subtract(player.LoginTime); LastSeen = DateTime.UtcNow; IsOnline = false; PlayerObject = null; LeaveReason = player.LeaveReason; LastModified = DateTime.UtcNow; //fix names if they leave during a TDM/FFA game if (player.Info.isPlayingTD || player.Info.isPlayingFFA) { player.iName = null; DisplayedName = oldname; isOnRedTeam = false; isOnBlueTeam = false; isPlayingTD = false; isPlayingFFA = false; player.entityChanged = true; } } public void ProcessRankChange([NotNull] Rank newRank, [NotNull] string changer, [CanBeNull] string reason, RankChangeType type) { if (newRank == null) throw new ArgumentNullException("newRank"); if (changer == null) throw new ArgumentNullException("changer"); PreviousRank = Rank; Rank = newRank; RankChangeDate = DateTime.UtcNow; RankChangedBy = changer; RankChangeReason = reason; RankChangeType = type; LastModified = DateTime.UtcNow; } public void ProcessBlockPlaced(byte type) { if (type == 0) { // air Interlocked.Increment(ref BlocksDeleted); } else { Interlocked.Increment(ref BlocksBuilt); } LastModified = DateTime.UtcNow; } public void ProcessDrawCommand(int blocksDrawn) { Interlocked.Add(ref BlocksDrawn, blocksDrawn); LastModified = DateTime.UtcNow; } internal void ProcessKick([NotNull] Player kickedBy, [CanBeNull] string reason) { if (kickedBy == null) throw new ArgumentNullException("kickedBy"); if (reason != null && reason.Trim().Length == 0) reason = null; lock (actionLock) { Interlocked.Increment(ref TimesKicked); Interlocked.Increment(ref kickedBy.Info.TimesKickedOthers); LastKickDate = DateTime.UtcNow; LastKickBy = kickedBy.Name; LastKickReason = reason; if (IsFrozen) { try { Unfreeze(kickedBy, false, true); } catch (PlayerOpException ex) { Logger.Log(LogType.Warning, "PlayerInfo.ProcessKick: {0}", ex.Message); } } LastModified = DateTime.UtcNow; } } #endregion #region Utilities public static string Escape([CanBeNull] string str) { if (String.IsNullOrEmpty(str)) { return ""; } else if (str.IndexOf(',') > -1) { return str.Replace(',', '\xFF'); } else { return str; } } public static string UnescapeOldFormat([NotNull] string str) { if (str == null) throw new ArgumentNullException("str"); return str.Replace('\xFF', ',').Replace("\'", "'").Replace(@"\\", @"\"); } public static string Unescape([NotNull] string str) { if (str == null) throw new ArgumentNullException("str"); if (str.IndexOf('\xFF') > -1) { return str.Replace('\xFF', ','); } else { return str; } } // implements IClassy interface public string ClassyName { get { StringBuilder sb = new StringBuilder(); if (TitleName != null) { sb.Append(TitleName); } if (ConfigKey.RankColorsInChat.Enabled()) { sb.Append(Rank.Color); } //tempDisplayName overrides DisplayedName always, but we store displayedname for use after games if (tempDisplayedName != null) { sb.Append(tempDisplayedName); } else if(DisplayedName != null) { sb.Append(DisplayedName);//Create priority list: Check temp first, then displ name, and finally use Name if nothing works } else { if (ConfigKey.RankPrefixesInChat.Enabled()) { sb.Append(Rank.Prefix); } sb.Append(Name); } if (IsBanned) { sb.Append(Color.Warning).Append('*'); } if (IsFrozen) { sb.Append(Color.Blue).Append('*'); } if (IsMuted) { sb.Append(Color.Olive).Append('*'); } if (IsWarned) { sb.Append(Color.Black).Append('*'); } return sb.ToString(); } } #endregion #region TimeSince_____ shortcuts public TimeSpan TimeSinceRankChange { get { return DateTime.UtcNow.Subtract(RankChangeDate); } } public TimeSpan TimeSinceBan { get { return DateTime.UtcNow.Subtract(BanDate); } } public TimeSpan TimeSinceUnban { get { return DateTime.UtcNow.Subtract(UnbanDate); } } public TimeSpan TimeSinceFirstLogin { get { return DateTime.UtcNow.Subtract(FirstLoginDate); } } public TimeSpan TimeSinceLastLogin { get { return DateTime.UtcNow.Subtract(LastLoginDate); } } public TimeSpan TimeSinceLastKick { get { return DateTime.UtcNow.Subtract(LastKickDate); } } public TimeSpan TimeSinceLastSeen { get { return DateTime.UtcNow.Subtract(LastSeen); } } public TimeSpan TimeSinceFrozen { get { return DateTime.UtcNow.Subtract(FrozenOn); } } public TimeSpan TimeMutedLeft { get { return MutedUntil.Subtract(DateTime.UtcNow); } } #endregion public override string ToString() { return String.Format("PlayerInfo({0},{1})", Name, Rank.Name); } public bool Can(Permission permission) { return Rank.Can(permission); } public bool Can(Permission permission, Rank rank) { return Rank.Can(permission, rank); } #region Unfinished / Not Implemented /// <summary> Not implemented (IRC/server password hash). </summary> public string Password = ""; // TODO public DateTime LastModified; // TODO public BandwidthUseMode BandwidthUseMode; // TODO /// <summary> Not implemented (for temp bans). </summary> public DateTime BannedUntil; // TODO #endregion } public sealed class PlayerInfoComparer : IComparer<PlayerInfo> { readonly Player observer; public PlayerInfoComparer(Player observer) { this.observer = observer; } public int Compare(PlayerInfo x, PlayerInfo y) { Player xPlayer = x.PlayerObject; Player yPlayer = y.PlayerObject; bool xIsOnline = xPlayer != null && observer.CanSee(xPlayer); bool yIsOnline = yPlayer != null && observer.CanSee(yPlayer); if (!xIsOnline && yIsOnline) { return 1; } else if (xIsOnline && !yIsOnline) { return -1; } if (x.Rank == y.Rank) { return Math.Sign(y.LastSeen.Ticks - x.LastSeen.Ticks); } else { return x.Rank.Index - y.Rank.Index; } } } }
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // 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; using System.Data; using System.Data.Common; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq.Expressions; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; #if MONO_STRICT using AttributeMappingSource = System.Data.Linq.Mapping.AttributeMappingSource; #else using AttributeMappingSource = DbLinq.Data.Linq.Mapping.AttributeMappingSource; #endif using DbLinq; using DbLinq.Data.Linq; using DbLinq.Data.Linq.Database; using DbLinq.Data.Linq.Database.Implementation; using DbLinq.Data.Linq.Identity; using DbLinq.Data.Linq.Implementation; using DbLinq.Data.Linq.Mapping; using DbLinq.Data.Linq.Sugar; using DbLinq.Factory; using DbLinq.Util; using DbLinq.Vendor; #if MONO_STRICT namespace System.Data.Linq #else namespace DbLinq.Data.Linq #endif { public partial class DataContext : IDisposable { //private readonly Dictionary<string, ITable> _tableMap = new Dictionary<string, ITable>(); private readonly Dictionary<Type, ITable> _tableMap = new Dictionary<Type, ITable>(); public MetaModel Mapping { get; private set; } // PC question: at ctor, we get a IDbConnection and the Connection property exposes a DbConnection // WTF? public DbConnection Connection { get { return DatabaseContext.Connection as DbConnection; } } // all properties below are set public to optionally be injected internal IVendor Vendor { get; set; } internal IQueryBuilder QueryBuilder { get; set; } internal IQueryRunner QueryRunner { get; set; } internal IMemberModificationHandler MemberModificationHandler { get; set; } internal IDatabaseContext DatabaseContext { get; private set; } // /all properties... private bool objectTrackingEnabled = true; private bool deferredLoadingEnabled = true; private bool queryCacheEnabled = false; /// <summary> /// Disable the QueryCache: this is surely good for rarely used Select, since preparing /// the SelectQuery to be cached could require more time than build the sql from scratch. /// </summary> [DBLinqExtended] public bool QueryCacheEnabled { get { return queryCacheEnabled; } set { queryCacheEnabled = value; } } private IEntityTracker currentTransactionEntities; private IEntityTracker CurrentTransactionEntities { get { if (this.currentTransactionEntities == null) { if (this.ObjectTrackingEnabled) this.currentTransactionEntities = new EntityTracker(); else this.currentTransactionEntities = new DisabledEntityTracker(); } return this.currentTransactionEntities; } } private IEntityTracker allTrackedEntities; private IEntityTracker AllTrackedEntities { get { if (this.allTrackedEntities == null) { allTrackedEntities = ObjectTrackingEnabled ? (IEntityTracker) new EntityTracker() : (IEntityTracker) new DisabledEntityTracker(); } return this.allTrackedEntities; } } private IIdentityReaderFactory identityReaderFactory; private readonly IDictionary<Type, IIdentityReader> identityReaders = new Dictionary<Type, IIdentityReader>(); /// <summary> /// The default behavior creates one MappingContext. /// </summary> [DBLinqExtended] internal virtual MappingContext _MappingContext { get; set; } [DBLinqExtended] internal IVendorProvider _VendorProvider { get; set; } public DataContext(IDbConnection connection, MappingSource mapping) { Profiler.At("START DataContext(IDbConnection, MappingSource)"); Init(new DatabaseContext(connection), mapping, null); Profiler.At("END DataContext(IDbConnection, MappingSource)"); } public DataContext(IDbConnection connection) { Profiler.At("START DataContext(IDbConnection)"); if (connection == null) throw new ArgumentNullException("connection"); Init(new DatabaseContext(connection), null, null); Profiler.At("END DataContext(IDbConnection)"); } [DbLinqToDo] public DataContext(string fileOrServerOrConnection, MappingSource mapping) { Profiler.At("START DataContext(string, MappingSource)"); if (fileOrServerOrConnection == null) throw new ArgumentNullException("fileOrServerOrConnection"); if (mapping == null) throw new ArgumentNullException("mapping"); if (File.Exists(fileOrServerOrConnection)) throw new NotImplementedException("File names not supported."); // Is this a decent server name check? // It assumes that the connection string will have at least 2 // parameters (separated by ';') if (!fileOrServerOrConnection.Contains(";")) throw new NotImplementedException("Server name not supported."); // Assume it's a connection string... IVendor ivendor = GetVendor(ref fileOrServerOrConnection); IDbConnection dbConnection = ivendor.CreateDbConnection(fileOrServerOrConnection); Init(new DatabaseContext(dbConnection), mapping, ivendor); Profiler.At("END DataContext(string, MappingSource)"); } /// <summary> /// Construct DataContext, given a connectionString. /// To determine which DB type to go against, we look for 'DbLinqProvider=xxx' substring. /// If not found, we assume that we are dealing with MS Sql Server. /// /// Valid values are names of provider DLLs (or any other DLL containing an IVendor implementation) /// DbLinqProvider=Mysql /// DbLinqProvider=Oracle etc. /// </summary> /// <param name="connectionString">specifies file or server connection</param> [DbLinqToDo] public DataContext(string connectionString) { Profiler.At("START DataContext(string)"); IVendor ivendor = GetVendor(ref connectionString); IDbConnection dbConnection = ivendor.CreateDbConnection(connectionString); Init(new DatabaseContext(dbConnection), null, ivendor); Profiler.At("END DataContext(string)"); } private IVendor GetVendor(ref string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); Assembly assy; string vendorClassToLoad; GetVendorInfo(ref connectionString, out assy, out vendorClassToLoad); var types = from type in assy.GetTypes() where type.Name.ToLowerInvariant() == vendorClassToLoad.ToLowerInvariant() && type.GetInterfaces().Contains(typeof(IVendor)) && type.GetConstructor(Type.EmptyTypes) != null select type; if (!types.Any()) { throw new ArgumentException(string.Format("Found no IVendor class in assembly `{0}' named `{1}' having a default constructor.", assy.GetName().Name, vendorClassToLoad)); } else if (types.Count() > 1) { throw new ArgumentException(string.Format("Found too many IVendor classes in assembly `{0}' named `{1}' having a default constructor.", assy.GetName().Name, vendorClassToLoad)); } return (IVendor) Activator.CreateInstance(types.First()); } private void GetVendorInfo(ref string connectionString, out Assembly assembly, out string typeName) { System.Text.RegularExpressions.Regex reProvider = new System.Text.RegularExpressions.Regex(@"DbLinqProvider=([\w\.]+);?"); string assemblyName = null; string vendor; if (!reProvider.IsMatch(connectionString)) { vendor = "SqlServer"; assemblyName = "DbLinq.SqlServer"; } else { var match = reProvider.Match(connectionString); vendor = match.Groups[1].Value; assemblyName = "DbLinq." + vendor; //plain DbLinq - non MONO: //IVendor classes are in DLLs such as "DbLinq.MySql.dll" if (vendor.Contains(".")) { //already fully qualified DLL name? throw new ArgumentException("Please provide a short name, such as 'MySql', not '" + vendor + "'"); } //shorten: "DbLinqProvider=X;Server=Y" -> ";Server=Y" connectionString = reProvider.Replace(connectionString, ""); } typeName = vendor + "Vendor"; try { #if MONO_STRICT assembly = typeof (DataContext).Assembly; // System.Data.Linq.dll #else assembly = Assembly.Load(assemblyName); #endif } catch (Exception e) { throw new ArgumentException( string.Format( "Unable to load the `{0}' DbLinq vendor within assembly '{1}.dll'.", assemblyName, vendor), "connectionString", e); } } private void Init(IDatabaseContext databaseContext, MappingSource mappingSource, IVendor vendor) { if (databaseContext == null) throw new ArgumentNullException("databaseContext"); // Yes, .NET throws an NRE for this. Why it's not ArgumentNullException, I couldn't tell you. if (databaseContext.Connection.ConnectionString == null) throw new NullReferenceException(); string connectionString = databaseContext.Connection.ConnectionString; _VendorProvider = ObjectFactory.Get<IVendorProvider>(); Vendor = vendor ?? (connectionString != null ? GetVendor(ref connectionString) : null) ?? _VendorProvider.FindVendorByProviderType(typeof(SqlClient.Sql2005Provider)); DatabaseContext = databaseContext; MemberModificationHandler = ObjectFactory.Create<IMemberModificationHandler>(); // not a singleton: object is stateful QueryBuilder = ObjectFactory.Get<IQueryBuilder>(); QueryRunner = ObjectFactory.Get<IQueryRunner>(); //EntityMap = ObjectFactory.Create<IEntityMap>(); identityReaderFactory = ObjectFactory.Get<IIdentityReaderFactory>(); _MappingContext = new MappingContext(); // initialize the mapping information if (mappingSource == null) mappingSource = new AttributeMappingSource(); Mapping = mappingSource.GetModel(GetType()); } /// <summary> /// Checks if the table is allready mapped or maps it if not. /// </summary> /// <param name="tableType">Type of the table.</param> /// <exception cref="InvalidOperationException">Thrown if the table is not mappable.</exception> private void CheckTableMapping(Type tableType) { //This will throw an exception if the table is not found if(Mapping.GetTable(tableType) == null) { throw new InvalidOperationException("The type '" + tableType.Name + "' is not mapped as a Table."); } } /// <summary> /// Returns a Table for the type TEntity. /// </summary> /// <exception cref="InvalidOperationException">If the type TEntity is not mappable as a Table.</exception> /// <typeparam name="TEntity">The table type.</typeparam> public Table<TEntity> GetTable<TEntity>() where TEntity : class { return (Table<TEntity>)GetTable(typeof(TEntity)); } /// <summary> /// Returns a Table for the given type. /// </summary> /// <param name="type">The table type.</param> /// <exception cref="InvalidOperationException">If the type is not mappable as a Table.</exception> public ITable GetTable(Type type) { Profiler.At("DataContext.GetTable(typeof({0}))", type != null ? type.Name : null); ITable tableExisting; if (_tableMap.TryGetValue(type, out tableExisting)) return tableExisting; //Check for table mapping CheckTableMapping(type); var tableNew = Activator.CreateInstance( typeof(Table<>).MakeGenericType(type) , BindingFlags.NonPublic | BindingFlags.Instance , null , new object[] { this } , System.Globalization.CultureInfo.CurrentCulture) as ITable; _tableMap[type] = tableNew; return tableNew; } public void SubmitChanges() { SubmitChanges(ConflictMode.FailOnFirstConflict); } /// <summary> /// Pings database /// </summary> /// <returns></returns> public bool DatabaseExists() { try { return Vendor.Ping(this); } catch (Exception) { return false; } } /// <summary> /// Commits all pending changes to database /// </summary> /// <param name="failureMode"></param> public virtual void SubmitChanges(ConflictMode failureMode) { if (this.objectTrackingEnabled == false) throw new InvalidOperationException("Object tracking is not enabled for the current data context instance."); using (DatabaseContext.OpenConnection()) //ConnMgr will close connection for us { if (Transaction != null) SubmitChangesImpl(failureMode); else { using (IDbTransaction transaction = DatabaseContext.CreateTransaction()) { try { Transaction = (DbTransaction) transaction; SubmitChangesImpl(failureMode); // TODO: handle conflicts (which can only occur when concurrency mode is implemented) transaction.Commit(); } finally { Transaction = null; } } } } } void SubmitChangesImpl(ConflictMode failureMode) { var queryContext = new QueryContext(this); // There's no sense in updating an entity when it's going to // be deleted in the current transaction, so do deletes first. foreach (var entityTrack in CurrentTransactionEntities.EnumerateAll().ToList()) { switch (entityTrack.EntityState) { case EntityState.ToDelete: var deleteQuery = QueryBuilder.GetDeleteQuery(entityTrack.Entity, queryContext); QueryRunner.Delete(entityTrack.Entity, deleteQuery); UnregisterDelete(entityTrack.Entity); AllTrackedEntities.RegisterToDelete(entityTrack.Entity); AllTrackedEntities.RegisterDeleted(entityTrack.Entity); break; default: // ignore. break; } } foreach (var entityTrack in CurrentTransactionEntities.EnumerateAll() .Concat(AllTrackedEntities.EnumerateAll()) .ToList()) { switch (entityTrack.EntityState) { case EntityState.ToInsert: foreach (var toInsert in GetReferencedObjects(entityTrack.Entity)) { InsertEntity(toInsert, queryContext); } break; case EntityState.ToWatch: foreach (var toUpdate in GetReferencedObjects(entityTrack.Entity)) { UpdateEntity(toUpdate, queryContext); } break; default: throw new ArgumentOutOfRangeException(); } } } private IEnumerable<object> GetReferencedObjects(object value) { var values = new EntitySet<object>(); FillReferencedObjects(value, values); return values; } // Breadth-first traversal of an object graph private void FillReferencedObjects(object parent, EntitySet<object> values) { if (parent == null) return; var children = new Queue<object>(); children.Enqueue(parent); while (children.Count > 0) { object value = children.Dequeue(); values.Add(value); IEnumerable<MetaAssociation> associationList = Mapping.GetMetaType(value.GetType()).Associations.Where(a => !a.IsForeignKey); if (associationList.Any()) { foreach (MetaAssociation association in associationList) { var memberData = association.ThisMember; var entitySetValue = memberData.Member.GetMemberValue(value); if (entitySetValue != null) { var hasLoadedOrAssignedValues = entitySetValue.GetType().GetProperty("HasLoadedOrAssignedValues"); if (!((bool)hasLoadedOrAssignedValues.GetValue(entitySetValue, null))) continue; // execution deferred; ignore. foreach (var o in ((IEnumerable)entitySetValue)) children.Enqueue(o); } } } } } private void InsertEntity(object entity, QueryContext queryContext) { var insertQuery = QueryBuilder.GetInsertQuery(entity, queryContext); QueryRunner.Insert(entity, insertQuery); Register(entity); UpdateReferencedObjects(entity); MoveToAllTrackedEntities(entity, true); } private void UpdateEntity(object entity, QueryContext queryContext) { if (!AllTrackedEntities.ContainsReference(entity)) InsertEntity(entity, queryContext); else if (MemberModificationHandler.IsModified(entity, Mapping)) { var modifiedMembers = MemberModificationHandler.GetModifiedProperties(entity, Mapping); var updateQuery = QueryBuilder.GetUpdateQuery(entity, modifiedMembers, queryContext); QueryRunner.Update(entity, updateQuery, modifiedMembers); RegisterUpdateAgain(entity); UpdateReferencedObjects(entity); MoveToAllTrackedEntities(entity, false); } } private void UpdateReferencedObjects(object root) { var metaType = Mapping.GetMetaType(root.GetType()); foreach (var assoc in metaType.Associations) { var memberData = assoc.ThisMember; //This is not correct - AutoSyncing applies to auto-updating columns, such as a TimeStamp, not to foreign key associations, which is always automatically synched //Confirmed against default .NET l2sql - association columns are always set, even if AutoSync==AutoSync.Never //if (memberData.Association.ThisKey.Any(m => (m.AutoSync != AutoSync.Always) && (m.AutoSync != sync))) // continue; var oks = memberData.Association.OtherKey.Select(m => m.StorageMember).ToList(); if (oks.Count == 0) continue; var pks = memberData.Association.ThisKey .Select(m => m.StorageMember.GetMemberValue(root)) .ToList(); if (pks.Count != oks.Count) throw new InvalidOperationException( string.Format("Count of primary keys ({0}) doesn't match count of other keys ({1}).", pks.Count, oks.Count)); var members = memberData.Member.GetMemberValue(root) as IEnumerable; if (members == null) continue; foreach (var member in members) { for (int i = 0; i < pks.Count; ++i) { oks[i].SetMemberValue(member, pks[i]); } } } } private void MoveToAllTrackedEntities(object entity, bool insert) { if (!ObjectTrackingEnabled) return; if (CurrentTransactionEntities.ContainsReference(entity)) { CurrentTransactionEntities.RegisterToDelete(entity); if (!insert) CurrentTransactionEntities.RegisterDeleted(entity); } if (!AllTrackedEntities.ContainsReference(entity)) { var identityReader = _GetIdentityReader(entity.GetType()); AllTrackedEntities.RegisterToWatch(entity, identityReader.GetIdentityKey(entity)); } } /// <summary> /// TODO - allow generated methods to call into stored procedures /// </summary> [DBLinqExtended] internal IExecuteResult _ExecuteMethodCall(DataContext context, System.Reflection.MethodInfo method, params object[] sqlParams) { using (DatabaseContext.OpenConnection()) { System.Data.Linq.IExecuteResult result = Vendor.ExecuteMethodCall(context, method, sqlParams); return result; } } [DbLinqToDo] protected IExecuteResult ExecuteMethodCall(object instance, System.Reflection.MethodInfo methodInfo, params object[] parameters) { throw new NotImplementedException(); } #region Identity management [DBLinqExtended] internal IIdentityReader _GetIdentityReader(Type t) { IIdentityReader identityReader; if (!identityReaders.TryGetValue(t, out identityReader)) { identityReader = identityReaderFactory.GetReader(t, this); identityReaders[t] = identityReader; } return identityReader; } [DBLinqExtended] internal object _GetRegisteredEntity(object entity) { // TODO: check what is faster: by identity or by ref var identityReader = _GetIdentityReader(entity.GetType()); var identityKey = identityReader.GetIdentityKey(entity); if (identityKey == null) // if we don't have an entitykey here, it means that the entity has no PK return entity; // even var registeredEntityTrack = CurrentTransactionEntities.FindByIdentity(identityKey) ?? AllTrackedEntities.FindByIdentity(identityKey); if (registeredEntityTrack != null) return registeredEntityTrack.Entity; return null; } //internal object GetRegisteredEntityByKey(IdentityKey identityKey) //{ // return EntityMap[identityKey]; //} /// <summary> /// Registers an entity in a watch state /// </summary> /// <param name="entity"></param> /// <returns></returns> [DBLinqExtended] internal object _GetOrRegisterEntity(object entity) { var identityReader = _GetIdentityReader(entity.GetType()); var identityKey = identityReader.GetIdentityKey(entity); SetEntitySetsQueries(entity); SetEntityRefQueries(entity); // if we have no identity, we can't track it if (identityKey == null) return entity; // try to find an already registered entity and return it var registeredEntityTrack = CurrentTransactionEntities.FindByIdentity(identityKey) ?? AllTrackedEntities.FindByIdentity(identityKey); if (registeredEntityTrack != null) return registeredEntityTrack.Entity; // otherwise, register and return AllTrackedEntities.RegisterToWatch(entity, identityKey); return entity; } readonly IDataMapper DataMapper = ObjectFactory.Get<IDataMapper>(); private void SetEntityRefQueries(object entity) { if (!this.deferredLoadingEnabled) return; // BUG: This is ignoring External Mappings from XmlMappingSource. Type thisType = entity.GetType(); IEnumerable<MetaAssociation> associationList = Mapping.GetMetaType(entity.GetType()).Associations.Where(a => a.IsForeignKey); foreach (MetaAssociation association in associationList) { //example of entityRef:Order.Employee var memberData = association.ThisMember; Type otherTableType = association.OtherType.Type; ParameterExpression p = Expression.Parameter(otherTableType, "other"); var otherTable = GetTable(otherTableType); //ie:EmployeeTerritories.EmployeeID var foreignKeys = memberData.Association.ThisKey; BinaryExpression predicate = null; var otherPKs = memberData.Association.OtherKey; IEnumerator<MetaDataMember> otherPKEnumerator = otherPKs.GetEnumerator(); if (otherPKs.Count != foreignKeys.Count) throw new InvalidOperationException("Foreign keys don't match ThisKey"); foreach (MetaDataMember key in foreignKeys) { otherPKEnumerator.MoveNext(); var thisForeignKeyProperty = (PropertyInfo)key.Member; object thisForeignKeyValue = thisForeignKeyProperty.GetValue(entity, null); if (thisForeignKeyValue != null) { BinaryExpression keyPredicate; if (!(thisForeignKeyProperty.PropertyType.IsNullable())) { keyPredicate = Expression.Equal(Expression.MakeMemberAccess(p, otherPKEnumerator.Current.Member), Expression.Constant(thisForeignKeyValue)); } else { var ValueProperty = thisForeignKeyProperty.PropertyType.GetProperty("Value"); keyPredicate = Expression.Equal(Expression.MakeMemberAccess(p, otherPKEnumerator.Current.Member), Expression.Constant(ValueProperty.GetValue(thisForeignKeyValue, null))); } if (predicate == null) predicate = keyPredicate; else predicate = Expression.And(predicate, keyPredicate); } } IEnumerable query = null; if (predicate != null) { query = GetOtherTableQuery(predicate, p, otherTableType, otherTable) as IEnumerable; //it would be interesting surround the above query with a .Take(1) expression for performance. } // If no separate Storage is specified, use the member directly MemberInfo storage = memberData.StorageMember; if (storage == null) storage = memberData.Member; // Check that the storage is a field or a writable property if (!(storage is FieldInfo) && !(storage is PropertyInfo && ((PropertyInfo)storage).CanWrite)) { throw new InvalidOperationException(String.Format( "Member {0}.{1} is not a field nor a writable property", storage.DeclaringType, storage.Name)); } Type storageType = storage.GetMemberType(); object entityRefValue = null; if (query != null) entityRefValue = Activator.CreateInstance(storageType, query); else entityRefValue = Activator.CreateInstance(storageType); storage.SetMemberValue(entity, entityRefValue); } } /// <summary> /// This method is executed when the entity is being registered. Each EntitySet property has a internal query that can be set using the EntitySet.SetSource method. /// Here we set the query source of each EntitySetProperty /// </summary> /// <param name="entity"></param> private void SetEntitySetsQueries(object entity) { if (!this.deferredLoadingEnabled) return; // BUG: This is ignoring External Mappings from XmlMappingSource. IEnumerable<MetaAssociation> associationList = Mapping.GetMetaType(entity.GetType()).Associations.Where(a => !a.IsForeignKey); if (associationList.Any()) { foreach (MetaAssociation association in associationList) { //example of entitySet: Employee.EmployeeTerritories var memberData = association.ThisMember; Type otherTableType = association.OtherType.Type; ParameterExpression p = Expression.Parameter(otherTableType, "other"); //other table:EmployeeTerritories var otherTable = GetTable(otherTableType); var otherKeys = memberData.Association.OtherKey; var thisKeys = memberData.Association.ThisKey; if (otherKeys.Count != thisKeys.Count) throw new InvalidOperationException("This keys don't match OtherKey"); BinaryExpression predicate = null; IEnumerator<MetaDataMember> thisKeyEnumerator = thisKeys.GetEnumerator(); foreach (MetaDataMember otherKey in otherKeys) { thisKeyEnumerator.MoveNext(); //other table member:EmployeeTerritories.EmployeeID var otherTableMember = (PropertyInfo)otherKey.Member; BinaryExpression keyPredicate; if (!(otherTableMember.PropertyType.IsNullable())) { keyPredicate = Expression.Equal(Expression.MakeMemberAccess(p, otherTableMember), Expression.Constant(thisKeyEnumerator.Current.Member.GetMemberValue(entity))); } else { var ValueProperty = otherTableMember.PropertyType.GetProperty("Value"); keyPredicate = Expression.Equal(Expression.MakeMemberAccess( Expression.MakeMemberAccess(p, otherTableMember), ValueProperty), Expression.Constant(thisKeyEnumerator.Current.Member.GetMemberValue(entity))); } if (predicate == null) predicate = keyPredicate; else predicate = Expression.And(predicate, keyPredicate); } var query = GetOtherTableQuery(predicate, p, otherTableType, otherTable); var entitySetValue = memberData.Member.GetMemberValue(entity); if (entitySetValue == null) { entitySetValue = Activator.CreateInstance(memberData.Member.GetMemberType()); memberData.Member.SetMemberValue(entity, entitySetValue); } var hasLoadedOrAssignedValues = entitySetValue.GetType().GetProperty("HasLoadedOrAssignedValues"); if ((bool)hasLoadedOrAssignedValues.GetValue(entitySetValue, null)) continue; var setSourceMethod = entitySetValue.GetType().GetMethod("SetSource"); setSourceMethod.Invoke(entitySetValue, new[] { query }); //employee.EmployeeTerritories.SetSource(Table[EmployeesTerritories].Where(other=>other.employeeID="WARTH")) } } } private static MethodInfo _WhereMethod = typeof(Queryable).GetMethods().First(m => m.Name == "Where"); internal object GetOtherTableQuery(Expression predicate, ParameterExpression parameter, Type otherTableType, IQueryable otherTable) { //predicate: other.EmployeeID== "WARTH" Expression lambdaPredicate = Expression.Lambda(predicate, parameter); //lambdaPredicate: other=>other.EmployeeID== "WARTH" Expression call = Expression.Call(_WhereMethod.MakeGenericMethod(otherTableType), otherTable.Expression, lambdaPredicate); //Table[EmployeesTerritories].Where(other=>other.employeeID="WARTH") return otherTable.Provider.CreateQuery(call); } #endregion #region Insert/Update/Delete management /// <summary> /// Registers an entity for insert /// </summary> /// <param name="entity"></param> internal void RegisterInsert(object entity) { CurrentTransactionEntities.RegisterToInsert(entity); } private void DoRegisterUpdate(object entity) { if (entity == null) throw new ArgumentNullException("entity"); if (!this.objectTrackingEnabled) return; var identityReader = _GetIdentityReader(entity.GetType()); var identityKey = identityReader.GetIdentityKey(entity); // if we have no key, we can not watch if (identityKey == null || identityKey.Keys.Count == 0) return; // register entity AllTrackedEntities.RegisterToWatch(entity, identityKey); } /// <summary> /// Registers an entity for update /// The entity will be updated only if some of its members have changed after the registration /// </summary> /// <param name="entity"></param> internal void RegisterUpdate(object entity) { DoRegisterUpdate(entity); MemberModificationHandler.Register(entity, Mapping); } /// <summary> /// Registers or re-registers an entity and clears its state /// </summary> /// <param name="entity"></param> /// <returns></returns> internal object Register(object entity) { if (! this.objectTrackingEnabled) return entity; var registeredEntity = _GetOrRegisterEntity(entity); // the fact of registering again clears the modified state, so we're... clear with that MemberModificationHandler.Register(registeredEntity, Mapping); return registeredEntity; } /// <summary> /// Registers an entity for update /// The entity will be updated only if some of its members have changed after the registration /// </summary> /// <param name="entity"></param> /// <param name="entityOriginalState"></param> internal void RegisterUpdate(object entity, object entityOriginalState) { if (!this.objectTrackingEnabled) return; DoRegisterUpdate(entity); MemberModificationHandler.Register(entity, entityOriginalState, Mapping); } /// <summary> /// Clears the current state, and marks the object as clean /// </summary> /// <param name="entity"></param> internal void RegisterUpdateAgain(object entity) { if (!this.objectTrackingEnabled) return; MemberModificationHandler.ClearModified(entity, Mapping); } /// <summary> /// Registers an entity for delete /// </summary> /// <param name="entity"></param> internal void RegisterDelete(object entity) { if (!this.objectTrackingEnabled) return; CurrentTransactionEntities.RegisterToDelete(entity); } /// <summary> /// Unregisters entity after deletion /// </summary> /// <param name="entity"></param> internal void UnregisterDelete(object entity) { if (!this.objectTrackingEnabled) return; CurrentTransactionEntities.RegisterDeleted(entity); } #endregion /// <summary> /// Changed object determine /// </summary> /// <returns>Lists of inserted, updated, deleted objects</returns> public ChangeSet GetChangeSet() { var inserts = new List<object>(); var updates = new List<object>(); var deletes = new List<object>(); foreach (var entityTrack in CurrentTransactionEntities.EnumerateAll() .Concat(AllTrackedEntities.EnumerateAll())) { switch (entityTrack.EntityState) { case EntityState.ToInsert: inserts.Add(entityTrack.Entity); break; case EntityState.ToWatch: if (MemberModificationHandler.IsModified(entityTrack.Entity, Mapping)) updates.Add(entityTrack.Entity); break; case EntityState.ToDelete: deletes.Add(entityTrack.Entity); break; default: throw new ArgumentOutOfRangeException(); } } return new ChangeSet(inserts, updates, deletes); } /// <summary> /// use ExecuteCommand to call raw SQL /// </summary> public int ExecuteCommand(string command, params object[] parameters) { var directQuery = QueryBuilder.GetDirectQuery(command, new QueryContext(this)); return QueryRunner.Execute(directQuery, parameters); } /// <summary> /// Execute raw SQL query and return object /// </summary> public IEnumerable<TResult> ExecuteQuery<TResult>(string query, params object[] parameters) where TResult : class, new() { if (query == null) throw new ArgumentNullException("query"); return CreateExecuteQueryEnumerable<TResult>(query, parameters); } private IEnumerable<TResult> CreateExecuteQueryEnumerable<TResult>(string query, object[] parameters) where TResult : class, new() { foreach (TResult result in ExecuteQuery(typeof(TResult), query, parameters)) yield return result; } public IEnumerable ExecuteQuery(Type elementType, string query, params object[] parameters) { if (elementType == null) throw new ArgumentNullException("elementType"); if (query == null) throw new ArgumentNullException("query"); var queryContext = new QueryContext(this); var directQuery = QueryBuilder.GetDirectQuery(query, queryContext); return QueryRunner.ExecuteSelect(elementType, directQuery, parameters); } /// <summary> /// Gets or sets the load options /// </summary> [DbLinqToDo] public DataLoadOptions LoadOptions { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public DbTransaction Transaction { get { return (DbTransaction) DatabaseContext.CurrentTransaction; } set { DatabaseContext.CurrentTransaction = value; } } /// <summary> /// Runs the given reader and returns columns. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="reader">The reader.</param> /// <returns></returns> public IEnumerable<TResult> Translate<TResult>(DbDataReader reader) { if (reader == null) throw new ArgumentNullException("reader"); return CreateTranslateIterator<TResult>(reader); } IEnumerable<TResult> CreateTranslateIterator<TResult>(DbDataReader reader) { foreach (TResult result in Translate(typeof(TResult), reader)) yield return result; } public IMultipleResults Translate(DbDataReader reader) { throw new NotImplementedException(); } public IEnumerable Translate(Type elementType, DbDataReader reader) { if (elementType == null) throw new ArgumentNullException("elementType"); if (reader == null) throw new ArgumentNullException("reader"); return QueryRunner.EnumerateResult(elementType, reader, this); } public void Dispose() { //connection closing should not be done here. //read: http://msdn2.microsoft.com/en-us/library/bb292288.aspx //We own the instance of MemberModificationHandler - we must unregister listeners of entities we attached to MemberModificationHandler.UnregisterAll(); } [DbLinqToDo] protected virtual void Dispose(bool disposing) { throw new NotImplementedException(); } /// <summary> /// Creates a IDbDataAdapter. Used internally by Vendors /// </summary> /// <returns></returns> internal IDbDataAdapter CreateDataAdapter() { return DatabaseContext.CreateDataAdapter(); } /// <summary> /// Sets a TextWriter where generated SQL commands are written /// </summary> public TextWriter Log { get; set; } /// <summary> /// Writes text on Log (if not null) /// Internal helper /// </summary> /// <param name="text"></param> internal void WriteLog(string text) { if (Log != null) Log.WriteLine(text); } /// <summary> /// Write an IDbCommand to Log (if non null) /// </summary> /// <param name="command"></param> internal void WriteLog(IDbCommand command) { if (Log != null) { Log.WriteLine(command.CommandText); foreach (IDbDataParameter parameter in command.Parameters) WriteLog(parameter); Log.Write("--"); Log.Write(" Context: {0}", Vendor.VendorName); Log.Write(" Model: {0}", Mapping.GetType().Name); Log.Write(" Build: {0}", Assembly.GetExecutingAssembly().GetName().Version); Log.WriteLine(); } } /// <summary> /// Writes and IDbDataParameter to Log (if non null) /// </summary> /// <param name="parameter"></param> internal void WriteLog(IDbDataParameter parameter) { if (Log != null) { // -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [2] // -- <name>: <direction> <type> (...) [<value>] Log.WriteLine("-- {0}: {1} {2} (Size = {3}; Prec = {4}; Scale = {5}) [{6}]", parameter.ParameterName, parameter.Direction, parameter.DbType, parameter.Size, parameter.Precision, parameter.Scale, parameter.Value); } } public bool ObjectTrackingEnabled { get { return this.objectTrackingEnabled; } set { if (this.currentTransactionEntities != null && value != this.objectTrackingEnabled) throw new InvalidOperationException("Data context options cannot be modified after results have been returned from a query."); this.objectTrackingEnabled = value; } } [DbLinqToDo] public int CommandTimeout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool DeferredLoadingEnabled { get { return this.deferredLoadingEnabled; } set { if (this.currentTransactionEntities != null && value != this.deferredLoadingEnabled) throw new InvalidOperationException("Data context options cannot be modified after results have been returned from a query."); this.deferredLoadingEnabled = value; } } [DbLinqToDo] public ChangeConflictCollection ChangeConflicts { get { throw new NotImplementedException(); } } [DbLinqToDo] public DbCommand GetCommand(IQueryable query) { DbCommand dbCommand = GetIDbCommand(query) as DbCommand; if (dbCommand == null) throw new InvalidOperationException(); return dbCommand; } [DBLinqExtended] public IDbCommand GetIDbCommand(IQueryable query) { if (query == null) throw new ArgumentNullException("query"); var qp = query.Provider as QueryProvider; if (qp == null) throw new InvalidOperationException(); if (qp.ExpressionChain.Expressions.Count == 0) qp.ExpressionChain.Expressions.Add(CreateDefaultQuery(query)); return qp.GetQuery(null).GetCommand().Command; } private Expression CreateDefaultQuery(IQueryable query) { // Manually create the expression tree for: IQueryable<TableType>.Select(e => e) var identityParameter = Expression.Parameter(query.ElementType, "e"); var identityBody = Expression.Lambda( typeof(Func<,>).MakeGenericType(query.ElementType, query.ElementType), identityParameter, new[] { identityParameter } ); return Expression.Call( typeof(Queryable), "Select", new[] { query.ElementType, query.ElementType }, query.Expression, Expression.Quote(identityBody) ); } [DbLinqToDo] public void Refresh(RefreshMode mode, IEnumerable entities) { throw new NotImplementedException(); } [DbLinqToDo] public void Refresh(RefreshMode mode, params object[] entities) { throw new NotImplementedException(); } [DbLinqToDo] public void Refresh(RefreshMode mode, object entity) { throw new NotImplementedException(); } [DbLinqToDo] public void DeleteDatabase() { throw new NotImplementedException(); } [DbLinqToDo] public void CreateDatabase() { throw new NotImplementedException(); } [DbLinqToDo] protected internal IQueryable<TResult> CreateMethodCallQuery<TResult>(object instance, MethodInfo methodInfo, params object[] parameters) { throw new NotImplementedException(); } [DbLinqToDo] protected internal void ExecuteDynamicDelete(object entity) { throw new NotImplementedException(); } [DbLinqToDo] protected internal void ExecuteDynamicInsert(object entity) { throw new NotImplementedException(); } [DbLinqToDo] protected internal void ExecuteDynamicUpdate(object entity) { throw new NotImplementedException(); } public DataMigrator GetDataMigrator() { return new DataMigrator(this); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.XSSF.UserModel.Extensions; using System.Collections.ObjectModel; using NPOI.SS; namespace NPOI.XSSF.Model { /** * Table of styles shared across all sheets in a workbook. * * @author ugo */ public class StylesTable : POIXMLDocumentPart { private SortedDictionary<short, String> numberFormats = new SortedDictionary<short, String>(); private bool[] usedNumberFormats = new bool[SpreadsheetVersion.EXCEL2007.MaxCellStyles]; private List<XSSFFont> fonts = new List<XSSFFont>(); private List<XSSFCellFill> fills = new List<XSSFCellFill>(); private List<XSSFCellBorder> borders = new List<XSSFCellBorder>(); private List<CT_Xf> styleXfs = new List<CT_Xf>(); private List<CT_Xf> xfs = new List<CT_Xf>(); private List<CT_Dxf> dxfs = new List<CT_Dxf>(); /** * The first style id available for use as a custom style */ public static int FIRST_CUSTOM_STYLE_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX + 1; // Is this right? Number formats (XSSFDataFormat) and cell styles (XSSFCellStyle) are different. What's up with the plus 1? private static int MAXIMUM_STYLE_ID = SpreadsheetVersion.EXCEL2007.MaxCellStyles; private static short FIRST_USER_DEFINED_NUMBER_FORMAT_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX; /** * Depending on the version of Excel, the maximum number of number formats in a workbook is between 200 and 250 * See https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 * POI defaults this limit to 250, but can be increased or decreased on a per-StylesTable basis with * {@link #setMaxNumberOfDataFormats(int)} if needed. */ private int MAXIMUM_NUMBER_OF_DATA_FORMATS = 250; /** * Get the upper limit on the number of data formats that has been set for the style table. * To get the current number of data formats in use, use {@link #getNumDataFormats()}. * * @return the maximum number of data formats allowed in the workbook */ public int MaxNumberOfDataFormats { get { return MAXIMUM_NUMBER_OF_DATA_FORMATS; } set { if (value < NumDataFormats) { if (value < 0) { throw new ArgumentException("Maximum Number of Data Formats must be greater than or equal to 0"); } else { throw new InvalidOperationException("Cannot set the maximum number of data formats less than the current quantity." + "Data formats must be explicitly removed (via StylesTable.removeNumberFormat) before the limit can be decreased."); } } MAXIMUM_NUMBER_OF_DATA_FORMATS = value; } } private StyleSheetDocument doc; private XSSFWorkbook workbook; private ThemesTable theme; /** * Create a new, empty StylesTable */ public StylesTable() : base() { doc = new StyleSheetDocument(); doc.AddNewStyleSheet(); // Initialization required in order to make the document Readable by MSExcel Initialize(); } internal StylesTable(PackagePart part) : base(part) { XmlDocument xmldoc = ConvertStreamToXml(part.GetInputStream()); ReadFrom(xmldoc); } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] public StylesTable(PackagePart part, PackageRelationship rel) : this(part) { } public void SetWorkbook(XSSFWorkbook wb) { this.workbook = wb; } public ThemesTable GetTheme() { return theme; } public void SetTheme(ThemesTable theme) { this.theme = theme; // Pass the themes table along to things which need to // know about it, but have already been Created by now foreach (XSSFFont font in fonts) { font.SetThemesTable(theme); } foreach (XSSFCellBorder border in borders) { border.SetThemesTable(theme); } } /** * If there isn't currently a {@link ThemesTable} for the * current Workbook, then creates one and sets it up. * After this, calls to {@link #getTheme()} won't give null */ public void EnsureThemesTable() { if (theme != null) return; theme = (ThemesTable)workbook.CreateRelationship(XSSFRelation.THEME, XSSFFactory.GetInstance()); } /** * Read this shared styles table from an XML file. * * @param is The input stream Containing the XML document. * @throws IOException if an error occurs while Reading. */ protected void ReadFrom(XmlDocument xmldoc) { try { doc = StyleSheetDocument.Parse(xmldoc, NamespaceManager); CT_Stylesheet styleSheet = doc.GetStyleSheet(); // Grab all the different bits we care about CT_NumFmts ctfmts = styleSheet.numFmts; if (ctfmts != null) { foreach (CT_NumFmt nfmt in ctfmts.numFmt) { short formatId = (short)nfmt.numFmtId; numberFormats.Add(formatId, nfmt.formatCode); } } CT_Fonts ctfonts = styleSheet.fonts; if (ctfonts != null) { int idx = 0; foreach (CT_Font font in ctfonts.font) { // Create the font and save it. Themes Table supplied later XSSFFont f = new XSSFFont(font, idx); fonts.Add(f); idx++; } } CT_Fills ctFills = styleSheet.fills; if (ctFills != null) { foreach (CT_Fill fill in ctFills.fill) { fills.Add(new XSSFCellFill(fill)); } } CT_Borders ctborders = styleSheet.borders; if (ctborders != null) { foreach (CT_Border border in ctborders.border) { borders.Add(new XSSFCellBorder(border)); } } CT_CellXfs cellXfs = styleSheet.cellXfs; if (cellXfs != null) xfs.AddRange(cellXfs.xf); CT_CellStyleXfs cellStyleXfs = styleSheet.cellStyleXfs; if (cellStyleXfs != null) styleXfs.AddRange(cellStyleXfs.xf); CT_Dxfs styleDxfs = styleSheet.dxfs; if (styleDxfs != null) dxfs.AddRange(styleDxfs.dxf); } catch (XmlException e) { throw new IOException(e.Message); } } // =========================================================== // Start of style related Getters and Setters // =========================================================== /** * Get number format string given its id * * @param idx number format id * @return number format code */ [Obsolete("deprecated POI 3.14-beta2. Use {@link #getNumberFormatAt(short)} instead.")] public String GetNumberFormatAt(int idx) { return GetNumberFormatAt((short)idx); } /** * Get number format string given its id * * @param fmtId number format id * @return number format code */ public String GetNumberFormatAt(short fmtId) { if (numberFormats.ContainsKey(fmtId)) return numberFormats[fmtId]; else return null; } private short GetNumberFormatId(String fmt) { // Find the key, and return that foreach (KeyValuePair<short, string> numFmt in numberFormats) { if (numFmt.Value.Equals(fmt)) { return numFmt.Key; } } throw new InvalidOperationException("Number format not in style table: " + fmt); } /** * Puts <code>fmt</code> in the numberFormats map if the format is not * already in the the number format style table. * Does nothing if <code>fmt</code> is already in number format style table. * * @param fmt the number format to add to number format style table * @return the index of <code>fmt</code> in the number format style table */ public int PutNumberFormat(String fmt) { // Check if number format already exists if (numberFormats.ContainsValue(fmt)) { try { return GetNumberFormatId(fmt); } catch (InvalidOperationException e) { throw new InvalidOperationException("Found the format, but couldn't figure out where - should never happen!"); } } if (numberFormats.Count >= MAXIMUM_NUMBER_OF_DATA_FORMATS) { throw new InvalidOperationException("The maximum number of Data Formats was exceeded. " + "You can define up to " + MAXIMUM_NUMBER_OF_DATA_FORMATS + " formats in a .xlsx Workbook."); } // Find a spare key, and add that short formatIndex; if (numberFormats.Count == 0) { formatIndex = FIRST_USER_DEFINED_NUMBER_FORMAT_ID; } else { // get next-available numberFormat index. // Assumption: gaps in number format ids are acceptable // to catch arithmetic overflow, nextKey's data type // must match numberFormat's key data type short nextKey = (short)(numberFormats.Last().Key + 1); if (nextKey < 0) { throw new InvalidOperationException( "Cowardly avoiding creating a number format with a negative id." + "This is probably due to arithmetic overflow."); } formatIndex = (short)Math.Max(nextKey, FIRST_USER_DEFINED_NUMBER_FORMAT_ID); } if (numberFormats.ContainsKey(formatIndex)) numberFormats[formatIndex] = fmt; else numberFormats.Add(formatIndex, fmt); return formatIndex; } /** * Add a number format with a specific ID into the numberFormats map. * If a format with the same ID already exists, overwrite the format code * with <code>fmt</code> * This may be used to override built-in number formats. * * @param index the number format ID * @param fmt the number format code */ public void PutNumberFormat(short index, String fmt) { if (numberFormats.ContainsKey(index)) numberFormats[index] = fmt; else numberFormats.Add(index, fmt); } /** * Remove a number format from the style table if it exists. * All cell styles with this number format will be modified to use the default number format. * * @param fmt the number format to remove * @return true if the number format was removed */ public bool RemoveNumberFormat(short index) { String fmt = numberFormats[index]; bool removed = numberFormats.Remove(index); //bool removed = (fmt != null); if (removed) { foreach (CT_Xf style in xfs) { if (style.numFmtIdSpecified && style.numFmtId == index) { style.applyNumberFormat = false; style.numFmtId = 0; style.numFmtIdSpecified = false;; } } } return removed; } /** * Remove a number format from the style table if it exists * All cell styles with this number format will be modified to use the default number format * * @param fmt the number format to remove * @return true if the number format was removed */ public bool RemoveNumberFormat(String fmt) { short id = GetNumberFormatId(fmt); return RemoveNumberFormat(id); } public XSSFFont GetFontAt(int idx) { return fonts[idx]; } /** * Records the given font in the font table. * Will re-use an existing font index if this * font matches another, EXCEPT if forced * registration is requested. * This allows people to create several fonts * then customise them later. * Note - End Users probably want to call * {@link XSSFFont#registerTo(StylesTable)} */ public int PutFont(XSSFFont font, bool forceRegistration) { int idx = -1; if (!forceRegistration) { idx = fonts.IndexOf(font); } if (idx != -1) { return idx; } idx = fonts.Count; fonts.Add(font); return idx; } public int PutFont(XSSFFont font) { return PutFont(font, false); } public XSSFCellStyle GetStyleAt(int idx) { int styleXfId = 0; if (xfs.Count == 0) //in case there is no default style return null; // 0 is the empty default if (xfs[idx].xfId > 0) { styleXfId = (int)xfs[idx].xfId; } return new XSSFCellStyle(idx, styleXfId, this, theme); } public int PutStyle(XSSFCellStyle style) { CT_Xf mainXF = style.GetCoreXf(); if (!xfs.Contains(mainXF)) { xfs.Add(mainXF); } return xfs.IndexOf(mainXF); } public XSSFCellBorder GetBorderAt(int idx) { return borders[idx]; } /// <summary> /// Adds a border to the border style table if it isn't already in the style table /// Does nothing if border is already in borders style table /// </summary> /// <param name="border">border to add</param> /// <returns>return the index of the added border</returns> public int PutBorder(XSSFCellBorder border) { int idx = borders.IndexOf(border); if (idx != -1) { return idx; } borders.Add(border); border.SetThemesTable(theme); return borders.Count - 1; } public XSSFCellFill GetFillAt(int idx) { return fills[idx]; } public ReadOnlyCollection<XSSFCellBorder> GetBorders() { return borders.AsReadOnly(); } public ReadOnlyCollection<XSSFCellFill> GetFills() { return fills.AsReadOnly(); } public ReadOnlyCollection<XSSFFont> GetFonts() { return fonts.AsReadOnly(); } public IDictionary<short, String> GetNumberFormats() { return numberFormats; } /// <summary> /// Adds a fill to the fill style table if it isn't already in the style table /// Does nothing if fill is already in fill style table /// </summary> /// <param name="fill">fill to add</param> /// <returns>return the index of the added fill</returns> public int PutFill(XSSFCellFill fill) { int idx = fills.IndexOf(fill); if (idx != -1) { return idx; } fills.Add(fill); return fills.Count - 1; } internal CT_Xf GetCellXfAt(int idx) { return xfs[idx]; } /// <summary> /// Adds a cell to the styles table. Does not check for duplicates /// </summary> /// <param name="cellXf">the cell to add to the styles table</param> /// <returns>return the added cell ID in the style table</returns> internal int PutCellXf(CT_Xf cellXf) { xfs.Add(cellXf); return xfs.Count; } internal void ReplaceCellXfAt(int idx, CT_Xf cellXf) { xfs[idx] = cellXf; } internal CT_Xf GetCellStyleXfAt(int idx) { if (idx < 0 || idx > styleXfs.Count) return null; return styleXfs[idx]; } /// <summary> /// Adds a cell style to the styles table.Does not check for duplicates. /// </summary> /// <param name="cellStyleXf">the cell style to add to the styles table</param> /// <returns>return the cell style ID in the style table</returns> internal int PutCellStyleXf(CT_Xf cellStyleXf) { styleXfs.Add(cellStyleXf); // TODO: check for duplicate return styleXfs.Count; } internal void ReplaceCellStyleXfAt(int idx, CT_Xf cellStyleXf) { styleXfs[idx] = cellStyleXf; } /** * get the size of cell styles */ public int NumCellStyles { get { // Each cell style has a unique xfs entry // Several might share the same styleXfs entry return xfs.Count; } } /** * @return number of data formats in the styles table */ public int NumDataFormats { get { return numberFormats.Count; } } /** * For unit testing only */ [Obsolete("deprecated POI 3.14 beta 2. Use {@link #getNumDataFormats()} instead.")] internal int NumberFormatSize { get { return numberFormats.Count; } } /** * For unit testing only */ internal int XfsSize { get { return xfs.Count; } } /** * For unit testing only */ internal int StyleXfsSize { get { return styleXfs.Count; } } /** * For unit testing only! */ internal CT_Stylesheet GetCTStylesheet() { return doc.GetStyleSheet(); } internal int DXfsSize { get { return dxfs.Count; } } /** * Write this table out as XML. * * @param out The stream to write to. * @throws IOException if an error occurs while writing. */ public void WriteTo(Stream out1) { // Work on the current one // Need to do this, as we don't handle // all the possible entries yet CT_Stylesheet styleSheet = doc.GetStyleSheet(); // Formats CT_NumFmts formats = new CT_NumFmts(); formats.count = (uint)numberFormats.Count; foreach (KeyValuePair<short, String > entry in numberFormats) { CT_NumFmt ctFmt = formats.AddNewNumFmt(); ctFmt.numFmtId = (uint)entry.Key; ctFmt.formatCode = entry.Value; } styleSheet.numFmts = formats; // Fonts CT_Fonts ctFonts = styleSheet.fonts; if (ctFonts == null) ctFonts = new CT_Fonts(); ctFonts.count = (uint)fonts.Count; if (ctFonts.count > 0) ctFonts.countSpecified = true; List<CT_Font> ctfnt = new List<CT_Font>(fonts.Count); foreach (XSSFFont f in fonts) ctfnt.Add(f.GetCTFont()); ctFonts.SetFontArray(ctfnt); styleSheet.fonts = (ctFonts); // Fills CT_Fills ctFills = styleSheet.fills; if (ctFills == null) { ctFills = new CT_Fills(); } ctFills.count = (uint)fills.Count; List<CT_Fill> ctf = new List<CT_Fill>(fills.Count); foreach (XSSFCellFill f in fills) ctf.Add( f.GetCTFill()); ctFills.SetFillArray(ctf); if (ctFills.count > 0) ctFills.countSpecified = true; styleSheet.fills = ctFills; // Borders CT_Borders ctBorders = styleSheet.borders; if (ctBorders == null) { ctBorders = new CT_Borders(); } ctBorders.count = (uint)borders.Count; List<CT_Border> ctb = new List<CT_Border>(borders.Count); foreach (XSSFCellBorder b in borders) ctb.Add(b.GetCTBorder()); ctBorders.SetBorderArray(ctb); styleSheet.borders = ctBorders; // Xfs if (xfs.Count > 0) { CT_CellXfs ctXfs = styleSheet.cellXfs; if (ctXfs == null) { ctXfs = new CT_CellXfs(); } ctXfs.count = (uint)xfs.Count; if (ctXfs.count > 0) ctXfs.countSpecified = true; ctXfs.xf = xfs; styleSheet.cellXfs = (ctXfs); } // Style xfs if (styleXfs.Count > 0) { CT_CellStyleXfs ctSXfs = styleSheet.cellStyleXfs; if (ctSXfs == null) { ctSXfs = new CT_CellStyleXfs(); } ctSXfs.count = (uint)(styleXfs.Count); if (ctSXfs.count > 0) ctSXfs.countSpecified = true; ctSXfs.xf = styleXfs; styleSheet.cellStyleXfs = (ctSXfs); } // Style dxfs if (dxfs.Count > 0) { CT_Dxfs ctDxfs = styleSheet.dxfs; if (ctDxfs == null) { ctDxfs = new CT_Dxfs(); } ctDxfs.count = (uint)dxfs.Count; if (ctDxfs.count > 0) ctDxfs.countSpecified = true; ctDxfs.dxf = dxfs; styleSheet.dxfs = (ctDxfs); } // Save doc.Save(out1); } protected internal override void Commit() { PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); WriteTo(out1); out1.Close(); } private void Initialize() { //CT_Font ctFont = CreateDefaultFont(); XSSFFont xssfFont = CreateDefaultFont(); fonts.Add(xssfFont); CT_Fill[] ctFill = CreateDefaultFills(); fills.Add(new XSSFCellFill(ctFill[0])); fills.Add(new XSSFCellFill(ctFill[1])); CT_Border ctBorder = CreateDefaultBorder(); borders.Add(new XSSFCellBorder(ctBorder)); CT_Xf styleXf = CreateDefaultXf(); styleXfs.Add(styleXf); CT_Xf xf = CreateDefaultXf(); xf.xfId = 0; xfs.Add(xf); } private static CT_Xf CreateDefaultXf() { CT_Xf ctXf = new CT_Xf(); ctXf.numFmtId = 0; ctXf.fontId = 0; ctXf.fillId = 0; ctXf.borderId = 0; return ctXf; } private static CT_Border CreateDefaultBorder() { CT_Border ctBorder = new CT_Border(); ctBorder.AddNewLeft(); ctBorder.AddNewRight(); ctBorder.AddNewTop(); ctBorder.AddNewBottom(); ctBorder.AddNewDiagonal(); return ctBorder; } private static CT_Fill[] CreateDefaultFills() { CT_Fill[] ctFill = new CT_Fill[] { new CT_Fill(), new CT_Fill() }; ctFill[0].AddNewPatternFill().patternType = (ST_PatternType.none); ctFill[1].AddNewPatternFill().patternType = (ST_PatternType.darkGray); return ctFill; } private static XSSFFont CreateDefaultFont() { CT_Font ctFont = new CT_Font(); XSSFFont xssfFont = new XSSFFont(ctFont, 0); xssfFont.FontHeightInPoints = (XSSFFont.DEFAULT_FONT_SIZE); xssfFont.Color = (XSSFFont.DEFAULT_FONT_COLOR);//SetTheme xssfFont.FontName = (XSSFFont.DEFAULT_FONT_NAME); xssfFont.SetFamily(FontFamily.SWISS); xssfFont.SetScheme(FontScheme.MINOR); return xssfFont; } public CT_Dxf GetDxfAt(int idx) { return dxfs[idx]; } /// <summary> /// Adds a Dxf to the style table Does not check for duplicates. /// </summary> /// <param name="dxf">the Dxf to add</param> /// <returns>added dxf ID in the style table</returns> public int PutDxf(CT_Dxf dxf) { this.dxfs.Add(dxf); return this.dxfs.Count; } /** * Create a cell style in this style table. * Note - End users probably want to call {@link XSSFWorkbook#createCellStyle()} * rather than working with the styles table directly. */ public XSSFCellStyle CreateCellStyle() { if (NumCellStyles > MAXIMUM_STYLE_ID) throw new InvalidOperationException("The maximum number of Cell Styles was exceeded. " + "You can define up to " + MAXIMUM_STYLE_ID + " style in a .xlsx Workbook"); int xfSize = styleXfs.Count; CT_Xf ctXf = new CT_Xf(); ctXf.numFmtId = 0; ctXf.fontId = 0; ctXf.fillId = 0; ctXf.borderId = 0; ctXf.xfId = 0; int indexXf = PutCellXf(ctXf); return new XSSFCellStyle(indexXf - 1, xfSize - 1, this, theme); } /** * Finds a font that matches the one with the supplied attributes */ [Obsolete("deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead.")] public XSSFFont FindFont(short boldWeight, short color, short fontHeight, String name, bool italic, bool strikeout, FontSuperScript typeOffset,FontUnderlineType underline) { foreach (XSSFFont font in fonts) { if ((font.Boldweight == boldWeight) && font.Color == color && font.FontHeight == fontHeight && font.FontName.Equals(name) && font.IsItalic == italic && font.IsStrikeout == strikeout && font.TypeOffset == typeOffset && font.Underline == underline) { return font; } } return null; } /** * Finds a font that matches the one with the supplied attributes */ public XSSFFont FindFont(bool bold, short color, short fontHeight, String name, bool italic, bool strikeout, FontSuperScript typeOffset, FontUnderlineType underline) { foreach (XSSFFont font in fonts) { if ((font.IsBold == bold) && font.Color == color && font.FontHeight == fontHeight && font.FontName.Equals(name) && font.IsItalic == italic && font.IsStrikeout == strikeout && font.TypeOffset == typeOffset && font.Underline == underline) { return font; } } return null; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Framework.Utils; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Framework.Tests.Visual.UserInterface { public class TestSceneContextMenu : ManualInputManagerTestScene { protected override Container<Drawable> Content => contextMenuContainer ?? base.Content; private readonly TestContextMenuContainer contextMenuContainer; public TestSceneContextMenu() { base.Content.Add(contextMenuContainer = new TestContextMenuContainer { RelativeSizeAxes = Axes.Both }); } [SetUp] public void Setup() => Schedule(Clear); [Test] public void TestMenuOpenedOnClick() { Drawable box = null; addBoxStep(b => box = b, 1); clickBoxStep(() => box); assertMenuState(true); } [Test] public void TestMenuClosedOnClickOutside() { Drawable box = null; addBoxStep(b => box = b, 1); clickBoxStep(() => box); clickOutsideStep(); assertMenuState(false); } [Test] public void TestMenuTransferredToNewTarget() { Drawable box1 = null; Drawable box2 = null; addBoxStep(b => { box1 = b.With(d => { d.X = -100; d.Colour = Color4.Green; }); }, 1); addBoxStep(b => { box2 = b.With(d => { d.X = 100; d.Colour = Color4.Red; }); }, 1); clickBoxStep(() => box1); clickBoxStep(() => box2); assertMenuState(true); assertMenuInCentre(() => box2); } [Test] public void TestMenuHiddenWhenTargetHidden() { Drawable box = null; addBoxStep(b => box = b, 1); clickBoxStep(() => box); AddStep("hide box", () => box.Hide()); assertMenuState(false); } [Test] public void TestMenuTracksMovement() { Drawable box = null; addBoxStep(b => box = b, 1); clickBoxStep(() => box); AddStep("move box", () => box.X += 100); assertMenuInCentre(() => box); } [TestCase(Anchor.TopLeft)] [TestCase(Anchor.TopCentre)] [TestCase(Anchor.TopRight)] [TestCase(Anchor.CentreLeft)] [TestCase(Anchor.CentreRight)] [TestCase(Anchor.BottomLeft)] [TestCase(Anchor.BottomCentre)] [TestCase(Anchor.BottomRight)] public void TestMenuOnScreenWhenTargetPartlyOffScreen(Anchor anchor) { Drawable box = null; addBoxStep(b => box = b, 5); clickBoxStep(() => box); AddStep($"move box to {anchor.ToString()}", () => { box.Anchor = anchor; box.X -= 5; box.Y -= 5; }); assertMenuOnScreen(true); } [TestCase(Anchor.TopLeft)] [TestCase(Anchor.TopCentre)] [TestCase(Anchor.TopRight)] [TestCase(Anchor.CentreLeft)] [TestCase(Anchor.CentreRight)] [TestCase(Anchor.BottomLeft)] [TestCase(Anchor.BottomCentre)] [TestCase(Anchor.BottomRight)] public void TestMenuNotOnScreenWhenTargetSignificantlyOffScreen(Anchor anchor) { Drawable box = null; addBoxStep(b => box = b, 5); clickBoxStep(() => box); AddStep($"move box to {anchor.ToString()}", () => { box.Anchor = anchor; if (anchor.HasFlagFast(Anchor.x0)) box.X -= contextMenuContainer.CurrentMenu.DrawWidth + 10; else if (anchor.HasFlagFast(Anchor.x2)) box.X += 10; if (anchor.HasFlagFast(Anchor.y0)) box.Y -= contextMenuContainer.CurrentMenu.DrawHeight + 10; else if (anchor.HasFlagFast(Anchor.y2)) box.Y += 10; }); assertMenuOnScreen(false); } [Test] public void TestReturnNullInNestedDrawableOpensParentMenu() { Drawable box2 = null; addBoxStep(_ => { }, 2); addBoxStep(b => box2 = b, null); clickBoxStep(() => box2); assertMenuState(true); assertMenuItems(2); } [Test] public void TestReturnEmptyInNestedDrawableBlocksMenuOpening() { Drawable box2 = null; addBoxStep(_ => { }, 2); addBoxStep(b => box2 = b); clickBoxStep(() => box2); assertMenuState(false); } private void clickBoxStep(Func<Drawable> getBoxFunc) { AddStep("right-click box", () => { InputManager.MoveMouseTo(getBoxFunc()); InputManager.Click(MouseButton.Right); }); } private void clickOutsideStep() { AddStep("click outside", () => { InputManager.MoveMouseTo(InputManager.ScreenSpaceDrawQuad.TopLeft); InputManager.Click(MouseButton.Right); }); } private void addBoxStep(Action<Drawable> boxFunc, int actionCount) => addBoxStep(boxFunc, Enumerable.Repeat(new Action(() => { }), actionCount).ToArray()); private void addBoxStep(Action<Drawable> boxFunc, params Action[] actions) { AddStep("add box", () => { var box = new BoxWithContextMenu(actions) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200), }; Add(box); boxFunc?.Invoke(box); }); } private void assertMenuState(bool opened) => AddAssert($"menu {(opened ? "opened" : "closed")}", () => (contextMenuContainer.CurrentMenu?.State == MenuState.Open) == opened); private void assertMenuInCentre(Func<Drawable> getBoxFunc) => AddAssert("menu in centre of box", () => Precision.AlmostEquals(contextMenuContainer.CurrentMenu.ScreenSpaceDrawQuad.TopLeft, getBoxFunc().ScreenSpaceDrawQuad.Centre)); private void assertMenuOnScreen(bool expected) => AddAssert($"menu {(expected ? "on" : "off")} screen", () => { var inputQuad = InputManager.ScreenSpaceDrawQuad; var menuQuad = contextMenuContainer.CurrentMenu.ScreenSpaceDrawQuad; bool result = inputQuad.Contains(menuQuad.TopLeft + new Vector2(1, 1)) && inputQuad.Contains(menuQuad.TopRight + new Vector2(-1, 1)) && inputQuad.Contains(menuQuad.BottomLeft + new Vector2(1, -1)) && inputQuad.Contains(menuQuad.BottomRight + new Vector2(-1, -1)); return result == expected; }); private void assertMenuItems(int expectedCount) => AddAssert($"menu contains {expectedCount} item(s)", () => contextMenuContainer.CurrentMenu.Items.Count == expectedCount); private class BoxWithContextMenu : Box, IHasContextMenu { private readonly Action[] actions; public BoxWithContextMenu(Action[] actions) { this.actions = actions; } public MenuItem[] ContextMenuItems => actions?.Select((a, i) => new MenuItem($"Item {i}", a)).ToArray(); } private class TestContextMenuContainer : BasicContextMenuContainer { public Menu CurrentMenu { get; private set; } protected override Menu CreateMenu() => CurrentMenu = base.CreateMenu(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Int32 ** ** ** Purpose: A representation of a 32 bit 2's complement ** integer. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [Microsoft.Zelig.Internals.WellKnownType( "System_Int32" )] [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<Int32>, IEquatable<Int32> { public const int MaxValue = 0x7FFFFFFF; public const int MinValue = unchecked( (int)0x80000000 ); internal int m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is Int32) { return CompareTo( (Int32)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeInt32" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( int value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is Int32)) { return false; } return Equals( (Int32)obj ); } public bool Equals( Int32 obj ) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } public override String ToString() { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( char formatChar ) { return Number.FormatInt32( m_value, formatChar, NumberFormatInfo.CurrentInfo ); } public String ToString( String format ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatInt32( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatInt32( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } public static int Parse( String s ) { return Number.ParseInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } public static int Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt32( s, style, NumberFormatInfo.CurrentInfo ); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse( String s , IFormatProvider provider ) { return Number.ParseInt32( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static int Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseInt32( s, style, NumberFormatInfo.GetInstance( provider ) ); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse( String s , out Int32 result ) { return Number.TryParseInt32( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // public static bool TryParse( String s , NumberStyles style , IFormatProvider provider , out Int32 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseInt32( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.Int32; } /// <internalonly/> bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// <internalonly/> char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// <internalonly/> sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// <internalonly/> byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// <internalonly/> short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// <internalonly/> ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// <internalonly/> int IConvertible.ToInt32( IFormatProvider provider ) { return m_value; } /// <internalonly/> uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// <internalonly/> long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// <internalonly/> ulong IConvertible.ToUInt64( IFormatProvider provider ) { return Convert.ToUInt64( m_value ); } /// <internalonly/> float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// <internalonly/> double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// <internalonly/> Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// <internalonly/> DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Int32", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// <internalonly/> Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Collections; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class wraps BuildEventArgs and used for sending BuildEventArgs across the node boundary /// </summary> internal class NodeLoggingEvent { // Enumeration of logging event types, this is used to recreate the correct type on deserialization private enum LoggingEventType { CustomEvent = 0, BuildErrorEvent = 1, BuildFinishedEvent = 2, BuildMessageEvent = 3, BuildStartedEvent = 4, BuildWarningEvent = 5, ProjectFinishedEvent = 6, ProjectStartedEvent = 7, TargetStartedEvent = 8, TargetFinishedEvent = 9, TaskStartedEvent = 10, TaskFinishedEvent = 11, TaskCommandLineEvent = 12 } #region Constructors /// <summary> /// This new constructor is required for custom serialization /// </summary> internal NodeLoggingEvent() { } /// <summary> /// Create an instance of this class wrapping given BuildEventArgs /// </summary> internal NodeLoggingEvent(BuildEventArgs eventToLog) { this.e = eventToLog; } #endregion #region Properties /// <summary> /// The BuildEventArgs wrapped by this class /// </summary> internal BuildEventArgs BuildEvent { get { return this.e; } } /// <summary> /// The ID of the central logger to which this event should be forwarded. By default /// all regular non-forwarded events are sent to all loggers registered on the parent. /// </summary> virtual internal int LoggerId { get { return 0; } } #endregion #region CustomSerializationToStream /// <summary> /// Converts a BuildEventArg into its associated enumeration Id. /// Any event which is a derrived event not in the predefined list will be /// considered a custom event and use .net serialization /// </summary> private LoggingEventType GetLoggingEventId(BuildEventArgs eventArg) { Type eventType = eventArg.GetType(); if (eventType == typeof(BuildMessageEventArgs)) { return LoggingEventType.BuildMessageEvent; } else if (eventType == typeof(TaskCommandLineEventArgs)) { return LoggingEventType.TaskCommandLineEvent; } else if (eventType == typeof(ProjectFinishedEventArgs)) { return LoggingEventType.ProjectFinishedEvent; } else if (eventType == typeof(ProjectStartedEventArgs)) { return LoggingEventType.ProjectStartedEvent; } else if (eventType == typeof(TargetStartedEventArgs)) { return LoggingEventType.TargetStartedEvent; } else if (eventType == typeof(TargetFinishedEventArgs)) { return LoggingEventType.TargetFinishedEvent; } else if (eventType == typeof(TaskStartedEventArgs)) { return LoggingEventType.TaskStartedEvent; } else if (eventType == typeof(TaskFinishedEventArgs)) { return LoggingEventType.TaskFinishedEvent; } else if (eventType == typeof(BuildFinishedEventArgs)) { return LoggingEventType.BuildFinishedEvent; } else if (eventType == typeof(BuildStartedEventArgs)) { return LoggingEventType.BuildStartedEvent; } else if (eventType == typeof(BuildWarningEventArgs)) { return LoggingEventType.BuildWarningEvent; } if (eventType == typeof(BuildErrorEventArgs)) { return LoggingEventType.BuildErrorEvent; } else { return LoggingEventType.CustomEvent; } } /// <summary> /// Takes in a id (LoggingEventType as an int) and creates the correct specific logging class /// </summary> private BuildEventArgs GetBuildEventArgFromId(LoggingEventType id) { switch (id) { case LoggingEventType.BuildErrorEvent: return new BuildErrorEventArgs(null, null, null, -1, -1, -1, -1, null, null, null); case LoggingEventType.BuildFinishedEvent: return new BuildFinishedEventArgs(null, null, false); case LoggingEventType.BuildMessageEvent: return new BuildMessageEventArgs(null, null, null, MessageImportance.Normal); case LoggingEventType.BuildStartedEvent: return new BuildStartedEventArgs(null, null); case LoggingEventType.BuildWarningEvent: return new BuildWarningEventArgs(null, null, null, -1, -1, -1, -1,null,null,null); case LoggingEventType.ProjectFinishedEvent: return new ProjectFinishedEventArgs(null, null, null, false); case LoggingEventType.ProjectStartedEvent: return new ProjectStartedEventArgs(-1, null, null, null, null, null, null, null); case LoggingEventType.TargetStartedEvent: return new TargetStartedEventArgs(null, null, null, null, null); case LoggingEventType.TargetFinishedEvent: return new TargetFinishedEventArgs(null, null, null, null, null, false); case LoggingEventType.TaskStartedEvent: return new TaskStartedEventArgs(null, null, null, null, null); case LoggingEventType.TaskFinishedEvent: return new TaskFinishedEventArgs(null, null, null, null, null, false); case LoggingEventType.TaskCommandLineEvent: return new TaskCommandLineEventArgs(null, null, MessageImportance.Normal); default: ErrorUtilities.VerifyThrow(false, "Should not get to the default of getBuildEventArgFromId ID:" + id); return null; } } internal virtual void WriteToStream(BinaryWriter writer, Hashtable loggingTypeCache) { LoggingEventType id = GetLoggingEventId(e); writer.Write((byte)id); if (id != LoggingEventType.CustomEvent) { if (!loggingTypeCache.ContainsKey(id)) { Type eventType = e.GetType(); MethodInfo methodInfo = eventType.GetMethod("WriteToStream", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod); loggingTypeCache.Add(id, methodInfo); } if (loggingTypeCache[id] != null) { ((MethodInfo)loggingTypeCache[id]).Invoke(e, new object[] { writer }); } else { // The customer serialization methods are not availiable, default to .net serialization writer.BaseStream.Position = writer.BaseStream.Position - 1; writer.Write((byte)0); binaryFormatter.Serialize(writer.BaseStream, e); } } else { writer.Write(e.GetType().Assembly.Location); binaryFormatter.Serialize(writer.BaseStream, e); } } internal virtual void CreateFromStream(BinaryReader reader, Hashtable loggingTypeCache) { LoggingEventType id = (LoggingEventType)reader.ReadByte(); if (LoggingEventType.CustomEvent != id) { e = GetBuildEventArgFromId(id); if (!loggingTypeCache.Contains(id)) { Type eventType = e.GetType(); MethodInfo methodInfo = eventType.GetMethod("CreateFromStream", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod); loggingTypeCache.Add(id, methodInfo); } int packetVersion = (Environment.Version.Major * 10) + Environment.Version.Minor; ((MethodInfo)loggingTypeCache[id]).Invoke(e, new object[] { reader, packetVersion }); } else { string fileLocation = reader.ReadString(); bool resolveAssembly = false; lock (lockObject) { if (customEventsLoaded == null) { customEventsLoaded = new Hashtable(StringComparer.OrdinalIgnoreCase); resolveAssembly = true; } else { if (!customEventsLoaded.Contains(fileLocation)) { resolveAssembly = true; } } // If we are to resolve the assembly add it to the list of assemblies resolved if (resolveAssembly) { customEventsLoaded.Add(fileLocation, null); } } if (resolveAssembly) { resolver = new TaskEngineAssemblyResolver(); resolver.InstallHandler(); resolver.Initialize(fileLocation); } try { e = (BuildEventArgs)binaryFormatter.Deserialize(reader.BaseStream); } finally { if (resolveAssembly) { resolver.RemoveHandler(); resolver = null; } } } } #endregion #region Data // The actual event wrapped by this container class private BuildEventArgs e; // Just need one of each per app domain private static BinaryFormatter binaryFormatter = new BinaryFormatter(); private TaskEngineAssemblyResolver resolver; private static Hashtable customEventsLoaded; private static object lockObject = new object(); #endregion } /// <summary> /// This class is used to associate wrapped BuildEventArgs with a loggerId which /// identifies which central logger this event should be delivered to. /// </summary> internal class NodeLoggingEventWithLoggerId : NodeLoggingEvent { #region Constructors internal NodeLoggingEventWithLoggerId() { } /// <summary> /// Create a wrapper for a given event associated with a particular loggerId /// </summary> internal NodeLoggingEventWithLoggerId(BuildEventArgs eventToLog, int loggerId) :base(eventToLog) { this.loggerId = loggerId; } #endregion #region Properties /// <summary> /// The ID of the central logger to which this event should be forwarded /// </summary> internal override int LoggerId { get { return loggerId; } } #endregion #region CustomSerializationToStream internal override void WriteToStream(BinaryWriter writer, Hashtable loggingTypeCache) { base.WriteToStream(writer, loggingTypeCache); writer.Write((Int32)loggerId); } internal override void CreateFromStream(BinaryReader reader, Hashtable loggingTypeCache) { base.CreateFromStream(reader, loggingTypeCache); loggerId = reader.ReadInt32(); } #endregion #region Data // The id of the central logger to which this event should be forwarded private int loggerId; #endregion } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using System.Linq.Expressions; using FluentMigrator.Exceptions; using FluentMigrator.Runner; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Tests.Integration; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; namespace FluentMigrator.Tests.Unit { [TestFixture] public class TaskExecutorTests : IntegrationTestBase { private Mock<IMigrationRunner> _migrationRunner; [SetUp] public void SetUp() { _migrationRunner = new Mock<IMigrationRunner>(); } private void Verify(Expression<Action<IMigrationRunner>> func, string task, long version, int steps) { _migrationRunner.Setup(func).Verifiable(); var processor = new Mock<IMigrationProcessor>(); const string profile = "Debug"; var dataSet = new DataSet(); dataSet.Tables.Add(new DataTable()); processor.Setup(x => x.ReadTableData(null, It.IsAny<string>())).Returns(dataSet); var stopWatch = new Mock<IStopWatch>(); var services = ServiceCollectionExtensions.CreateServices() .WithProcessor(processor) .AddSingleton(stopWatch.Object) .AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader(IntegrationTestOptions.SqlServer2008.ConnectionString)) .AddScoped(_ => _migrationRunner.Object) .Configure<SelectingProcessorAccessorOptions>(opt => opt.ProcessorId = "sqlserver2008") .Configure<RunnerOptions>( opt => { opt.Task = task; opt.Version = version; opt.Steps = steps; opt.Profile = profile; }) .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3") .AddScoped<TaskExecutor, FakeTaskExecutor>(); var serviceProvider = services .BuildServiceProvider(); var taskExecutor = serviceProvider.GetRequiredService<TaskExecutor>(); taskExecutor.Execute(); _migrationRunner.VerifyAll(); } [Test] public void InvalidProviderNameShouldThrowArgumentException() { var services = ServiceCollectionExtensions.CreateServices() .ConfigureRunner(r => r.AddSQLite()) .AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader(IntegrationTestOptions.SqlServer2008.ConnectionString)) .Configure<SelectingProcessorAccessorOptions>(opt => opt.ProcessorId = "sqlWRONG") .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations") .AddScoped<TaskExecutor, FakeTaskExecutor>(); var serviceProvider = services .BuildServiceProvider(); var taskExecutor = serviceProvider.GetRequiredService<TaskExecutor>(); Assert.Throws<ProcessorFactoryNotFoundException>(() => taskExecutor.Execute()); } [Test] public void ShouldCallMigrateDownIfSpecified() { Verify(x => x.MigrateDown(It.Is<long>(c => c == 20)), "migrate:down", 20, 0); } [Test] public void ShouldCallMigrateUpByDefault() { Verify(x => x.MigrateUp(), null, 0, 0); Verify(x => x.MigrateUp(), "", 0, 0); } [Test] public void ShouldCallMigrateUpIfSpecified() { Verify(x => x.MigrateUp(), "migrate", 0, 0); Verify(x => x.MigrateUp(), "migrate:up", 0, 0); } [Test] public void ShouldCallMigrateUpWithVersionIfSpecified() { Verify(x => x.MigrateUp(It.Is<long>(c => c == 1)), "migrate", 1, 0); Verify(x => x.MigrateUp(It.Is<long>(c => c == 1)), "migrate:up", 1, 0); } [Test] public void ShouldCallRollbackIfSpecified() { Verify(x => x.Rollback(It.Is<int>(c => c == 2)), "rollback", 0, 2); } [Test] public void ShouldCallRollbackIfSpecifiedAndDefaultTo1Step() { Verify(x => x.Rollback(It.Is<int>(c => c == 1)), "rollback", 0, 0); } [Test] public void ShouldCallValidateVersionOrder() { Verify(x => x.ValidateVersionOrder(), "validateversionorder", 0, 0); } [Test] public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnNoTask() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "", 0); } [Test] public void ShouldCallHasMigrationsToApplyUpWithVersionOnNoTask() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "", 1); } [Test] public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnMigrate() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "migrate", 0); } [Test] public void ShouldCallHasMigrationsToApplyUpWithVersionOnMigrate() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "migrate", 1); } [Test] public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnMigrateUp() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "migrate:up", 0); } [Test] public void ShouldCallHasMigrationsToApplyUpWithVersionOnMigrateUp() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "migrate:up", 1); } [Test] public void ShouldCallHasMigrationsToApplyRollbackOnRollback() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyRollback(), "rollback", 0); } [Test] public void ShouldCallHasMigrationsToApplyRollbackOnRollbackAll() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyRollback(), "rollback:all", 0); } [Test] public void ShouldCallHasMigrationsToApplyDownOnRollbackToVersion() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyDown(It.Is<long>(version => version == 2)), "rollback:toversion", 2); } [Test] public void ShouldCallHasMigrationsToApplyDownOnMigrateDown() { VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyDown(It.Is<long>(version => version == 2)), "migrate:down", 2); } private void VerifyHasMigrationsToApply(Expression<Func<IMigrationRunner, bool>> func, string task, long version) { _migrationRunner.Setup(func).Verifiable(); var processor = new Mock<IMigrationProcessor>(); var dataSet = new DataSet(); dataSet.Tables.Add(new DataTable()); processor.Setup(x => x.ReadTableData(null, It.IsAny<string>())).Returns(dataSet); _migrationRunner.SetupGet(x => x.Processor).Returns(processor.Object); var services = ServiceCollectionExtensions.CreateServices() .WithProcessor(processor) .AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader(IntegrationTestOptions.SqlServer2008.ConnectionString)) .AddScoped(_ => _migrationRunner.Object) .Configure<SelectingProcessorAccessorOptions>(opt => opt.ProcessorId = "sqlserver2008") .Configure<RunnerOptions>( opt => { opt.Task = task; opt.Version = version; }) .WithMigrationsIn("FluentMigrator.Tests.Integration.Migrations") .AddScoped<TaskExecutor, FakeTaskExecutor>(); var serviceProvider = services .BuildServiceProvider(); var taskExecutor = serviceProvider.GetRequiredService<TaskExecutor>(); taskExecutor.HasMigrationsToApply(); _migrationRunner.Verify(func, Times.Once()); } internal class FakeTaskExecutor : TaskExecutor { public FakeTaskExecutor( [NotNull] ILogger<TaskExecutor> logger, [NotNull] IAssemblySource assemblySource, [NotNull] IOptions<RunnerOptions> runnerOptions, [NotNull] IServiceProvider serviceProvider) : base(logger, assemblySource, runnerOptions, serviceProvider) { } } } }
using System; using System.Collections.ObjectModel; using Sce.Atf.VectorMath; namespace Sce.Atf.Controls.CurveEditing { /// <summary> /// Evaluator for hermite curve. /// A curve evaluator calculates y-coordinates from x-coordinates using appropriate interpolation for a curve</summary> public class HermiteCurveEvaluator : ICurveEvaluator { #region ctor /// <summary> /// Default constructor</summary> /// <param name="curve">Curve for which evaluator created</param> public HermiteCurveEvaluator(ICurve curve) { if (curve == null) throw new ArgumentNullException("curve"); m_curve = curve; Reset(); } #endregion #region public methods /// <summary> /// Resets the curve. Call this whenever curve changes.</summary> public void Reset() { m_lastP1 = null; m_points = m_curve.ControlPoints; } /// <summary> /// Evaluates point on curve</summary> /// <param name="x">X-coordinate for which y-coordinate is calculated</param> /// <returns>Y-coordinate on curve corresponding to given x-coordinate</returns> /// <remarks>Calculates y-coordinate from x-coordinate using appropriate interpolation for a curve</remarks> public float Evaluate(float x) { if (m_points.Count == 0) return 0.0f; if (m_points.Count == 1) return m_points[0].Y; IControlPoint firstPt = m_points[0]; IControlPoint lastPt = m_points[m_points.Count - 1]; float offset = 0.0f; if (x < firstPt.X) // pre-infiniy. { CurveLoopTypes loop = m_curve.PreInfinity; if (loop == CurveLoopTypes.Constant) { return firstPt.Y; } if (loop == CurveLoopTypes.Linear) { return (firstPt.Y - ((firstPt.TangentIn.Y / firstPt.TangentIn.X) * (firstPt.X - x))); } float firstX = firstPt.X; float lastX = lastPt.X; float rangeX = lastX - firstX; float numcycle = (int)((firstX - x) / rangeX); float nx = ((firstX - x) - numcycle * rangeX); if (loop == CurveLoopTypes.Cycle) { x = lastX-nx; } else if(loop == CurveLoopTypes.CycleWithOffset) { x = lastX-nx; offset = -((numcycle+1) * (lastPt.Y - firstPt.Y)); } else if (loop == CurveLoopTypes.Oscillate) { x = (((int)numcycle & 1) == 0) ? firstX + nx : lastX - nx; } } else if (x > lastPt.X) // post-infinity. { CurveLoopTypes loop = m_curve.PostInfinity; if (loop == CurveLoopTypes.Constant) { return lastPt.Y; } if (loop == CurveLoopTypes.Linear) { return (lastPt.Y + ((lastPt.TangentOut.Y / lastPt.TangentOut.X) * ( x-lastPt.X))); } float firstX = firstPt.X; float lastX = lastPt.X; float rangeX = lastX - firstX; float numcycle = (int)((x-lastX) / rangeX); float nx = (x - lastX) - numcycle * rangeX; if (loop == CurveLoopTypes.Cycle) { x = firstX + nx; } else if(loop == CurveLoopTypes.CycleWithOffset) { x = firstX + nx; offset = (numcycle+1) * (lastPt.Y - firstPt.Y); } else if (loop == CurveLoopTypes.Oscillate) { x = (((int)numcycle & 1)==0)? lastX - nx : firstX + nx; } } // correct any potential floating point error. x = MathUtil.Clamp(x, firstPt.X, lastPt.X); bool exactMatch; int index = FindIndex(x, out exactMatch); if (exactMatch) return m_points[index].Y + offset; IControlPoint p1 = m_points[index]; IControlPoint p2 = m_points[index + 1]; if (p1.TangentOut.X == 0 && p1.TangentOut.Y == 0) {// step return p1.Y + offset; } else if (p1.TangentOut.X == float.MaxValue && p1.TangentOut.Y == float.MaxValue) {// step-next return p2.Y + offset; } else {// hermite eval. if (m_lastP1 != p1) { // compute coeff. ComputeHermiteCoeff(p1, p2, m_coeff); m_lastP1 = p1; } return CubicPolyEval(p1.X, x, m_coeff) + offset; } } #endregion #region private helper methods /// <summary> /// Finds control points at x coordinate or prior to it</summary> private int FindIndex(float x, out bool exactMatch) { exactMatch = false; int low = 0; int high = m_points.Count - 1; do { int mid = (low + high) >> 1; if (x < m_points[mid].X) { high = mid - 1; } else if (x > m_points[mid].X) { low = mid + 1; } else { exactMatch = true; return mid; } } while (low <= high); return high; } private float CubicPolyEval(float x0, float x, float[] Coeff) { float t = x - x0; // usually t = (x-x0)/(x1-x0), but coeff has extra 1/(x1-x0) factor. return (t * (t * (t * Coeff[0] + Coeff[1]) + Coeff[2]) + Coeff[3]); } private void ComputeHermiteCoeff(IControlPoint p1, IControlPoint p2, float[] Coeff) { Vec2F t1 = new Vec2F(p1.TangentOut.X, p1.TangentOut.Y); Vec2F t2 = new Vec2F(p2.TangentIn.X, p2.TangentIn.Y); float m1 = 0.0f; if (t1.X != 0.0f) { m1 = t1.Y / t1.X; } float m2 = 0.0f; if (t2.X != 0.0f) { m2 = t2.Y / t2.X; } float dx = p2.X - p1.X; float dy = p2.Y - p1.Y; float length = 1.0f / (dx * dx); float d1 = dx * m1; float d2 = dx * m2; Coeff[0] = (d1 + d2 - dy - dy) * length / dx; Coeff[1] = (dy + dy + dy - d1 - d1 - d2) * length; Coeff[2] = m1; Coeff[3] = p1.Y; } #endregion #region private fields private readonly ICurve m_curve; private readonly float[] m_coeff = new float[4]; private ReadOnlyCollection<IControlPoint> m_points; private IControlPoint m_lastP1; #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DriveItemChildrenCollectionRequest. /// </summary> public partial class DriveItemChildrenCollectionRequest : BaseRequest, IDriveItemChildrenCollectionRequest { /// <summary> /// Constructs a new DriveItemChildrenCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DriveItemChildrenCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified DriveItem to the collection via POST. /// </summary> /// <param name="driveItem">The DriveItem to add.</param> /// <returns>The created DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem) { return this.AddAsync(driveItem, CancellationToken.None); } /// <summary> /// Adds the specified DriveItem to the collection via POST. /// </summary> /// <param name="driveItem">The DriveItem to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DriveItem.</returns> public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<DriveItem>(driveItem, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IDriveItemChildrenCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IDriveItemChildrenCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<DriveItemChildrenCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Expand(Expression<Func<DriveItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Select(Expression<Func<DriveItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IDriveItemChildrenCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
#if UNITY_PURCHASING #if UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_TVOS // You must obfuscate your secrets using Window > Unity IAP > Receipt Validation Obfuscator // before receipt validation will compile in this sample. //#define RECEIPT_VALIDATION #endif //#define DELAY_CONFIRMATION // Returns PurchaseProcessingResult.Pending from ProcessPurchase, then calls ConfirmPendingPurchase after a delay //#define USE_PAYOUTS // Enables use of PayoutDefinitions to specify what the player should receive when a product is purchased //#define INTERCEPT_PROMOTIONAL_PURCHASES // Enables intercepting promotional purchases that come directly from the Apple App Store //#define SUBSCRIPTION_MANAGER //Enables subscription product manager for AppleStore and GooglePlay store using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Purchasing; using UnityEngine.Store; // UnityChannel #if RECEIPT_VALIDATION using UnityEngine.Purchasing.Security; #endif /// <summary> /// An example of Unity IAP functionality. /// To use with your account, configure the product ids (AddProduct). /// </summary> [AddComponentMenu("Unity IAP/Demo")] public class IAPDemo : MonoBehaviour, IStoreListener { // Unity IAP objects private IStoreController m_Controller; private IAppleExtensions m_AppleExtensions; private IMoolahExtension m_MoolahExtensions; private ISamsungAppsExtensions m_SamsungExtensions; private IMicrosoftExtensions m_MicrosoftExtensions; private IUnityChannelExtensions m_UnityChannelExtensions; private ITransactionHistoryExtensions m_TransactionHistoryExtensions; #if SUBSCRIPTION_MANAGER private IGooglePlayStoreExtensions m_GooglePlayStoreExtensions; #endif #pragma warning disable 0414 private bool m_IsGooglePlayStoreSelected; #pragma warning restore 0414 private bool m_IsSamsungAppsStoreSelected; private bool m_IsCloudMoolahStoreSelected; private bool m_IsUnityChannelSelected; private string m_LastTransactionID; private bool m_IsLoggedIn; private UnityChannelLoginHandler unityChannelLoginHandler; // Helper for interfacing with UnityChannel API private bool m_FetchReceiptPayloadOnPurchase = false; private bool m_PurchaseInProgress; private Dictionary<string, IAPDemoProductUI> m_ProductUIs = new Dictionary<string, IAPDemoProductUI>(); public GameObject productUITemplate; public RectTransform contentRect; public Button restoreButton; public Button loginButton; public Button validateButton; public Text versionText; #if RECEIPT_VALIDATION private CrossPlatformValidator validator; #endif /// <summary> /// This will be called when Unity IAP has finished initialising. /// </summary> public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { m_Controller = controller; m_AppleExtensions = extensions.GetExtension<IAppleExtensions>(); m_SamsungExtensions = extensions.GetExtension<ISamsungAppsExtensions>(); m_MoolahExtensions = extensions.GetExtension<IMoolahExtension>(); m_MicrosoftExtensions = extensions.GetExtension<IMicrosoftExtensions>(); m_UnityChannelExtensions = extensions.GetExtension<IUnityChannelExtensions>(); m_TransactionHistoryExtensions = extensions.GetExtension<ITransactionHistoryExtensions>(); #if SUBSCRIPTION_MANAGER m_GooglePlayStoreExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>(); #endif InitUI(controller.products.all); // On Apple platforms we need to handle deferred purchases caused by Apple's Ask to Buy feature. // On non-Apple platforms this will have no effect; OnDeferred will never be called. m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred); #if SUBSCRIPTION_MANAGER Dictionary<string, string> introductory_info_dict = m_AppleExtensions.GetIntroductoryPriceDictionary(); #endif // This extension function returns a dictionary of the products' skuDetails from GooglePlay Store // Key is product Id (Sku), value is the skuDetails json string //Dictionary<string, string> google_play_store_product_SKUDetails_json = m_GooglePlayStoreExtensions.GetProductJSONDictionary(); Debug.Log("Available items:"); foreach (var item in controller.products.all) { if (item.availableToPurchase) { Debug.Log(string.Join(" - ", new[] { item.metadata.localizedTitle, item.metadata.localizedDescription, item.metadata.isoCurrencyCode, item.metadata.localizedPrice.ToString(), item.metadata.localizedPriceString, item.transactionID, item.receipt })); #if INTERCEPT_PROMOTIONAL_PURCHASES // Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show); #endif #if SUBSCRIPTION_MANAGER // this is the usage of SubscriptionManager class if (item.receipt != null) { if (item.definition.type == ProductType.Subscription) { if (checkIfProductIsAvailableForSubscriptionManager(item.receipt)) { string intro_json = (introductory_info_dict == null || !introductory_info_dict.ContainsKey(item.definition.storeSpecificId)) ? null : introductory_info_dict[item.definition.storeSpecificId]; SubscriptionManager p = new SubscriptionManager(item, intro_json); SubscriptionInfo info = p.getSubscriptionInfo(); Debug.Log("product id is: " + info.getProductId()); Debug.Log("purchase date is: " + info.getPurchaseDate()); Debug.Log("subscription next billing date is: " + info.getExpireDate()); Debug.Log("is subscribed? " + info.isSubscribed().ToString()); Debug.Log("is expired? " + info.isExpired().ToString()); Debug.Log("is cancelled? " + info.isCancelled()); Debug.Log("product is in free trial peroid? " + info.isFreeTrial()); Debug.Log("product is auto renewing? " + info.isAutoRenewing()); Debug.Log("subscription remaining valid time until next billing date is: " + info.getRemainingTime()); Debug.Log("is this product in introductory price period? " + info.isIntroductoryPricePeriod()); Debug.Log("the product introductory localized price is: " + info.getIntroductoryPrice()); Debug.Log("the product introductory price period is: " + info.getIntroductoryPricePeriod()); Debug.Log("the number of product introductory price period cycles is: " + info.getIntroductoryPricePeriodCycles()); } else { Debug.Log("This product is not available for SubscriptionManager class, only products that are purchase by 1.19+ SDK can use this class."); } } else { Debug.Log("the product is not a subscription product"); } } else { Debug.Log("the product should have a valid receipt"); } #endif } } // Populate the product menu now that we have Products AddProductUIs(m_Controller.products.all); LogProductDefinitions(); } #if SUBSCRIPTION_MANAGER private bool checkIfProductIsAvailableForSubscriptionManager(string receipt) { var receipt_wrapper = (Dictionary<string, object>)MiniJson.JsonDecode(receipt); if (!receipt_wrapper.ContainsKey("Store") || !receipt_wrapper.ContainsKey("Payload")) { Debug.Log("The product receipt does not contain enough information"); return false; } var store = (string)receipt_wrapper ["Store"]; var payload = (string)receipt_wrapper ["Payload"]; if (payload != null ) { switch (store) { case GooglePlay.Name: { var payload_wrapper = (Dictionary<string, object>)MiniJson.JsonDecode(payload); if (!payload_wrapper.ContainsKey("json")) { Debug.Log("The product receipt does not contain enough information, the 'json' field is missing"); return false; } var original_json_payload_wrapper = (Dictionary<string, object>)MiniJson.JsonDecode((string)payload_wrapper["json"]); if (original_json_payload_wrapper == null || !original_json_payload_wrapper.ContainsKey("developerPayload")) { Debug.Log("The product receipt does not contain enough information, the 'developerPayload' field is missing"); return false; } var developerPayloadJSON = (string)original_json_payload_wrapper["developerPayload"]; var developerPayload_wrapper = (Dictionary<string, object>)MiniJson.JsonDecode(developerPayloadJSON); if (developerPayload_wrapper == null || !developerPayload_wrapper.ContainsKey("is_free_trial") || !developerPayload_wrapper.ContainsKey("has_introductory_price_trial")) { Debug.Log("The product receipt does not contain enough information, the product is not purchased using 1.19 or later"); return false; } return true; } case AppleAppStore.Name: case AmazonApps.Name: case MacAppStore.Name: { return true; } default: { return false; } } } return false; } #endif /// <summary> /// This will be called when a purchase completes. /// </summary> public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e) { Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id); Debug.Log("Receipt: " + e.purchasedProduct.receipt); m_LastTransactionID = e.purchasedProduct.transactionID; m_PurchaseInProgress = false; // Decode the UnityChannelPurchaseReceipt, extracting the gameOrderId if (m_IsUnityChannelSelected) { var unifiedReceipt = JsonUtility.FromJson<UnifiedReceipt>(e.purchasedProduct.receipt); if (unifiedReceipt != null && !string.IsNullOrEmpty(unifiedReceipt.Payload)) { var purchaseReceipt = JsonUtility.FromJson<UnityChannelPurchaseReceipt>(unifiedReceipt.Payload); Debug.LogFormat( "UnityChannel receipt: storeSpecificId = {0}, transactionId = {1}, orderQueryToken = {2}", purchaseReceipt.storeSpecificId, purchaseReceipt.transactionId, purchaseReceipt.orderQueryToken); } } #if RECEIPT_VALIDATION // Local validation is available for GooglePlay, Apple, and UnityChannel stores if (m_IsGooglePlayStoreSelected || (m_IsUnityChannelSelected && m_FetchReceiptPayloadOnPurchase) || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.tvOS) { try { var result = validator.Validate(e.purchasedProduct.receipt); Debug.Log("Receipt is valid. Contents:"); foreach (IPurchaseReceipt productReceipt in result) { Debug.Log(productReceipt.productID); Debug.Log(productReceipt.purchaseDate); Debug.Log(productReceipt.transactionID); GooglePlayReceipt google = productReceipt as GooglePlayReceipt; if (null != google) { Debug.Log(google.purchaseState); Debug.Log(google.purchaseToken); } UnityChannelReceipt unityChannel = productReceipt as UnityChannelReceipt; if (null != unityChannel) { Debug.Log(unityChannel.productID); Debug.Log(unityChannel.purchaseDate); Debug.Log(unityChannel.transactionID); } AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt; if (null != apple) { Debug.Log(apple.originalTransactionIdentifier); Debug.Log(apple.subscriptionExpirationDate); Debug.Log(apple.cancellationDate); Debug.Log(apple.quantity); } // For improved security, consider comparing the signed // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data // embedded in the signed receipt objects to the data which the game is using // to make this purchase. } } catch (IAPSecurityException ex) { Debug.Log("Invalid receipt, not unlocking content. " + ex); return PurchaseProcessingResult.Complete; } } #endif // Unlock content from purchases here. #if USE_PAYOUTS if (e.purchasedProduct.definition.payouts != null) { Debug.Log("Purchase complete, paying out based on defined payouts"); foreach (var payout in e.purchasedProduct.definition.payouts) { Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data)); } } #endif // Indicate if we have handled this purchase. // PurchaseProcessingResult.Complete: ProcessPurchase will not be called // with this product again, until next purchase. // PurchaseProcessingResult.Pending: ProcessPurchase will be called // again with this product at next app launch. Later, call // m_Controller.ConfirmPendingPurchase(Product) to complete handling // this purchase. Use to transactionally save purchases to a cloud // game service. #if DELAY_CONFIRMATION StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct)); return PurchaseProcessingResult.Pending; #else UpdateProductUI(e.purchasedProduct); return PurchaseProcessingResult.Complete; #endif } #if DELAY_CONFIRMATION private HashSet<string> m_PendingProducts = new HashSet<string>(); private IEnumerator ConfirmPendingPurchaseAfterDelay(Product p) { m_PendingProducts.Add(p.definition.id); Debug.Log("Delaying confirmation of " + p.definition.id + " for 5 seconds."); var end = Time.time + 5f; while (Time.time < end) { yield return null; var remaining = Mathf.CeilToInt (end - Time.time); UpdateProductPendingUI (p, remaining); } Debug.Log("Confirming purchase of " + p.definition.id); m_Controller.ConfirmPendingPurchase(p); m_PendingProducts.Remove(p.definition.id); UpdateProductUI (p); } #endif /// <summary> /// This will be called if an attempted purchase fails. /// </summary> public void OnPurchaseFailed(Product item, PurchaseFailureReason r) { Debug.Log("Purchase failed: " + item.definition.id); Debug.Log(r); // Detailed debugging information Debug.Log("Store specific error code: " + m_TransactionHistoryExtensions.GetLastStoreSpecificPurchaseErrorCode()); if (m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription() != null) { Debug.Log("Purchase failure description message: " + m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription().message); } if (m_IsUnityChannelSelected) { var extra = m_UnityChannelExtensions.GetLastPurchaseError(); var purchaseError = JsonUtility.FromJson<UnityChannelPurchaseError>(extra); if (purchaseError != null && purchaseError.purchaseInfo != null) { // Additional information about purchase failure. var purchaseInfo = purchaseError.purchaseInfo; Debug.LogFormat( "UnityChannel purchaseInfo: productCode = {0}, gameOrderId = {1}, orderQueryToken = {2}", purchaseInfo.productCode, purchaseInfo.gameOrderId, purchaseInfo.orderQueryToken); } // Determine if the user already owns this item and that it can be added to // their inventory, if not already present. #if UNITY_5_6_OR_NEWER if (r == PurchaseFailureReason.DuplicateTransaction) { // Unlock `item` in inventory if not already present. Debug.Log("Duplicate transaction detected, unlock this item"); } #else // Building using Unity strictly less than 5.6; e.g 5.3-5.5. // In Unity 5.3 the enum PurchaseFailureReason.DuplicateTransaction // may not be available (is available in 5.6 ... specifically // 5.5.1p1+, 5.4.4p2+) and can be substituted with this call. if (r == PurchaseFailureReason.Unknown) { if (purchaseError != null && purchaseError.error != null && purchaseError.error.Equals("DuplicateTransaction")) { // Unlock `item` in inventory if not already present. Debug.Log("Duplicate transaction detected, unlock this item"); } } #endif } m_PurchaseInProgress = false; } public void OnInitializeFailed(InitializationFailureReason error) { Debug.Log("Billing failed to initialize!"); switch (error) { case InitializationFailureReason.AppNotKnown: Debug.LogError("Is your App correctly uploaded on the relevant publisher console?"); break; case InitializationFailureReason.PurchasingUnavailable: // Ask the user if billing is disabled in device settings. Debug.Log("Billing disabled!"); break; case InitializationFailureReason.NoProductsAvailable: // Developer configuration error; check product metadata. Debug.Log("No products available for purchase!"); break; } } [Serializable] public class UnityChannelPurchaseError { public string error; public UnityChannelPurchaseInfo purchaseInfo; } [Serializable] public class UnityChannelPurchaseInfo { public string productCode; // Corresponds to storeSpecificId public string gameOrderId; // Corresponds to transactionId public string orderQueryToken; } public void Awake() { var module = StandardPurchasingModule.Instance(); // The FakeStore supports: no-ui (always succeeding), basic ui (purchase pass/fail), and // developer ui (initialization, purchase, failure code setting). These correspond to // the FakeStoreUIMode Enum values passed into StandardPurchasingModule.useFakeStoreUIMode. module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser; var builder = ConfigurationBuilder.Instance(module); // Set this to true to enable the Microsoft IAP simulator for local testing. builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = false; m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.GooglePlay; // CloudMoolah Configuration setings // All games must set the configuration. the configuration need to apply on the CloudMoolah Portal. // CloudMoolah APP Key builder.Configure<IMoolahConfiguration>().appKey = "d93f4564c41d463ed3d3cd207594ee1b"; // CloudMoolah Hash Key builder.Configure<IMoolahConfiguration>().hashKey = "cc"; // This enables the CloudMoolah test mode for local testing. // You would remove this, or set to CloudMoolahMode.Production, before building your release package. builder.Configure<IMoolahConfiguration>().SetMode(CloudMoolahMode.AlwaysSucceed); // This records whether we are using Cloud Moolah IAP. // Cloud Moolah requires logging in to access your Digital Wallet, so: // A) IAPDemo (this) displays the Cloud Moolah GUI button for Cloud Moolah m_IsCloudMoolahStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.CloudMoolah; // UnityChannel, provides access to Xiaomi MiPay. // Products are required to be set in the IAP Catalog window. The file "MiProductCatalog.prop" // is required to be generated into the project's // Assets/Plugins/Android/assets folder, based off the contents of the // IAP Catalog window, for MiPay. m_IsUnityChannelSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.XiaomiMiPay; // UnityChannel supports receipt validation through a backend fetch. builder.Configure<IUnityChannelConfiguration>().fetchReceiptPayloadOnPurchase = m_FetchReceiptPayloadOnPurchase; // Define our products. // Either use the Unity IAP Catalog, or manually use the ConfigurationBuilder.AddProduct API. // Use IDs from both the Unity IAP Catalog and hardcoded IDs via the ConfigurationBuilder.AddProduct API. // Use the products defined in the IAP Catalog GUI. // E.g. Menu: "Window" > "Unity IAP" > "IAP Catalog", then add products, then click "App Store Export". var catalog = ProductCatalog.LoadDefaultCatalog(); foreach (var product in catalog.allValidProducts) { if (product.allStoreIDs.Count > 0) { var ids = new IDs(); foreach (var storeID in product.allStoreIDs) { ids.Add(storeID.id, storeID.store); } builder.AddProduct(product.id, product.type, ids); } else { builder.AddProduct(product.id, product.type); } } // In this case our products have the same identifier across all the App stores, // except on the Mac App store where product IDs cannot be reused across both Mac and // iOS stores. // So on the Mac App store our products have different identifiers, // and we tell Unity IAP this by using the IDs class. builder.AddProduct("100.gold.coins", ProductType.Consumable, new IDs { {"com.unity3d.unityiap.unityiapdemo.100goldcoins.7", MacAppStore.Name}, {"000000596586", TizenStore.Name}, {"com.ff", MoolahAppStore.Name}, {"100.gold.coins", AmazonApps.Name} } #if USE_PAYOUTS , new PayoutDefinition(PayoutType.Currency, "gold", 100) #endif //USE_PAYOUTS ); builder.AddProduct("500.gold.coins", ProductType.Consumable, new IDs { {"com.unity3d.unityiap.unityiapdemo.500goldcoins.7", MacAppStore.Name}, {"000000596581", TizenStore.Name}, {"com.ee", MoolahAppStore.Name}, {"500.gold.coins", AmazonApps.Name}, } #if USE_PAYOUTS , new PayoutDefinition(PayoutType.Currency, "gold", 500) #endif //USE_PAYOUTS ); builder.AddProduct("sword", ProductType.NonConsumable, new IDs { {"com.unity3d.unityiap.unityiapdemo.sword.7", MacAppStore.Name}, {"000000596583", TizenStore.Name}, {"sword", AmazonApps.Name} } #if USE_PAYOUTS , new List<PayoutDefinition> { new PayoutDefinition(PayoutType.Item, "", 1, "item_id:76543"), new PayoutDefinition(PayoutType.Currency, "gold", 50) } #endif //USE_PAYOUTS ); #if SUBSCRIPTION_MANAGER // Auto-Renewing subscription builder.AddProduct("sub9", ProductType.Subscription, new IDs { {"sub9", MacAppStore.Name}, {"sub9", AmazonApps.Name} }); #endif // Write Amazon's JSON description of our products to storage when using Amazon's local sandbox. // This should be removed from a production build. //builder.Configure<IAmazonConfiguration>().WriteSandboxJSON(builder.products); // This enables simulated purchase success for Samsung IAP. // You would remove this, or set to SamsungAppsMode.Production, before building your release package. builder.Configure<ISamsungAppsConfiguration>().SetMode(SamsungAppsMode.AlwaysSucceed); // This records whether we are using Samsung IAP. Currently ISamsungAppsExtensions.RestoreTransactions // displays a blocking Android Activity, so: // A) Unity IAP does not automatically restore purchases on Samsung Galaxy Apps // B) IAPDemo (this) displays the "Restore" GUI button for Samsung Galaxy Apps m_IsSamsungAppsStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.SamsungApps; // This selects the GroupId that was created in the Tizen Store for this set of products // An empty or non-matching GroupId here will result in no products available for purchase builder.Configure<ITizenStoreConfiguration>().SetGroupId("100000085616"); #if INTERCEPT_PROMOTIONAL_PURCHASES // On iOS and tvOS we can intercept promotional purchases that come directly from the App Store. // On other platforms this will have no effect; OnPromotionalPurchase will never be called. builder.Configure<IAppleConfiguration>().SetApplePromotionalPurchaseInterceptorCallback(OnPromotionalPurchase); Debug.Log("Setting Apple promotional purchase interceptor callback"); #endif #if RECEIPT_VALIDATION string appIdentifier; #if UNITY_5_6_OR_NEWER appIdentifier = Application.identifier; #else appIdentifier = Application.bundleIdentifier; #endif validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), UnityChannelTangle.Data(), appIdentifier); #endif Action initializeUnityIap = () => { // Now we're ready to initialize Unity IAP. UnityPurchasing.Initialize(this, builder); }; bool needExternalLogin = m_IsUnityChannelSelected; if (!needExternalLogin) { initializeUnityIap(); } else { // Call UnityChannel initialize and (later) login asynchronously // UnityChannel configuration settings. Required for Xiaomi MiPay. // Collect this app configuration from the Unity Developer website at // [2017-04-17 PENDING - Contact support representative] // https://developer.cloud.unity3d.com/ providing your Xiaomi MiPay App // ID, App Key, and App Secret. This permits Unity to proxy from the // user's device into the MiPay system. // IMPORTANT PRE-BUILD STEP: For mandatory Chinese Government app auditing // and for MiPay testing, enable debug mode (test mode) // using the `AppInfo.debug = true;` when initializing Unity Channel. AppInfo unityChannelAppInfo = new AppInfo(); unityChannelAppInfo.appId = "abc123appId"; unityChannelAppInfo.appKey = "efg456appKey"; unityChannelAppInfo.clientId = "hij789clientId"; unityChannelAppInfo.clientKey = "klm012clientKey"; unityChannelAppInfo.debug = false; // Shared handler for Unity Channel initialization, here, and login, later unityChannelLoginHandler = new UnityChannelLoginHandler(); unityChannelLoginHandler.initializeFailedAction = (string message) => { Debug.LogError("Failed to initialize and login to UnityChannel: " + message); }; unityChannelLoginHandler.initializeSucceededAction = () => { initializeUnityIap(); }; StoreService.Initialize(unityChannelAppInfo, unityChannelLoginHandler); } } // For handling initialization and login of UnityChannel, returning control to our store after. class UnityChannelLoginHandler : ILoginListener { internal Action initializeSucceededAction; internal Action<string> initializeFailedAction; internal Action<UserInfo> loginSucceededAction; internal Action<string> loginFailedAction; public void OnInitialized() { initializeSucceededAction(); } public void OnInitializeFailed(string message) { initializeFailedAction(message); } public void OnLogin(UserInfo userInfo) { loginSucceededAction(userInfo); } public void OnLoginFailed(string message) { loginFailedAction(message); } } /// <summary> /// This will be called after a call to IAppleExtensions.RestoreTransactions(). /// </summary> private void OnTransactionsRestored(bool success) { Debug.Log("Transactions restored."); } /// <summary> /// iOS Specific. /// This is called as part of Apple's 'Ask to buy' functionality, /// when a purchase is requested by a minor and referred to a parent /// for approval. /// /// When the purchase is approved or rejected, the normal purchase events /// will fire. /// </summary> /// <param name="item">Item.</param> private void OnDeferred(Product item) { Debug.Log("Purchase deferred: " + item.definition.id); } #if INTERCEPT_PROMOTIONAL_PURCHASES private void OnPromotionalPurchase(Product item) { Debug.Log("Attempted promotional purchase: " + item.definition.id); // Promotional purchase has been detected. Handle this event by, e.g. presenting a parental gate. // Here, for demonstration purposes only, we will wait five seconds before continuing the purchase. StartCoroutine(ContinuePromotionalPurchases()); } private IEnumerator ContinuePromotionalPurchases() { Debug.Log("Continuing promotional purchases in 5 seconds"); yield return new WaitForSeconds(5); Debug.Log("Continuing promotional purchases now"); m_AppleExtensions.ContinuePromotionalPurchases (); // iOS and tvOS only; does nothing on Mac } #endif private void InitUI(IEnumerable<Product> items) { // Show Restore, Register, Login, and Validate buttons on supported platforms restoreButton.gameObject.SetActive(NeedRestoreButton()); loginButton.gameObject.SetActive(NeedLoginButton()); validateButton.gameObject.SetActive(NeedValidateButton()); ClearProductUIs(); restoreButton.onClick.AddListener(RestoreButtonClick); loginButton.onClick.AddListener(LoginButtonClick); validateButton.onClick.AddListener(ValidateButtonClick); versionText.text = "Unity version: " + Application.unityVersion + "\n" + "IAP version: " + StandardPurchasingModule.k_PackageVersion; } public void PurchaseButtonClick(string productID) { if (m_PurchaseInProgress == true) { Debug.Log("Please wait, purchase in progress"); return; } if (m_Controller == null) { Debug.LogError("Purchasing is not initialized"); return; } if (m_Controller.products.WithID(productID) == null) { Debug.LogError("No product has id " + productID); return; } // For platforms needing Login, games utilizing a connected backend // game server may wish to login. // Standalone games may not need to login. if (NeedLoginButton() && m_IsLoggedIn == false) { Debug.LogWarning("Purchase notifications will not be forwarded server-to-server. Login incomplete."); } // Don't need to draw our UI whilst a purchase is in progress. // This is not a requirement for IAP Applications but makes the demo // scene tidier whilst the fake purchase dialog is showing. m_PurchaseInProgress = true; m_Controller.InitiatePurchase(m_Controller.products.WithID(productID), "aDemoDeveloperPayload"); } public void RestoreButtonClick() { if (m_IsCloudMoolahStoreSelected) { if (m_IsLoggedIn == false) { Debug.LogError("CloudMoolah purchase restoration aborted. Login incomplete."); } else { // Restore abnornal transaction identifer, if Client don't receive transaction identifer. m_MoolahExtensions.RestoreTransactionID((RestoreTransactionIDState restoreTransactionIDState) => { Debug.Log("restoreTransactionIDState = " + restoreTransactionIDState.ToString()); bool success = restoreTransactionIDState != RestoreTransactionIDState.RestoreFailed && restoreTransactionIDState != RestoreTransactionIDState.NotKnown; OnTransactionsRestored(success); }); } } else if (m_IsSamsungAppsStoreSelected) { m_SamsungExtensions.RestoreTransactions(OnTransactionsRestored); } else if (Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM) { m_MicrosoftExtensions.RestoreTransactions(); } else { m_AppleExtensions.RestoreTransactions(OnTransactionsRestored); } } public void LoginButtonClick() { if (!m_IsUnityChannelSelected) { Debug.Log("Login is only required for the Xiaomi store"); return; } unityChannelLoginHandler.loginSucceededAction = (UserInfo userInfo) => { m_IsLoggedIn = true; Debug.LogFormat("Succeeded logging into UnityChannel. channel {0}, userId {1}, userLoginToken {2} ", userInfo.channel, userInfo.userId, userInfo.userLoginToken); }; unityChannelLoginHandler.loginFailedAction = (string message) => { m_IsLoggedIn = false; Debug.LogError("Failed logging into UnityChannel. " + message); }; StoreService.Login(unityChannelLoginHandler); } public void ValidateButtonClick() { // For local validation, see ProcessPurchase. if (!m_IsUnityChannelSelected) { Debug.Log("Remote purchase validation is only supported for the Xiaomi store"); return; } string txId = m_LastTransactionID; m_UnityChannelExtensions.ValidateReceipt(txId, (bool success, string signData, string signature) => { Debug.LogFormat("ValidateReceipt transactionId {0}, success {1}, signData {2}, signature {3}", txId, success, signData, signature); // May use signData and signature results to validate server-to-server }); } private void ClearProductUIs() { foreach (var productUIKVP in m_ProductUIs) { GameObject.Destroy(productUIKVP.Value.gameObject); } m_ProductUIs.Clear(); } private void AddProductUIs(Product[] products) { ClearProductUIs(); var templateRectTransform = productUITemplate.GetComponent<RectTransform>(); var height = templateRectTransform.rect.height; var currPos = templateRectTransform.localPosition; contentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, products.Length * height); foreach (var p in products) { var newProductUI = GameObject.Instantiate(productUITemplate.gameObject) as GameObject; newProductUI.transform.SetParent(productUITemplate.transform.parent, false); var rect = newProductUI.GetComponent<RectTransform>(); rect.localPosition = currPos; currPos += Vector3.down * height; newProductUI.SetActive(true); var productUIComponent = newProductUI.GetComponent<IAPDemoProductUI>(); productUIComponent.SetProduct(p, PurchaseButtonClick); m_ProductUIs[p.definition.id] = productUIComponent; } } private void UpdateProductUI(Product p) { if (m_ProductUIs.ContainsKey(p.definition.id)) { m_ProductUIs[p.definition.id].SetProduct(p, PurchaseButtonClick); } } private void UpdateProductPendingUI(Product p, int secondsRemaining) { if (m_ProductUIs.ContainsKey(p.definition.id)) { m_ProductUIs[p.definition.id].SetPendingTime(secondsRemaining); } } private bool NeedRestoreButton() { return Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.tvOS || Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM || m_IsSamsungAppsStoreSelected || m_IsCloudMoolahStoreSelected; } private bool NeedLoginButton() { return m_IsUnityChannelSelected; } private bool NeedValidateButton() { return m_IsUnityChannelSelected; } private void LogProductDefinitions() { var products = m_Controller.products.all; foreach (var product in products) { #if UNITY_5_6_OR_NEWER Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\nenabled: {3}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString(), product.definition.enabled ? "enabled" : "disabled")); #else Debug.Log(string.Format("id: {0}\nstore-specific id: {1}\ntype: {2}\n", product.definition.id, product.definition.storeSpecificId, product.definition.type.ToString())); #endif } } } #endif // UNITY_PURCHASING
using System; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Text; using RRLab.PhysiologyDataConnectivity; using RRLab.PhysiologyWorkbench.Data; using RRLab.Utilities; using System.IO; using System.Data; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; namespace RRLab.PhysiologyWorkbench { /// <summary> /// Handles data management tasks. /// </summary> public partial class DataManager : Component { public enum DataTemplateMode { Manual, UsePreviousItem }; public event EventHandler CellUpdated; public event EventHandler CellRemoved; public event EventHandler CellStored; public event EventHandler RecordingUpdated; public event EventHandler RecordingRemoved; public event EventHandler RecordingStored; public event EventHandler DataUpdated; public event EventHandler DataStored; public event EventHandler<ExceptionEventArgs> DataStorageError; public DataManager() { InitializeComponent(); } public DataManager(IContainer container) { container.Add(this); InitializeComponent(); } #region Properties /// <summary> /// The dataset has been changed. /// </summary> public event EventHandler DataChanged; private PhysiologyDataSet _Data = new PhysiologyDataSet(); /// <summary> /// A dataset containing all the collected data. /// </summary> public PhysiologyDataSet Data { get { return _Data; } set { _Data = value; OnDataChanged(EventArgs.Empty); } } /// <summary> /// Fires the DataChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDataChanged(EventArgs e) { if (DataChanged != null) try { DataChanged(this, e); } catch(Exception x) { Console.WriteLine("Error during DataChanged event: " + x.Message); } } #endregion #region State Management /// <summary> /// Initializes the DataManager by loading recovery data and retrieving initial data from the database /// </summary> public virtual void Initialize() { // Generate initial dataset if (DatabaseConnector != null) NewDataSetFromDatabase(); else NewDataSet(); // Restore recovery file data RestoreRecoveryFile(); // Register application exit listener Application.ApplicationExit += new EventHandler(OnApplicationExit); } private void OnApplicationExit(object sender, EventArgs e) { OnApplicationExit(e); } /// <summary> /// Finalizes the DataManager by saving data /// </summary> protected virtual void OnApplicationExit(EventArgs e) { IsExiting = true; if (DatabaseConnector != null) { UpdateAllToDatabase(); } else SaveRecoveryFile(); } #endregion #region Current Cell/Recording Management /// <summary> /// Occurs when the cell template mode is changed. /// </summary> public event EventHandler CellTemplateModeChanged; private DataManager.DataTemplateMode _CellTemplateMode = DataTemplateMode.UsePreviousItem; /// <summary> /// Determines how the source template for new cells is chosen. /// </summary> [DefaultValue(DataManager.DataTemplateMode.UsePreviousItem)] [SettingsBindable(true)] public DataManager.DataTemplateMode CellTemplateMode { get { return _CellTemplateMode; } set { _CellTemplateMode = value; OnCellTemplateModeChanged(EventArgs.Empty); } } /// <summary> /// Fires the CellTemplateModeChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnCellTemplateModeChanged(EventArgs e) { if (CellTemplateModeChanged != null) try { CellTemplateModeChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during CellTemplateModeChanged event: " + x.Message); } } public event EventHandler RecordingTemplateModeChanged; private DataManager.DataTemplateMode _RecordingTemplateMode = DataTemplateMode.UsePreviousItem; /// <summary> /// Determines how the source template for new recordings is chosen. /// </summary> [DefaultValue(DataManager.DataTemplateMode.UsePreviousItem)] [SettingsBindable(true)] public DataManager.DataTemplateMode RecordingTemplateMode { get { return _RecordingTemplateMode; } set { _RecordingTemplateMode = value; OnRecordingTemplateModeChanged(EventArgs.Empty); } } /// <summary> /// Fires the RecordingTemplateModeChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnRecordingTemplateModeChanged(EventArgs e) { if (RecordingTemplateChanged != null) try { RecordingTemplateChanged(this, EventArgs.Empty); } catch (Exception x) { Console.WriteLine("Error during TemplateRecordingChanged event: " + x.Message); } } /// <summary> /// Occurs when the current Recording is changed. /// </summary> public event EventHandler CurrentRecordingChanged; private PhysiologyDataSet.RecordingsRow _CurrentRecording = null; /// <summary> /// Gets or sets the current Recording by its row in the dataset. /// If the row's dataset is not the same as the current dataset, /// DataManager.Data will be changed accordingly. Acts by setting /// the CurrentRecording property. /// </summary> [Bindable(true)] public PhysiologyDataSet.RecordingsRow CurrentRecording { get { return _CurrentRecording; } set { if (RecordingTemplateMode == DataTemplateMode.UsePreviousItem && CurrentRecording != null) RecordingTemplate = CurrentRecording; _CurrentRecording = value; OnCurrentRecordingChanged(EventArgs.Empty); } } /// <summary> /// Fires the CurrentRecordingChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnCurrentRecordingChanged(EventArgs e) { if (CurrentRecordingChanged != null) try { CurrentRecordingChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.WriteLine("Error during CurrentRecordingChanged event: " + x.Message); } } /// <summary> /// Occurs when the current cell is changed. /// </summary> public event EventHandler CurrentCellChanged; private PhysiologyDataSet.CellsRow _CurrentCell = null; /// <summary> /// Gets or sets the current cell by its row in the dataset. /// If the dataset of the row is not the same as the current dataset, /// DataManager.Data is updated accordingly. Acts by setting /// CellID. /// </summary> public PhysiologyDataSet.CellsRow CurrentCell { get { return _CurrentCell; } set { if (CellTemplateMode == DataTemplateMode.UsePreviousItem && CurrentCell != null) CellTemplate = CurrentCell; _CurrentCell = value; OnCurrentCellChanged(EventArgs.Empty); } } /// <summary> /// Fires the CellChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnCurrentCellChanged(EventArgs e) { if (CurrentCellChanged != null) try { CurrentCellChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.WriteLine("Error during CellChanged event: " + x.Message); } } #endregion #region Data Creation Methods /// <summary> /// Occurs when the default genotype is changed. /// </summary> public event EventHandler DefaultFlyStockIDChanged; private int _DefaultFlyStockID = 0; /// <summary> /// The default genotype to use in the absence of a template cell. /// </summary> [SettingsBindable(true)] [DefaultValue(0)] public int DefaultFlyStockID { get { return _DefaultFlyStockID; } set { _DefaultFlyStockID = value; OnDefaultFlyStockIDChanged(EventArgs.Empty); } } /// <summary> /// Fires the DefaultFlyStockIDChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDefaultFlyStockIDChanged(EventArgs e) { if (DefaultFlyStockIDChanged != null) try { DefaultFlyStockIDChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DefaultFlyStockIDChanged event: " + x.Message); } } /// <summary> /// Occurs when the default user is changed. /// </summary> public event EventHandler DefaultUserIDChanged; private short _DefaultUserID = 0; /// <summary> /// The default user to use in the absence of a template cell. /// </summary> [SettingsBindable(true)] [DefaultValue(0)] public short DefaultUserID { get { return _DefaultUserID; } set { _DefaultUserID = value; OnDefaultUserIDChanged(EventArgs.Empty); } } /// <summary> /// Fires the DefaultUserIDChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDefaultUserIDChanged(EventArgs e) { if (DefaultUserIDChanged != null) try { DefaultUserIDChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DefaultUserIDChanged event: " + x.Message); } } /// <summary> /// Occurs when the default bath solution is changed. /// </summary> public event EventHandler DefaultBathSolutionChanged; private string _DefaultBathSolution = ""; /// <summary> /// The default bath solution to use in the absence of a template recording. /// </summary> [SettingsBindable(true)] public string DefaultBathSolution { get { return _DefaultBathSolution; } set { _DefaultBathSolution = value; OnDefaultBathSolutionChanged(EventArgs.Empty); } } /// <summary> /// Fires the DefaultBathSolutionChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDefaultBathSolutionChanged(EventArgs e) { if (DefaultBathSolutionChanged != null) try { DefaultBathSolutionChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DefaultBathSolutionChanged event: " + x.Message); } } /// <summary> /// Occurs when the default recording title is changed. /// </summary> public event EventHandler DefaultRecordingTitleChanged; private string _DefaultRecordingTitle = "Untitled Recording"; /// <summary> /// The default recording title. /// </summary> [SettingsBindable(true)] [DefaultValue("Untitled Recording")] public string DefaultRecordingTitle { get { return _DefaultRecordingTitle; } set { _DefaultRecordingTitle = value; OnDefaultRecordingTitleChanged(EventArgs.Empty); } } /// <summary> /// Fires the DefaultRecordingTitleChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDefaultRecordingTitleChanged(EventArgs e) { if (DefaultRecordingTitleChanged != null) try { DefaultRecordingTitleChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DefaultRecordingTitleChanged event: " + x.Message); } } /// <summary> /// Occurs when the template cell is changed. /// </summary> public event EventHandler CellTemplateChanged; private PhysiologyDataSet.CellsRow _CellTemplate; /// <summary> /// The cell row that will be used as a template for new cells. /// </summary> [Bindable(true)] public PhysiologyDataSet.CellsRow CellTemplate { get { return _CellTemplate; } set { _CellTemplate = value; OnCellTemplateChanged(EventArgs.Empty); } } /// <summary> /// Fires the CellTemplateChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnCellTemplateChanged(EventArgs e) { if (CellTemplateChanged != null) try { CellTemplateChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during CellTemplateChanged event: " + x.Message); } } /// <summary> /// Occurs when the recording template is changed. /// </summary> public event EventHandler RecordingTemplateChanged; private PhysiologyDataSet.RecordingsRow _RecordingTemplate; /// <summary> /// The Recordings row that will be used as a template for new rows. /// </summary> [Bindable(true)] public PhysiologyDataSet.RecordingsRow RecordingTemplate { get { return _RecordingTemplate; } set { _RecordingTemplate = value; OnRecordingTemplateChanged(EventArgs.Empty); } } protected virtual void OnRecordingTemplateChanged(EventArgs e) { if (RecordingTemplateChanged != null) try { RecordingTemplateChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during RecordingTemplateChanged event: " + x.Message); } } /// <summary> /// If there is no current dataset, creates a new empty one. /// </summary> public virtual void NewDataSet() { if (Data == null) Data = new PhysiologyDataSet(); } /// <summary> /// Generates a new cells row, setting Created and filling in /// the FlyStockID and UserID based on the CellTemplate or /// DefaultFlyStockID and DefaultUserID. /// </summary> /// <returns>The new cells row.</returns> public virtual PhysiologyDataSet.CellsRow CreateNewCell() { if (Data == null) NewDataSetFromDatabase(); UpdateAllToDatabase(); PhysiologyDataSet.CellsRow cell = Data.Cells.NewCellsRow(); // Apply general settings cell.Created = DateTime.Now; // Apply template if (CellTemplate != null) { cell.FlyStockID = CellTemplate.FlyStockID; cell.UserID = CellTemplate.UserID; } else // Ensure no fields that are NotNull are left null { cell.FlyStockID = DefaultFlyStockID; cell.UserID = DefaultUserID; } Data.Cells.AddCellsRow(cell); CurrentCell = cell; return cell; } public virtual PhysiologyDataSet.RecordingsRow GetNewRecording() { if (Data == null) NewDataSetFromDatabase(); PhysiologyDataSet.RecordingsRow recording = Data.Recordings.NewRecordingsRow(); if (CurrentCell == null) CreateNewCell(); // Apply general settings recording.Recorded = DateTime.Now; recording.CellID = CurrentCell.CellID; // Add it to the current cell recording.Title = DefaultRecordingTitle; // Apply template if (RecordingTemplate != null) { recording.BathSolution = RecordingTemplate.BathSolution; if (!RecordingTemplate.IsPipetteSolutionNull()) recording.PipetteSolution = RecordingTemplate.PipetteSolution; } else // Ensure that no NotNull fields are left null { recording.BathSolution = DefaultBathSolution; } Data.Recordings.AddRecordingsRow(recording); return recording; } /// <summary> /// Creates a new recording, attaches it to the the current cell, and /// sets Recorded to the current time, Title to DefaultRecordingTitle, /// and fills in BathSolution and PipetteSolution using RecordingTemplate /// or DefaultBathSolution. /// </summary> /// <returns>The new recording.</returns> public virtual PhysiologyDataSet.RecordingsRow CreateNewRecording() { CurrentRecording = GetNewRecording(); return CurrentRecording; } #endregion #region Database Storage /// <summary> /// The database connector has been changed. /// </summary> public event EventHandler DatabaseConnectorChanged; private IPhysiologyDataDatabaseConnector _DatabaseConnector = new MySqlDataManagerDatabaseConnector(); /// <summary> /// The database connector that will be called when the data needs to be updated to a database. /// </summary> public IPhysiologyDataDatabaseConnector DatabaseConnector { get { return _DatabaseConnector; } set { _DatabaseConnector = value; OnDatabaseConnectorChanged(EventArgs.Empty); } } /// <summary> /// Fires the DatabaseConnectorChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDatabaseConnectorChanged(EventArgs e) { if (DatabaseConnectorChanged != null) try { DatabaseConnectorChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DatabaseConnectorChanged event: " + x.Message); } } /// <summary> /// Creates a new dataset and fills the users and genotypes table. /// If DatabaseConnector is null, only calls NewDataSet. /// </summary> public virtual void NewDataSetFromDatabase() { NewDataSet(); if (DatabaseConnector != null) { try { DatabaseConnector.LoadUsersFromDatabase(Data); DatabaseConnector.LoadGenotypesFromDatabase(Data); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error loading users and genotypes: " + e.Message); } } } public event EventHandler StartingDatabaseUpdate; protected virtual void OnStartingDatabaseUpdate(EventArgs e) { if(StartingDatabaseUpdate != null) try { StartingDatabaseUpdate(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("DataManager: Error during StartingDatabaseUpdate event.", x.Message); } } public event EventHandler FinishedDatabaseUpdate; protected virtual void OnFinishedDatabaseUpdate(object sender, EventArgs e) { OnFinishedDatabaseUpdate(e); } protected virtual void OnFinishedDatabaseUpdate(EventArgs e) { ClearStoredRecordingData(); // To save memory System.GC.Collect(); if (FinishedDatabaseUpdate != null) try { FinishedDatabaseUpdate(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("DataManager: Error during FinishedDatabaseUpdate event.", x.Message); } } /// <summary> /// Updates all data to the database asynchronously, showing a ProgressDialog. /// If a TaskError occurs, fires DataStorageError. /// </summary> public virtual void UpdateAllToDatabase() { // TODO: Safe handling of this error if (DatabaseConnector == null) throw new Exception("Database connector is null."); OnStartingDatabaseUpdate(EventArgs.Empty); ProgressDialog dialog = new ProgressDialog(); dialog.TaskError += new EventHandler<ExceptionEventArgs>(OnDataStorageError); dialog.TaskStopped += new EventHandler(OnFinishedDatabaseUpdate); DatabaseConnector.BeginUpdateDataSetToDatabase(Data, dialog); } /// <summary> /// Updates the current cell to the database asynchronously, showing a ProgressDialog. /// If a TaskError occurs, fires DataStorageError. /// </summary> public virtual void UpdateCurrentCellToDatabase() { if (CurrentCell == null) return; // TODO: Safe handling of this error if (DatabaseConnector == null) throw new Exception("Database connector is null."); OnStartingDatabaseUpdate(EventArgs.Empty); ProgressDialog dialog = new ProgressDialog(); dialog.TaskError += new EventHandler<ExceptionEventArgs>(OnDataStorageError); dialog.TaskStopped += new EventHandler(OnFinishedDatabaseUpdate); DatabaseConnector.BeginUpdateCellAndSubdataToDatabase(Data, CurrentCell.CellID, dialog); } /// <summary> /// Updates the current recording to the database asynchronously, showing a ProgressDialog. /// If a TaskError occurs, fires DataStorageError. /// </summary> public virtual void UpdateCurrentRecordingToDatabase() { // TODO: Safe handling of this error if (DatabaseConnector == null) throw new Exception("Database connector is null."); OnStartingDatabaseUpdate(EventArgs.Empty); ProgressDialog dialog = new ProgressDialog(); dialog.TaskError += new EventHandler<ExceptionEventArgs>(OnDataStorageError); dialog.TaskStopped += new EventHandler(OnFinishedDatabaseUpdate); DatabaseConnector.BeginUpdateRecordingAndSubdataToDatabase(Data, CurrentRecording.RecordingID, dialog); } /// <summary> /// Removes recording data that has already been stored /// (determined by the RowState being set to Original). Be sure to call /// EndCurrentEdit() on any BindingSources before this method. /// </summary> public virtual void ClearStoredRecordingData() { // Recording data DataRow[] rows = Data.Recordings_Data.Select(null, null, System.Data.DataViewRowState.Unchanged); foreach (DataRow row in rows) { row.EndEdit(); // Does this address the BindingSource edit problem? if (row.RowState == DataRowState.Unchanged) { row.Delete(); row.AcceptChanges(); } } } private bool _IsExiting = false; /// <summary> /// True if the application is exiting. /// </summary> protected bool IsExiting { get { return _IsExiting; } set { _IsExiting = value; } } private void OnDataStorageError(object sender, ExceptionEventArgs e) { OnDataStorageError(e); } /// <summary> /// Fires the DataStorageError event. /// </summary> /// <param name="e"></param> protected virtual void OnDataStorageError(ExceptionEventArgs e) { System.Windows.Forms.MessageBox.Show("Error storing data: " + e.Message); if (IsExiting) { System.Windows.Forms.MessageBox.Show("Saving recovery file..."); try { SaveRecoveryFile(); System.Windows.Forms.MessageBox.Show("Recovery file successfully saved to " + DataFolder + RecoveryFileName); } catch (Exception x) { System.Windows.Forms.MessageBox.Show("Error while saving recovery file: " + x.Message); } } if(DataStorageError != null) try { DataStorageError(this, e); } catch (Exception x) { Console.WriteLine("Error during DataStorageError event: " + x.Message); } } #endregion #region File Storage Methods /// <summary> /// Occurs when the data folder is changed. /// </summary> public event EventHandler DataFolderChanged; private string _DataFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + System.IO.Path.DirectorySeparatorChar + "Physiology Workbench Data" + System.IO.Path.DirectorySeparatorChar; /// <summary> /// The default folder to store saved data and recovery information to. /// </summary> [Bindable(true)] [SettingsBindable(true)] public string DataFolder { get { return _DataFolder; } set { _DataFolder = value; OnDataFolderChanged(EventArgs.Empty); } } /// <summary> /// Fires the DataFolderChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnDataFolderChanged(EventArgs e) { if (DataFolderChanged != null) try { DataFolderChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during DataFolderChanged event: " + x.Message); } } /// <summary> /// Occurs when the recovery file name is changed. /// </summary> public event EventHandler RecoveryFileNameChanged; private string _RecoveryFileName = "Recovery Autosave.pdata"; /// <summary> /// The recovery autosave file name. Should have the pdata extension. /// The file will be placed in the DataFolder. /// </summary> [DefaultValue("Recovery Autosave.pdata")] [Bindable(true)] [SettingsBindable(true)] public string RecoveryFileName { get { return _RecoveryFileName; } set { _RecoveryFileName = value; OnRecoveryFileNameChanged(EventArgs.Empty); } } /// <summary> /// Fires the RecoveryFileNameChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnRecoveryFileNameChanged(EventArgs e) { if (RecoveryFileNameChanged != null) try { RecoveryFileNameChanged(this, e); } catch (Exception x) { Console.WriteLine("Error during RecoveryFileNameChanged event: " + x.Message); } } /// <summary> /// Checks whether the recovery file exists. /// </summary> public bool DoesRecoveryFileExist { get { return File.Exists(DataFolder + RecoveryFileName); } } /// <summary> /// Shows the user a save file dialog box and saves the current data /// to the chosen file. /// </summary> /// <returns>True if the data was saved</returns> public virtual bool RequestUserToSaveDataToFile() { if (SaveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { using (Stream fileStream = SaveFileDialog.OpenFile()) { SaveDataToStream(fileStream); return true; } } catch(Exception e) { OnDataStorageError(new ExceptionEventArgs(e)); return false; } } else return false; } /// <summary> /// Saves the current data to the recovery file. /// </summary> public virtual void SaveRecoveryFile() { SaveDataToFile(DataFolder + RecoveryFileName); } /// <summary> /// Saves the current data to the specified file /// </summary> /// <param name="path">The file name and path to save the data to</param> public virtual void SaveDataToFile(string path) { using (FileStream fileStream = File.Open(path, FileMode.OpenOrCreate)) { SaveDataToStream(fileStream); } } /// <summary> /// Saves the current data to the provided stream /// </summary> /// <param name="stream">The stream to save the data to</param> public virtual void SaveDataToStream(Stream stream) { using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); try { binaryFormatter.Serialize(zipStream, Data); } catch (Exception e) { OnDataStorageError(new ExceptionEventArgs("Error during data serialization",e)); } } } /// <summary> /// Restores the recovery file if it exists /// </summary> public virtual void RestoreRecoveryFile() { if (DoesRecoveryFileExist) { OpenDataFromFile(DataFolder + RecoveryFileName); } } /// <summary> /// Merges the data in the provided file with the current data /// </summary> /// <param name="file">The file name to open</param> public virtual void OpenDataFromFile(string file) { using (FileStream fileStream = File.Open(file, FileMode.Open)) { OpenDataFromStream(fileStream); } } /// <summary> /// Merges the data in the provided stream with the current data /// </summary> /// <param name="stream">The stream to read from</param> public virtual void OpenDataFromStream(Stream stream) { using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); try { PhysiologyDataSet openedData = binaryFormatter.Deserialize(zipStream) as PhysiologyDataSet; if (openedData != null && Data != null) Data.Merge(openedData); else if (Data == null) Data = openedData; } catch (Exception e) { OnDataStorageError(new ExceptionEventArgs("Error during data deserialization", e)); } } } #endregion } }
// // lambda.cs: support for lambda expressions // // Authors: Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2007-2008 Novell, Inc // Copyright 2011 Xamarin Inc // #if STATIC using IKVM.Reflection.Emit; #else using System.Reflection.Emit; #endif namespace Mono.CSharp { public class LambdaExpression : AnonymousMethodExpression { // // The parameters can either be: // A list of Parameters (explicitly typed parameters) // An ImplicitLambdaParameter // public LambdaExpression (Location loc) : base (loc) { } protected override Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type) { if (ec.IsInProbingMode) return this; BlockContext bc = new BlockContext (ec.MemberContext, ec.ConstructorBlock, ec.BuiltinTypes.Void) { CurrentAnonymousMethod = ec.CurrentAnonymousMethod }; Expression args = Parameters.CreateExpressionTree (bc, loc); Expression expr = Block.CreateExpressionTree (ec); if (expr == null) return null; Arguments arguments = new Arguments (2); arguments.Add (new Argument (expr)); arguments.Add (new Argument (args)); return CreateExpressionFactoryCall (ec, "Lambda", new TypeArguments (new TypeExpression (delegate_type, loc)), arguments); } public override bool HasExplicitParameters { get { return Parameters.Count > 0 && !(Parameters.FixedParameters [0] is ImplicitLambdaParameter); } } protected override ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegateType) { if (!delegateType.IsDelegate) return null; AParametersCollection d_params = Delegate.GetParameters (delegateType); if (HasExplicitParameters) { if (!VerifyExplicitParameters (ec, tic, delegateType, d_params)) return null; return Parameters; } // // If L has an implicitly typed parameter list we make implicit parameters explicit // Set each parameter of L is given the type of the corresponding parameter in D // if (!VerifyParameterCompatibility (ec, tic, delegateType, d_params, ec.IsInProbingMode)) return null; TypeSpec [] ptypes = new TypeSpec [Parameters.Count]; for (int i = 0; i < d_params.Count; i++) { // D has no ref or out parameters if ((d_params.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != 0) return null; TypeSpec d_param = d_params.Types [i]; // // When type inference context exists try to apply inferred type arguments // if (tic != null) { d_param = tic.InflateGenericArgument (ec, d_param); } ptypes [i] = d_param; ImplicitLambdaParameter ilp = (ImplicitLambdaParameter) Parameters.FixedParameters [i]; ilp.SetParameterType (d_param); ilp.Resolve (null, i); } Parameters.Types = ptypes; return Parameters; } protected override AnonymousMethodBody CompatibleMethodFactory (TypeSpec returnType, TypeSpec delegateType, ParametersCompiled p, ParametersBlock b) { return new LambdaMethod (p, b, returnType, delegateType, loc); } protected override bool DoResolveParameters (ResolveContext rc) { // // Only explicit parameters can be resolved at this point // if (HasExplicitParameters) { return Parameters.Resolve (rc); } return true; } public override string GetSignatureForError () { return "lambda expression"; } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } class LambdaMethod : AnonymousMethodBody { public LambdaMethod (ParametersCompiled parameters, ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type, Location loc) : base (parameters, block, return_type, delegate_type, loc) { } #region Properties public override string ContainerType { get { return "lambda expression"; } } #endregion protected override void CloneTo (CloneContext clonectx, Expression target) { // TODO: nothing ?? } public override Expression CreateExpressionTree (ResolveContext ec) { BlockContext bc = new BlockContext (ec.MemberContext, Block, ReturnType); Expression args = parameters.CreateExpressionTree (bc, loc); Expression expr = Block.CreateExpressionTree (ec); if (expr == null) return null; Arguments arguments = new Arguments (2); arguments.Add (new Argument (expr)); arguments.Add (new Argument (args)); return CreateExpressionFactoryCall (ec, "Lambda", new TypeArguments (new TypeExpression (type, loc)), arguments); } } // // This is a return statement that is prepended lambda expression bodies that happen // to be expressions. Depending on the return type of the delegate this will behave // as either { expr (); return (); } or { return expr (); } // public class ContextualReturn : Return { ExpressionStatement statement; public ContextualReturn (Expression expr) : base (expr, expr.StartLocation) { } public override Expression CreateExpressionTree (ResolveContext ec) { if (Expr is ReferenceExpression) { ec.Report.Error (8155, Expr.Location, "Lambda expressions that return by reference cannot be converted to expression trees"); return null; } return Expr.CreateExpressionTree (ec); } protected override void DoEmit (EmitContext ec) { if (statement != null) { statement.EmitStatement (ec); if (unwind_protect) ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ()); else { ec.Emit (OpCodes.Ret); } return; } base.DoEmit (ec); } protected override bool DoResolve (BlockContext ec) { // // When delegate returns void, only expression statements can be used // if (ec.ReturnType.Kind == MemberKind.Void) { Expr = Expr.Resolve (ec); if (Expr == null) return false; if (Expr is ReferenceExpression) { // CSC: should be different error code ec.Report.Error (8149, loc, "By-reference returns can only be used in lambda expressions that return by reference"); return false; } statement = Expr as ExpressionStatement; if (statement == null) { var reduced = Expr as IReducedExpressionStatement; if (reduced != null) { statement = EmptyExpressionStatement.Instance; } else { Expr.Error_InvalidExpressionStatement (ec); } } return true; } return base.DoResolve (ec); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// InheritanceOperations operations. /// </summary> internal partial class InheritanceOperations : IServiceOperations<AzureCompositeModel>, IInheritanceOperations { /// <summary> /// Initializes a new instance of the InheritanceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal InheritanceOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex types that extend others /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SiameseInner>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SiameseInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SiameseInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that extend others /// </summary> /// <param name='complexBody'> /// Please put a siamese with id=2, name="Siameee", color=green, breed=persion, /// which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", /// and the 2nd one named "Tomato" with id=-1 and food="french fries". /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(SiameseInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A recycling center. /// </summary> public class RecyclingCenter_Core : TypeCore, ILocalBusiness { public RecyclingCenter_Core() { this._TypeId = 225; this._Id = "RecyclingCenter"; this._Schema_Org_Url = "http://schema.org/RecyclingCenter"; string label = ""; GetLabel(out label, "RecyclingCenter", typeof(RecyclingCenter_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; using System.Text; namespace SharpMath.LinearAlgebra { [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{DebuggerDisplay}")] public sealed class ComplexMatrix { private int rows, columns; private Complex[] entries; public ComplexMatrix(Complex[,] values) : this(values.GetLength(0), values.GetLength(1)) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { SetEntryInternal(i, j, values[i, j]); } } } private ComplexMatrix(int rows, int columns) { // This constructor is intentionally kept private. Use Zero instead. this.rows = rows; this.columns = columns; entries = new Complex[rows * columns]; } private ComplexMatrix(int rows, int columns, Complex[] entries) { this.rows = rows; this.columns = columns; this.entries = (Complex[])entries.Clone(); } private void SetEntryInternal(int row, int column, Complex t) { entries[row + column * rows] = t; } private Complex GetEntryInternal(int row, int column) { return entries[row + column * rows]; } public ComplexMatrix SetEntry(int row, int column, Complex t) { if (row < 0 || row >= rows || column < 0 || column >= columns) { throw new IndexOutOfRangeException(); } ComplexMatrix a = new ComplexMatrix(rows, columns, entries); a.SetEntryInternal(row, column, t); return a; } public ComplexMatrix SetMatrix(int row, int column, ComplexMatrix a) { if (row < 0 || row + a.rows > rows || column < 0 || column + a.columns > columns) { throw new IndexOutOfRangeException(); } ComplexMatrix b = new ComplexMatrix(rows, columns, entries); for (int i = 0; i < a.rows; i++) { for (int j = 0; j < a.columns; j++) { b.SetEntryInternal(row + i, column + j, a.GetEntryInternal(i, j)); } } return b; } public ComplexMatrix GetMatrix(int row, int column, int rows, int columns) { if (row < 0 || row + rows > this.rows || column < 0 || column + columns > this.columns) { throw new IndexOutOfRangeException(); } int n = rows; int m = columns; ComplexMatrix a = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a.SetEntryInternal(i, j, GetEntryInternal(row + i, column + j)); } } return a; } public ComplexMatrix GetRow(int row) { int n = columns; return GetMatrix(row, 0, 1, n); } public ComplexVector GetColumn(int column) { int n = rows; // Use conversion operator defined in Vector. return (ComplexVector)(GetMatrix(0, column, n, 1)); } public Complex[,] ToArray() { Complex[,] values = new Complex[rows, columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { values[i, j] = GetEntryInternal(i, j); } } return values; } public Complex[] ToLinearArray() { return (Complex[])entries.Clone(); } public override string ToString() { return ToString(null); } public string ToString(string format) { StringBuilder sb = new StringBuilder(); sb.Append("{"); for (int i = 0; i < rows; i++) { if (i > 0) { sb.Append(", "); } sb.Append("{"); for (int j = 0; j < columns; j++) { if (j > 0) { sb.Append(", "); } sb.Append(GetEntryInternal(i, j).ToString()); } sb.Append("}"); } sb.Append("}"); return sb.ToString(); } public static ComplexMatrix Zero(int rows, int columns) { return new ComplexMatrix(rows, columns); } public static ComplexMatrix Identity(int rows, int columns) { int n = Math.Min(rows, columns); ComplexMatrix a = new ComplexMatrix(rows, columns); for (int i = 0; i < n; i++) { a.SetEntryInternal(i, i, 1.0); } return a; } public static ComplexMatrix Diagonal(Complex[] values) { int n = values.Length; ComplexMatrix a = new ComplexMatrix(n, n); for (int i = 0; i < n; i++) { a.SetEntryInternal(i, i, values[i]); } return a; } public static ComplexMatrix Basis(int rows, int columns, int row, int column) { if (row < 0 || row >= rows || column < 0 || column >= columns) { throw new IndexOutOfRangeException(); } ComplexMatrix a = new ComplexMatrix(rows, columns); a.SetEntryInternal(row, column, 1.0); return a; } public static ComplexMatrix Transpose(ComplexMatrix a) { int n = a.columns; int m = a.rows; ComplexMatrix b = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b.SetEntryInternal(i, j, a.GetEntryInternal(j, i)); } } return b; } public static Complex Trace(ComplexMatrix a) { int n = Math.Min(a.rows, a.columns); Complex s = 0.0; for (int i = 0; i < n; i++) { s += a[i, i]; } return s; } public static implicit operator ComplexMatrix(Matrix a) { int n = a.Rows; int m = a.Columns; ComplexMatrix b = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b.SetEntryInternal(i, j, a[i, j]); } } return b; } public static ComplexMatrix operator +(ComplexMatrix a, ComplexMatrix b) { int n = a.Rows; int m = a.Columns; if (b.rows != n || b.columns != m) { throw new ArgumentException("The matrix dimensions don't match."); } ComplexMatrix c = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { c.SetEntryInternal(i, j, a.GetEntryInternal(i, j) + b.GetEntryInternal(i, j)); } } return c; } public static ComplexMatrix operator +(ComplexMatrix a, Matrix b) { return a + (ComplexMatrix)b; } public static ComplexMatrix operator +(Matrix a, ComplexMatrix b) { return (ComplexMatrix)a + b; } public static ComplexMatrix operator +(ComplexMatrix a, Complex t) { int n = a.Rows; int m = a.Columns; ComplexMatrix c = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { c.SetEntryInternal(i, j, a.GetEntryInternal(i, j) + t); } } return c; } public static ComplexMatrix operator +(Complex t, ComplexMatrix a) { return a + t; } public static ComplexMatrix operator -(ComplexMatrix a) { return a * -1.0; } public static ComplexMatrix operator -(ComplexMatrix a, ComplexMatrix b) { int n = a.rows; int m = a.columns; if (b.rows != n || b.columns != m) { throw new ArgumentException("The matrix dimensions don't match."); } ComplexMatrix c = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { c.SetEntryInternal(i, j, a.GetEntryInternal(i, j) - b.GetEntryInternal(i, j)); } } return c; } public static ComplexMatrix operator -(ComplexMatrix a, Complex t) { return a + (-t); } public static ComplexMatrix operator -(Complex t, ComplexMatrix a) { int n = a.rows; int m = a.columns; ComplexMatrix b = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b.SetEntryInternal(i, j, t - a.GetEntryInternal(i, j)); } } return b; } public static ComplexMatrix operator *(ComplexMatrix a, ComplexMatrix b) { int n = a.rows; int m = b.columns; int l = a.columns; if (b.rows != l) { throw new ArgumentException("The matrix dimensions don't match."); } ComplexMatrix c = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Complex s = 0.0; for (int k = 0; k < l; k++) { s += a.GetEntryInternal(i, k) * b.GetEntryInternal(k, j); } c.SetEntryInternal(i, j, s); } } return c; } public static ComplexMatrix operator *(Matrix a, ComplexMatrix b) { return (ComplexMatrix)a * b; } public static ComplexMatrix operator *(ComplexMatrix a, Complex t) { int n = a.rows; int m = a.columns; ComplexMatrix b = new ComplexMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { b.SetEntryInternal(i, j, a.GetEntryInternal(i, j) * t); } } return b; } public static ComplexMatrix operator *(Complex t, ComplexMatrix a) { return a * t; } public static ComplexMatrix operator /(ComplexMatrix a, Complex t) { return a * (1.0 / t); } public Complex this[int row, int column] { get { if (row < 0 || row >= rows || column < 0 || column >= columns) { throw new IndexOutOfRangeException(); } return GetEntryInternal(row, column); } } public int Rows { get { return rows; } } public int Columns { get { return columns; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { return ToString(); } } } }
#region Copyright and License // Copyright 2010..2015 Alexander Reinert // // This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.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 using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using ARSoft.Tools.Net.Dns.DynamicUpdate; namespace ARSoft.Tools.Net.Dns { /// <summary> /// Base class for a dns answer /// </summary> public abstract class DnsMessageBase { protected ushort Flags; protected internal List<DnsQuestion> Questions = new List<DnsQuestion>(); protected internal List<DnsRecordBase> AnswerRecords = new List<DnsRecordBase>(); protected internal List<DnsRecordBase> AuthorityRecords = new List<DnsRecordBase>(); private List<DnsRecordBase> _additionalRecords = new List<DnsRecordBase>(); /// <summary> /// Gets or sets the entries in the additional records section /// </summary> public List<DnsRecordBase> AdditionalRecords { get { return _additionalRecords; } set { _additionalRecords = (value ?? new List<DnsRecordBase>()); } } internal abstract bool IsTcpUsingRequested { get; } internal abstract bool IsTcpResendingRequested { get; } internal abstract bool IsTcpNextMessageWaiting(bool isSubsequentResponseMessage); #region Header /// <summary> /// Gets or sets the transaction identifier (ID) of the message /// </summary> public ushort TransactionID { get; set; } /// <summary> /// Gets or sets the query (QR) flag /// </summary> public bool IsQuery { get { return (Flags & 0x8000) == 0; } set { if (value) { Flags &= 0x7fff; } else { Flags |= 0x8000; } } } /// <summary> /// Gets or sets the Operation Code (OPCODE) /// </summary> public OperationCode OperationCode { get { return (OperationCode) ((Flags & 0x7800) >> 11); } set { ushort clearedOp = (ushort) (Flags & 0x8700); Flags = (ushort) (clearedOp | (ushort) value << 11); } } /// <summary> /// Gets or sets the return code (RCODE) /// </summary> public ReturnCode ReturnCode { get { ReturnCode rcode = (ReturnCode) (Flags & 0x000f); OptRecord ednsOptions = EDnsOptions; if (ednsOptions == null) { return rcode; } else { // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags return (rcode | ednsOptions.ExtendedReturnCode); } } set { OptRecord ednsOptions = EDnsOptions; if ((ushort) value > 15) { if (ednsOptions == null) { throw new ArgumentOutOfRangeException(nameof(value), "ReturnCodes greater than 15 only allowed in edns messages"); } else { ednsOptions.ExtendedReturnCode = value; } } else { if (ednsOptions != null) { ednsOptions.ExtendedReturnCode = 0; } } ushort clearedOp = (ushort) (Flags & 0xfff0); Flags = (ushort) (clearedOp | ((ushort) value & 0x0f)); } } #endregion #region EDNS /// <summary> /// Enables or disables EDNS /// </summary> public bool IsEDnsEnabled { get { if (_additionalRecords != null) { return _additionalRecords.Any(record => (record.RecordType == RecordType.Opt)); } else { return false; } } set { if (value && !IsEDnsEnabled) { if (_additionalRecords == null) { _additionalRecords = new List<DnsRecordBase>(); } _additionalRecords.Add(new OptRecord()); } else if (!value && IsEDnsEnabled) { _additionalRecords.RemoveAll(record => (record.RecordType == RecordType.Opt)); } } } /// <summary> /// Gets or set the OptRecord for the EDNS options /// </summary> public OptRecord EDnsOptions { get { return (OptRecord) _additionalRecords?.Find(record => (record.RecordType == RecordType.Opt)); } set { if (value == null) { IsEDnsEnabled = false; } else if (IsEDnsEnabled) { int pos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.Opt)); _additionalRecords[pos] = value; } else { if (_additionalRecords == null) { _additionalRecords = new List<DnsRecordBase>(); } _additionalRecords.Add(value); } } } #endregion #region TSig /// <summary> /// Gets or set the TSigRecord for the tsig signed messages /// </summary> // ReSharper disable once InconsistentNaming public TSigRecord TSigOptions { get; set; } internal static DnsMessageBase CreateByFlag(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac) { int flagPosition = 2; ushort flags = ParseUShort(data, ref flagPosition); DnsMessageBase res; switch ((OperationCode) ((flags & 0x7800) >> 11)) { case OperationCode.Update: res = new DnsUpdateMessage(); break; default: res = new DnsMessage(); break; } res.ParseInternal(data, tsigKeySelector, originalMac); return res; } internal static TMessage Parse<TMessage>(byte[] data) where TMessage : DnsMessageBase, new() { return Parse<TMessage>(data, null, null); } internal static TMessage Parse<TMessage>(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac) where TMessage : DnsMessageBase, new() { TMessage result = new TMessage(); result.ParseInternal(data, tsigKeySelector, originalMac); return result; } private void ParseInternal(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac) { int currentPosition = 0; TransactionID = ParseUShort(data, ref currentPosition); Flags = ParseUShort(data, ref currentPosition); int questionCount = ParseUShort(data, ref currentPosition); int answerRecordCount = ParseUShort(data, ref currentPosition); int authorityRecordCount = ParseUShort(data, ref currentPosition); int additionalRecordCount = ParseUShort(data, ref currentPosition); ParseQuestions(data, ref currentPosition, questionCount); ParseSection(data, ref currentPosition, AnswerRecords, answerRecordCount); ParseSection(data, ref currentPosition, AuthorityRecords, authorityRecordCount); ParseSection(data, ref currentPosition, _additionalRecords, additionalRecordCount); if (_additionalRecords.Count > 0) { int tSigPos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.TSig)); if (tSigPos == (_additionalRecords.Count - 1)) { TSigOptions = (TSigRecord) _additionalRecords[tSigPos]; _additionalRecords.RemoveAt(tSigPos); TSigOptions.ValidationResult = ValidateTSig(data, tsigKeySelector, originalMac); } } FinishParsing(); } private ReturnCode ValidateTSig(byte[] resultData, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac) { byte[] keyData; if ((TSigOptions.Algorithm == TSigAlgorithm.Unknown) || (tsigKeySelector == null) || ((keyData = tsigKeySelector(TSigOptions.Algorithm, TSigOptions.Name)) == null)) { return ReturnCode.BadKey; } else if (((TSigOptions.TimeSigned - TSigOptions.Fudge) > DateTime.Now) || ((TSigOptions.TimeSigned + TSigOptions.Fudge) < DateTime.Now)) { return ReturnCode.BadTime; } else if ((TSigOptions.Mac == null) || (TSigOptions.Mac.Length == 0)) { return ReturnCode.BadSig; } else { TSigOptions.KeyData = keyData; // maxLength for the buffer to validate: Original (unsigned) dns message and encoded TSigOptions // because of compression of keyname, the size of the signed message can not be used int maxLength = TSigOptions.StartPosition + TSigOptions.MaximumLength; if (originalMac != null) { // add length of mac on responses. MacSize not neccessary, this field is allready included in the size of the tsig options maxLength += originalMac.Length; } byte[] validationBuffer = new byte[maxLength]; int currentPosition = 0; // original mac if neccessary if ((originalMac != null) && (originalMac.Length > 0)) { EncodeUShort(validationBuffer, ref currentPosition, (ushort) originalMac.Length); EncodeByteArray(validationBuffer, ref currentPosition, originalMac); } // original unsiged buffer Buffer.BlockCopy(resultData, 0, validationBuffer, currentPosition, TSigOptions.StartPosition); // update original transaction id and ar count in message EncodeUShort(validationBuffer, currentPosition, TSigOptions.OriginalID); EncodeUShort(validationBuffer, currentPosition + 10, (ushort) _additionalRecords.Count); currentPosition += TSigOptions.StartPosition; // TSig Variables EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigOptions.Name, null, false); EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.RecordClass); EncodeInt(validationBuffer, ref currentPosition, (ushort) TSigOptions.TimeToLive); EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), null, false); TSigRecord.EncodeDateTime(validationBuffer, ref currentPosition, TSigOptions.TimeSigned); EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Fudge.TotalSeconds); EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Error); EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.OtherData.Length); EncodeByteArray(validationBuffer, ref currentPosition, TSigOptions.OtherData); // Validate MAC KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm); hashAlgorithm.Key = keyData; return (hashAlgorithm.ComputeHash(validationBuffer, 0, currentPosition).SequenceEqual(TSigOptions.Mac)) ? ReturnCode.NoError : ReturnCode.BadSig; } } #endregion #region Parsing protected virtual void FinishParsing() {} #region Methods for parsing answer private static void ParseSection(byte[] resultData, ref int currentPosition, List<DnsRecordBase> sectionList, int recordCount) { for (int i = 0; i < recordCount; i++) { sectionList.Add(ParseRecord(resultData, ref currentPosition)); } } private static DnsRecordBase ParseRecord(byte[] resultData, ref int currentPosition) { int startPosition = currentPosition; DomainName name = ParseDomainName(resultData, ref currentPosition); RecordType recordType = (RecordType) ParseUShort(resultData, ref currentPosition); DnsRecordBase record = DnsRecordBase.Create(recordType, resultData, currentPosition + 6); record.StartPosition = startPosition; record.Name = name; record.RecordType = recordType; record.RecordClass = (RecordClass) ParseUShort(resultData, ref currentPosition); record.TimeToLive = ParseInt(resultData, ref currentPosition); record.RecordDataLength = ParseUShort(resultData, ref currentPosition); if (record.RecordDataLength > 0) { record.ParseRecordData(resultData, currentPosition, record.RecordDataLength); currentPosition += record.RecordDataLength; } return record; } private void ParseQuestions(byte[] resultData, ref int currentPosition, int recordCount) { for (int i = 0; i < recordCount; i++) { DnsQuestion question = new DnsQuestion { Name = ParseDomainName(resultData, ref currentPosition), RecordType = (RecordType) ParseUShort(resultData, ref currentPosition), RecordClass = (RecordClass) ParseUShort(resultData, ref currentPosition) }; Questions.Add(question); } } #endregion #region Helper methods for parsing records internal static string ParseText(byte[] resultData, ref int currentPosition) { int length = resultData[currentPosition++]; return ParseText(resultData, ref currentPosition, length); } internal static string ParseText(byte[] resultData, ref int currentPosition, int length) { string res = Encoding.ASCII.GetString(resultData, currentPosition, length); currentPosition += length; return res; } internal static DomainName ParseDomainName(byte[] resultData, ref int currentPosition) { int firstLabelLength; DomainName res = ParseDomainName(resultData, currentPosition, out firstLabelLength); currentPosition += firstLabelLength; return res; } internal static ushort ParseUShort(byte[] resultData, ref int currentPosition) { ushort res; if (BitConverter.IsLittleEndian) { res = (ushort) ((resultData[currentPosition++] << 8) | resultData[currentPosition++]); } else { res = (ushort) (resultData[currentPosition++] | (resultData[currentPosition++] << 8)); } return res; } internal static int ParseInt(byte[] resultData, ref int currentPosition) { int res; if (BitConverter.IsLittleEndian) { res = ((resultData[currentPosition++] << 24) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 8) | resultData[currentPosition++]); } else { res = (resultData[currentPosition++] | (resultData[currentPosition++] << 8) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 24)); } return res; } internal static uint ParseUInt(byte[] resultData, ref int currentPosition) { uint res; if (BitConverter.IsLittleEndian) { res = (((uint) resultData[currentPosition++] << 24) | ((uint) resultData[currentPosition++] << 16) | ((uint) resultData[currentPosition++] << 8) | resultData[currentPosition++]); } else { res = (resultData[currentPosition++] | ((uint) resultData[currentPosition++] << 8) | ((uint) resultData[currentPosition++] << 16) | ((uint) resultData[currentPosition++] << 24)); } return res; } internal static ulong ParseULong(byte[] resultData, ref int currentPosition) { ulong res; if (BitConverter.IsLittleEndian) { res = ((ulong) ParseUInt(resultData, ref currentPosition) << 32) | ParseUInt(resultData, ref currentPosition); } else { res = ParseUInt(resultData, ref currentPosition) | ((ulong) ParseUInt(resultData, ref currentPosition) << 32); } return res; } private static DomainName ParseDomainName(byte[] resultData, int currentPosition, out int uncompressedLabelBytes) { List<string> labels = new List<string>(); bool isInUncompressedSpace = true; uncompressedLabelBytes = 0; for (int i = 0; i < 127; i++) // max is 127 labels (see RFC 2065) { byte currentByte = resultData[currentPosition++]; if (currentByte == 0) { // end of domain, RFC1035 if (isInUncompressedSpace) uncompressedLabelBytes += 1; return new DomainName(labels.ToArray()); } else if (currentByte >= 192) { // Pointer, RFC1035 if (isInUncompressedSpace) { uncompressedLabelBytes += 2; isInUncompressedSpace = false; } int pointer; if (BitConverter.IsLittleEndian) { pointer = (ushort) (((currentByte - 192) << 8) | resultData[currentPosition]); } else { pointer = (ushort) ((currentByte - 192) | (resultData[currentPosition] << 8)); } currentPosition = pointer; } else if (currentByte == 65) { // binary EDNS label, RFC2673, RFC3363, RFC3364 int length = resultData[currentPosition++]; if (isInUncompressedSpace) uncompressedLabelBytes += 1; if (length == 0) length = 256; StringBuilder sb = new StringBuilder(); sb.Append(@"\[x"); string suffix = "/" + length + "]"; do { currentByte = resultData[currentPosition++]; if (isInUncompressedSpace) uncompressedLabelBytes += 1; if (length < 8) { currentByte &= (byte) (0xff >> (8 - length)); } sb.Append(currentByte.ToString("x2")); length = length - 8; } while (length > 0); sb.Append(suffix); labels.Add(sb.ToString()); } else if (currentByte >= 64) { // extended dns label RFC 2671 throw new NotSupportedException("Unsupported extended dns label"); } else { // append additional text part if (isInUncompressedSpace) uncompressedLabelBytes += 1 + currentByte; labels.Add(Encoding.ASCII.GetString(resultData, currentPosition, currentByte)); currentPosition += currentByte; } } throw new FormatException("Domain name could not be parsed. Invalid message?"); } internal static byte[] ParseByteData(byte[] resultData, ref int currentPosition, int length) { if (length == 0) { return new byte[] { }; } else { byte[] res = new byte[length]; Buffer.BlockCopy(resultData, currentPosition, res, 0, length); currentPosition += length; return res; } } #endregion #endregion #region Serializing protected virtual void PrepareEncoding() {} internal int Encode(bool addLengthPrefix, out byte[] messageData) { byte[] newTSigMac; return Encode(addLengthPrefix, null, false, out messageData, out newTSigMac); } internal int Encode(bool addLengthPrefix, byte[] originalTsigMac, out byte[] messageData) { byte[] newTSigMac; return Encode(addLengthPrefix, originalTsigMac, false, out messageData, out newTSigMac); } internal int Encode(bool addLengthPrefix, byte[] originalTsigMac, bool isSubSequentResponse, out byte[] messageData, out byte[] newTSigMac) { PrepareEncoding(); int offset = 0; int messageOffset = offset; int maxLength = addLengthPrefix ? 2 : 0; originalTsigMac = originalTsigMac ?? new byte[] { }; if (TSigOptions != null) { if (!IsQuery) { offset += 2 + originalTsigMac.Length; maxLength += 2 + originalTsigMac.Length; } maxLength += TSigOptions.MaximumLength; } #region Get Message Length maxLength += 12; maxLength += Questions.Sum(question => question.MaximumLength); maxLength += AnswerRecords.Sum(record => record.MaximumLength); maxLength += AuthorityRecords.Sum(record => record.MaximumLength); maxLength += _additionalRecords.Sum(record => record.MaximumLength); #endregion messageData = new byte[maxLength]; int currentPosition = offset; Dictionary<DomainName, ushort> domainNames = new Dictionary<DomainName, ushort>(); EncodeUShort(messageData, ref currentPosition, TransactionID); EncodeUShort(messageData, ref currentPosition, Flags); EncodeUShort(messageData, ref currentPosition, (ushort) Questions.Count); EncodeUShort(messageData, ref currentPosition, (ushort) AnswerRecords.Count); EncodeUShort(messageData, ref currentPosition, (ushort) AuthorityRecords.Count); EncodeUShort(messageData, ref currentPosition, (ushort) _additionalRecords.Count); foreach (DnsQuestion question in Questions) { question.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in AnswerRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in AuthorityRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in _additionalRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } if (TSigOptions == null) { newTSigMac = null; } else { if (!IsQuery) { EncodeUShort(messageData, messageOffset, (ushort) originalTsigMac.Length); Buffer.BlockCopy(originalTsigMac, 0, messageData, messageOffset + 2, originalTsigMac.Length); } EncodeUShort(messageData, offset, TSigOptions.OriginalID); int tsigVariablesPosition = currentPosition; if (isSubSequentResponse) { TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Fudge.TotalSeconds); } else { EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigOptions.Name, null, false); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.RecordClass); EncodeInt(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.TimeToLive); EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), null, false); TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Fudge.TotalSeconds); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Error); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.OtherData.Length); EncodeByteArray(messageData, ref tsigVariablesPosition, TSigOptions.OtherData); } KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm); if ((hashAlgorithm != null) && (TSigOptions.KeyData != null) && (TSigOptions.KeyData.Length > 0)) { hashAlgorithm.Key = TSigOptions.KeyData; newTSigMac = hashAlgorithm.ComputeHash(messageData, messageOffset, tsigVariablesPosition); } else { newTSigMac = new byte[] { }; } EncodeUShort(messageData, offset, TransactionID); EncodeUShort(messageData, offset + 10, (ushort) (_additionalRecords.Count + 1)); TSigOptions.Encode(messageData, offset, ref currentPosition, domainNames, newTSigMac); if (!IsQuery) { Buffer.BlockCopy(messageData, offset, messageData, messageOffset, (currentPosition - offset)); currentPosition -= (2 + originalTsigMac.Length); } } if (addLengthPrefix) { Buffer.BlockCopy(messageData, 0, messageData, 2, currentPosition); EncodeUShort(messageData, 0, (ushort) (currentPosition)); currentPosition += 2; } return currentPosition; } internal static void EncodeUShort(byte[] buffer, int currentPosition, ushort value) { EncodeUShort(buffer, ref currentPosition, value); } internal static void EncodeUShort(byte[] buffer, ref int currentPosition, ushort value) { if (BitConverter.IsLittleEndian) { buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); buffer[currentPosition++] = (byte) (value & 0xff); } else { buffer[currentPosition++] = (byte) (value & 0xff); buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); } } internal static void EncodeInt(byte[] buffer, ref int currentPosition, int value) { if (BitConverter.IsLittleEndian) { buffer[currentPosition++] = (byte) ((value >> 24) & 0xff); buffer[currentPosition++] = (byte) ((value >> 16) & 0xff); buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); buffer[currentPosition++] = (byte) (value & 0xff); } else { buffer[currentPosition++] = (byte) (value & 0xff); buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); buffer[currentPosition++] = (byte) ((value >> 16) & 0xff); buffer[currentPosition++] = (byte) ((value >> 24) & 0xff); } } internal static void EncodeUInt(byte[] buffer, ref int currentPosition, uint value) { if (BitConverter.IsLittleEndian) { buffer[currentPosition++] = (byte) ((value >> 24) & 0xff); buffer[currentPosition++] = (byte) ((value >> 16) & 0xff); buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); buffer[currentPosition++] = (byte) (value & 0xff); } else { buffer[currentPosition++] = (byte) (value & 0xff); buffer[currentPosition++] = (byte) ((value >> 8) & 0xff); buffer[currentPosition++] = (byte) ((value >> 16) & 0xff); buffer[currentPosition++] = (byte) ((value >> 24) & 0xff); } } internal static void EncodeULong(byte[] buffer, ref int currentPosition, ulong value) { if (BitConverter.IsLittleEndian) { EncodeUInt(buffer, ref currentPosition, (uint) ((value >> 32) & 0xffffffff)); EncodeUInt(buffer, ref currentPosition, (uint) (value & 0xffffffff)); } else { EncodeUInt(buffer, ref currentPosition, (uint) (value & 0xffffffff)); EncodeUInt(buffer, ref currentPosition, (uint) ((value >> 32) & 0xffffffff)); } } internal static void EncodeDomainName(byte[] messageData, int offset, ref int currentPosition, DomainName name, Dictionary<DomainName, ushort> domainNames, bool useCanonical) { if (name.LabelCount == 0) { messageData[currentPosition++] = 0; return; } bool isCompressionAllowed = !useCanonical & (domainNames != null); ushort pointer; if (isCompressionAllowed && domainNames.TryGetValue(name, out pointer)) { EncodeUShort(messageData, ref currentPosition, pointer); return; } string label = name.Labels[0]; if (isCompressionAllowed) domainNames[name] = (ushort) ((currentPosition | 0xc000) - offset); messageData[currentPosition++] = (byte) label.Length; if (useCanonical) label = label.ToLowerInvariant(); EncodeByteArray(messageData, ref currentPosition, Encoding.ASCII.GetBytes(label)); EncodeDomainName(messageData, offset, ref currentPosition, name.GetParentName(), domainNames, useCanonical); } internal static void EncodeTextBlock(byte[] messageData, ref int currentPosition, string text) { byte[] textData = Encoding.ASCII.GetBytes(text); for (int i = 0; i < textData.Length; i += 255) { int blockLength = Math.Min(255, (textData.Length - i)); messageData[currentPosition++] = (byte) blockLength; Buffer.BlockCopy(textData, i, messageData, currentPosition, blockLength); currentPosition += blockLength; } } internal static void EncodeTextWithoutLength(byte[] messageData, ref int currentPosition, string text) { byte[] textData = Encoding.ASCII.GetBytes(text); Buffer.BlockCopy(textData, 0, messageData, currentPosition, textData.Length); currentPosition += textData.Length; } internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data) { if (data != null) { EncodeByteArray(messageData, ref currentPosition, data, data.Length); } } internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data, int length) { if ((data != null) && (length > 0)) { Buffer.BlockCopy(data, 0, messageData, currentPosition, length); currentPosition += length; } } #endregion } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // 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 FluentAssertions; using System.Collections; using Xunit; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace YamlDotNet.Test.Core { public class ParserTests : EventsHelper { [Fact] public void EmptyDocument() { AssertSequenceOfEventsFrom(Yaml.ParserForEmptyContent(), StreamStart, StreamEnd); } [Fact] public void VerifyEventsOnExample1() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("01-directives.yaml"), StreamStart, DocumentStart(Explicit, Version(1, 1), TagDirective("!", "!foo"), TagDirective("!yaml!", TagYaml), TagDirective("!!", TagYaml)), PlainScalar(string.Empty), DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample2() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("02-scalar-in-imp-doc.yaml"), StreamStart, DocumentStart(Implicit), SingleQuotedScalar("a scalar"), DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample3() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("03-scalar-in-exp-doc.yaml"), StreamStart, DocumentStart(Explicit), SingleQuotedScalar("a scalar"), DocumentEnd(Explicit), StreamEnd); } [Fact] public void VerifyTokensOnExample4() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("04-scalars-in-multi-docs.yaml"), StreamStart, DocumentStart(Implicit), SingleQuotedScalar("a scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), SingleQuotedScalar("another scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), SingleQuotedScalar("yet another scalar"), DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample5() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("05-circular-sequence.yaml"), StreamStart, DocumentStart(Implicit), FlowSequenceStart.A("A"), AnchorAlias("A"), SequenceEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample6() { var parser = Yaml.ParserForResource("06-float-tag.yaml"); AssertSequenceOfEventsFrom(parser, StreamStart, DocumentStart(Implicit), DoubleQuotedScalar("3.14").T(TagYaml + "float"), DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample7() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("07-scalar-styles.yaml"), StreamStart, DocumentStart(Explicit), PlainScalar(string.Empty), DocumentEnd(Implicit), DocumentStart(Explicit), PlainScalar("a plain scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), SingleQuotedScalar("a single-quoted scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), DoubleQuotedScalar("a double-quoted scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), LiteralScalar("a literal scalar"), DocumentEnd(Implicit), DocumentStart(Explicit), FoldedScalar("a folded scalar"), DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample8() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("08-flow-sequence.yaml"), StreamStart, DocumentStart(Implicit), FlowSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), PlainScalar("item 3"), SequenceEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample9() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("09-flow-mapping.yaml"), StreamStart, DocumentStart(Implicit), FlowMappingStart, PlainScalar("a simple key"), PlainScalar("a value"), PlainScalar("a complex key"), PlainScalar("another value"), MappingEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample10() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("10-mixed-nodes-in-sequence.yaml"), StreamStart, DocumentStart(Implicit), BlockSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), BlockSequenceStart, PlainScalar("item 3.1"), PlainScalar("item 3.2"), SequenceEnd, BlockMappingStart, PlainScalar("key 1"), PlainScalar("value 1"), PlainScalar("key 2"), PlainScalar("value 2"), MappingEnd, SequenceEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample11() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("11-mixed-nodes-in-mapping.yaml"), StreamStart, DocumentStart(Implicit), BlockMappingStart, PlainScalar("a simple key"), PlainScalar("a value"), PlainScalar("a complex key"), PlainScalar("another value"), PlainScalar("a mapping"), BlockMappingStart, PlainScalar("key 1"), PlainScalar("value 1"), PlainScalar("key 2"), PlainScalar("value 2"), MappingEnd, PlainScalar("a sequence"), BlockSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), SequenceEnd, MappingEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample12() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("12-compact-sequence.yaml"), StreamStart, DocumentStart(Implicit), BlockSequenceStart, BlockSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), SequenceEnd, BlockMappingStart, PlainScalar("key 1"), PlainScalar("value 1"), PlainScalar("key 2"), PlainScalar("value 2"), MappingEnd, BlockMappingStart, PlainScalar("complex key"), PlainScalar("complex value"), MappingEnd, SequenceEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample13() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("13-compact-mapping.yaml"), StreamStart, DocumentStart(Implicit), BlockMappingStart, PlainScalar("a sequence"), BlockSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), SequenceEnd, PlainScalar("a mapping"), BlockMappingStart, PlainScalar("key 1"), PlainScalar("value 1"), PlainScalar("key 2"), PlainScalar("value 2"), MappingEnd, MappingEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokensOnExample14() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("14-mapping-wo-indent.yaml"), StreamStart, DocumentStart(Implicit), BlockMappingStart, PlainScalar("key"), BlockSequenceStart, PlainScalar("item 1"), PlainScalar("item 2"), SequenceEnd, MappingEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void VerifyTokenWithLocalTags() { AssertSequenceOfEventsFrom(Yaml.ParserForResource("local-tags.yaml"), StreamStart, DocumentStart(Explicit), BlockMappingStart.T("!MyObject").Explicit, PlainScalar("a"), PlainScalar("1.0"), PlainScalar("b"), PlainScalar("42"), PlainScalar("c"), PlainScalar("-7"), MappingEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void CommentsAreReturnedWhenRequested() { AssertSequenceOfEventsFrom(new Parser(new Scanner(Yaml.ReaderForText(@" # Top comment - first # Comment on first item - second - # a mapping ? key # my key : value # my value # Bottom comment "), skipComments: false)), StreamStart, StandaloneComment("Top comment"), DocumentStart(Implicit), BlockSequenceStart, PlainScalar("first"), InlineComment("Comment on first item"), PlainScalar("second"), InlineComment("a mapping"), BlockMappingStart, PlainScalar("key"), InlineComment("my key"), PlainScalar("value"), InlineComment("my value"), StandaloneComment("Bottom comment"), MappingEnd, SequenceEnd, DocumentEnd(Implicit), StreamEnd); } [Fact] public void CommentsAreOmittedUnlessRequested() { AssertSequenceOfEventsFrom(Yaml.ParserForText(@" # Top comment - first # Comment on first item - second - # a mapping ? key # my key : value # my value # Bottom comment "), StreamStart, DocumentStart(Implicit), BlockSequenceStart, PlainScalar("first"), PlainScalar("second"), BlockMappingStart, PlainScalar("key"), PlainScalar("value"), MappingEnd, SequenceEnd, DocumentEnd(Implicit), StreamEnd); } private void AssertSequenceOfEventsFrom(IParser parser, params ParsingEvent[] events) { var eventNumber = 1; foreach (var expected in events) { parser.MoveNext().Should().BeTrue("Missing parse event number {0}", eventNumber); AssertEvent(expected, parser.Current, eventNumber); eventNumber++; } parser.MoveNext().Should().BeFalse("Found extra parse events"); } private void AssertEvent(ParsingEvent expected, ParsingEvent actual, int eventNumber) { actual.GetType().Should().Be(expected.GetType(), "Parse event {0} is not of the expected type.", eventNumber); foreach (var property in expected.GetType().GetProperties()) { if (property.PropertyType == typeof(Mark) || !property.CanRead) { continue; } var value = property.GetValue(actual, null); var expectedValue = property.GetValue(expected, null); if (expectedValue is IEnumerable && !(expectedValue is string)) { Dump.Write("\t{0} = {{", property.Name); Dump.Write(string.Join(", ", (IEnumerable)value)); Dump.WriteLine("}"); if (expectedValue is ICollection && value is ICollection) { var expectedCount = ((ICollection)expectedValue).Count; var valueCount = ((ICollection)value).Count; valueCount.Should().Be(expectedCount, "Compared size of collections in property {0} in parse event {1}", property.Name, eventNumber); } var values = ((IEnumerable)value).GetEnumerator(); var expectedValues = ((IEnumerable)expectedValue).GetEnumerator(); while (expectedValues.MoveNext()) { values.MoveNext().Should().BeTrue("Property {0} in parse event {1} had too few elements", property.Name, eventNumber); values.Current.Should().Be(expectedValues.Current, "Compared element in property {0} in parse event {1}", property.Name, eventNumber); } values.MoveNext().Should().BeFalse("Property {0} in parse event {1} had too many elements", property.Name, eventNumber); } else { Dump.WriteLine("\t{0} = {1}", property.Name, value); value.Should().Be(expectedValue, "Compared property {0} in parse event {1}", property.Name, eventNumber); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net.Http; using System.Threading.Tasks; using System.Net.Http.Headers; using Discord; using Discord.WebSocket; using Discord.Commands; using Discord.Addons.Interactive; using Newtonsoft.Json; using Nero.Modules.Utilities; namespace Nero { [Group("static")] [Alias("s")] public partial class LFG : InteractiveBase { //private readonly PaginationService paginator; //public LFG(PaginationService _paginator) { // paginator = _paginator; //} [Command("create", RunMode = RunMode.Async)] [Alias("c")] public async Task CreateStatic() { await Context.User.SendMessageAsync("Welcome to the Static Setup Wizard. Next, please invite the bot (use the command `!n invite bot` for a link) to your static's discord server **(MAKE SURE that the name of the static and the server match for this)** and select yes for the question asking if it's for a static. Type next to continue"); var goNextResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if (goNextResponse.Content.ToLower() == "next") { // Static Name await Context.User.SendMessageAsync("Please input your static name (**NOTE** Must match static discord name)"); var staticNameResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); // Static Datacenter await Context.User.SendMessageAsync("Please enter the datacenter (primal, chaos, aether, etc) where your static is located: "); var staticDCResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if(staticDCResponse.Content.ToLower() != "primal" && staticDCResponse.Content.ToLower() != "aether" && staticDCResponse.Content.ToLower() != "elemental" && staticDCResponse.Content.ToLower() != "gaia" && staticDCResponse.Content.ToLower() != "chaos" && staticDCResponse.Content.ToLower() != "mana") { await Context.User.SendMessageAsync("Thats not a datacenter, (primal, chaos, aether, etc) try again: "); staticDCResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); } // Gets the Server, probably should refactor this var serv = Context.Client.Guilds; var results = from server in serv where server.Name.ToLower().Contains(staticNameResponse.Content.ToLower()) select server; if (results.Count() == 0) { await Context.User.SendMessageAsync($"Error: Static server `{staticNameResponse.Content}` not found, are you sure you added Nero to it?"); return; } // Loads the server and player objects to set the player static ID ulong seId = results.First().Id; Server serpento = Server.Load(seId); var player = Player.Load(Context.User.Id); player.staticId = serpento.discordServerID; player.EnsureExists(); // Creates the Static Object PlayerStatic ps = new PlayerStatic(results.First().Id, staticNameResponse.Content.ToLower(), staticDCResponse.Content.ToLower(), Context.User.Id, serpento.invite); // Gets the recruitment filters from the user await Context.User.SendMessageAsync("Please input any recruiting filters you want seperated by commas, these can be changed later. Filter List: `job`, `cleared-o#s`\nTo skip this type **skip**"); var filterResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if (!filterResponse.Content.ToLower().Contains("skip")) { var filterList = filterResponse.Content.ToLower().Split(',').ToList(); ps.Filters = filterList; } // Recruitment await Context.User.SendMessageAsync("Enable Recruitment? This can be enabled later. Y/N"); var recruitmentResponse = await NextMessageAsync(true, false, timeout:TimeSpan.FromMinutes(5)); if (recruitmentResponse.Content.ToLower() == "y") { ps.recruiting = true; } await Context.User.SendMessageAsync("Recruitment set"); // Adds the Creator to the Member List ps.Members.Add(Context.User.Username, Context.User.Id); ps.EnsureExists(); await Context.User.SendMessageAsync("Static setup Complete.\nNow instruct your members to use the command !n static join to start the wizard. Nero will then dm you for approval before sending them a server invite."); } } [Command("recruitment", RunMode = RunMode.Async)] [Alias("r")] public async Task RecruitmentToggle() { var player = Player.Load(Context.User.Id); PlayerStatic ps = ListOwnerServers(Context).Result; if (ps.recruiting == true) { await Context.User.SendMessageAsync($"Recruitment is **Enabled** for {ps.PlayerStaticName}"); } else { await Context.User.SendMessageAsync($"Recruitment is **Disabled** for {ps.PlayerStaticName}"); } await Context.User.SendMessageAsync("Type On to enable Recruitment, Off to Disable recruitment or Exit to exit this prompt"); var recruitmentResponse = await NextMessageAsync(true, false, timeout:TimeSpan.FromMinutes(5)); if (recruitmentResponse.Content.ToLower() == "on") { ps.recruiting = true; ps.EnsureExists(); await Context.User.SendMessageAsync("Recruitment is now **Enabled**"); } else if (recruitmentResponse.Content.ToLower() == "off") { ps.recruiting = false; ps.EnsureExists(); await Context.User.SendMessageAsync("Recruitment is now **Disabled**"); } else { return; } } [Command("view", RunMode = RunMode.Async)] [Alias("v")] public async Task ViewStatic() { var player = Player.Load(Context.User.Id); if(player.staticId == 0) { await Context.User.SendMessageAsync("You are not in a static"); return; } PlayerStatic ps = ListOwnerServersInChannel(Context).Result; var reply = ""; foreach (var member in ps.Members) { if(Player.DoesProfileExist(member.Value)) { var membah = Player.Load(member.Value); reply += $"{membah.playerName} - "; var cleared = membah.GetClearedFights(); foreach (var clear in cleared) { reply += $"{clear} "; } reply += "\n"; } else { reply += $"{member.Key}\n"; } } var embed = new EmbedBuilder() .WithTitle(ps.PlayerStaticName) .WithColor(new Color(250, 140, 73)) .WithDescription(reply) .WithFooter(new EmbedFooterBuilder() .WithText($"{ps.Applications.Count()} pending application(s)")) .Build(); await ReplyAsync("", embed: embed); } [Command("filters", RunMode = RunMode.Async)] [Alias("f")] public async Task UpdateFilters() { var player = Player.Load(Context.User.Id); PlayerStatic ps = ListOwnerServers(Context).Result; var reply = ""; if (ps.Filters != null) { foreach(var filt in ps.Filters) { reply += $"{filt}\n"; } } await Context.User.SendMessageAsync($"Current Filters for {ps.PlayerStaticName}:\n{reply}\nPlease input new filters seperated by commas. Available filters: `job`, `cleared-o#s`\nThe old filters are overwritten\nTo exit type **exit**"); if (ps.Filters != null){ ps.Filters.Clear(); } var filterResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if(filterResponse.Content.ToLower() == "exit") { await Context.User.SendMessageAsync("exiting"); return; } var filterList = filterResponse.Content.ToLower().Split(',').ToList(); ps.Filters = filterList; ps.EnsureExists(); await Context.User.SendMessageAsync("Filters set"); } [Command("join", RunMode = RunMode.Async)] [Alias("j")] public async Task JoinStatic() { if (Player.DoesProfileExist(Context.User.Id) == false) { await Context.User.SendMessageAsync("Please run the command !n add profile `world` `firstname lastname` first."); return; } await Context.User.SendMessageAsync("Greetings! Please input the name of the static(case insensitive) you wish to join: "); var staticNameR = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); var serv = Context.Client.Guilds; var results = from server in serv where server.Name.ToLower().Contains(staticNameR.Content.ToLower()) select server; if (results.Count() == 0) { await Context.User.SendMessageAsync($"Error: Static server `{staticNameR.Content} not found"); return; } PlayerStatic ps = PlayerStatic.Load(results.First().Id); Player playa = Player.Load(Context.User.Id); if (playa.dc.ToLower() != ps.dc.ToLower()) { await Context.User.SendMessageAsync($"You are not located in the {ps.dc} datacenter"); } if (!ps.Applications.ContainsValue(Context.User.Id) && !ps.Members.ContainsValue(Context.User.Id)) { if (ps.Filters.Count == 0) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Console.WriteLine("sending profile"); Embed embed = await fflogs.SendProfileReply(Context.User.Id); Console.WriteLine("profile sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { foreach(var filt in ps.Filters) { //Job Filter if (filt.Length == 3) { foreach (var jb in playa.jobs) { if (filt.ToLower() == jb.short_name) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Embed embed = await fflogs.SendProfileReply(Context.User.Id); await Context.User.SendMessageAsync("Application sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { await Context.User.SendMessageAsync("Requirements not met"); } } } // Cleared Fights Filter else { foreach(var clrd in playa.cleared) { if (filt.ToLower().Contains(clrd.ToLower())) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Embed embed = await fflogs.SendProfileReply(Context.User.Id); await Context.User.SendMessageAsync("Application sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { await Context.User.SendMessageAsync("Requirements not met"); } } } } } } else { await Context.User.SendMessageAsync($"You are either already a member of {ps.PlayerStaticName} or have already sent in an application"); } } [Command("join", RunMode = RunMode.Async)] [Alias("j")] public async Task JoinStatic([Remainder] string input) { if (Player.DoesProfileExist(Context.User.Id) == false) { await Context.User.SendMessageAsync("Please run the command !n add profile `world` `firstname lastname` first."); return; } var staticNameR = input; var serv = Context.Client.Guilds; var results = from server in serv where server.Name.ToLower().Contains(staticNameR.ToLower()) select server; if (results.Count() == 0) { await Context.User.SendMessageAsync($"Error: Static server `{staticNameR} not found"); return; } PlayerStatic ps = PlayerStatic.Load(results.First().Id); Player playa = Player.Load(Context.User.Id); if (playa.dc.ToLower() != ps.dc.ToLower()) { await Context.User.SendMessageAsync($"You are not located in the {ps.dc} datacenter"); } if (!ps.Applications.ContainsValue(Context.User.Id) && !ps.Members.ContainsValue(Context.User.Id)) { if (ps.Filters.Count == 0) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Console.WriteLine("sending profile"); Embed embed = await fflogs.SendProfileReply(Context.User.Id); Console.WriteLine("profile sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { foreach(var filt in ps.Filters) { //Job Filter if (filt.Length == 3) { foreach (var jb in playa.jobs) { if (filt.ToLower() == jb.short_name) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Embed embed = await fflogs.SendProfileReply(Context.User.Id); await Context.User.SendMessageAsync("Application sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { await Context.User.SendMessageAsync("Requirements not met"); } } } // Cleared Fights Filter else { foreach(var clrd in playa.cleared) { if (filt.ToLower().Contains(clrd.ToLower())) { ps.Applications.Add(Context.User.Username.ToLower(), Context.User.Id); ps.EnsureExists(); var fflogs = new fflogs(); Embed embed = await fflogs.SendProfileReply(Context.User.Id); await Context.User.SendMessageAsync("Application sent"); await results.First().Owner.SendMessageAsync($"New Application from {Context.User.Username}, use !n static applications to approve/deny the application", embed: embed); } else { await Context.User.SendMessageAsync("Requirements not met"); } } } } } } else { await Context.User.SendMessageAsync($"You are either already a member of {ps.PlayerStaticName} or have already sent in an application"); } } [Command("applications", RunMode = RunMode.Async)] [Alias("a")] public async Task Applications() { var playe = Player.Load(Context.User.Id); PlayerStatic ps = ListOwnerServers(Context).Result; string reply = ""; int i=0; foreach (var app in ps.Applications) { reply += $" **{i}**. {app.Key}\n"; Console.WriteLine($""); i++; } await Context.User.SendMessageAsync($"Greetings! here are the Current applications for {ps.PlayerStaticName}: \n{reply}\n type approve or deny to launch a prompt.\n"); var response = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); //Approve if (response.Content.ToLower().Contains("approve")) { await Context.User.SendMessageAsync("Type one or more names seperated by commas to approve them, or type `all` to approve all applicants"); var approveResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if (approveResponse.Content.Contains(',')) { var approveList = approveResponse.Content.Split(',').ToList(); foreach (var approve in approveList) { ulong value = ps.Applications[approve.ToLower()]; ps.Members.Add(approve.ToLower(), value); ps.Applications.Remove(approve.ToLower()); var usr = Context.Client.GetUser(value); var player = Player.Load(usr.Id); player.staticId = ps.discordServerID; player.EnsureExists(); await usr.SendMessageAsync($"Your Application to join {ps.PlayerStaticName} has been approved, click here to join: {ps.InviteLink}"); } ps.EnsureExists(); } else { if (approveResponse.Content.ToLower().Substring(0,3) == "all") { foreach (var approved in ps.Applications) { ps.Members.Add(approved.Key, approved.Value); var usr = Context.Client.GetUser(approved.Value); var player = Player.Load(usr.Id); player.staticId = ps.discordServerID; player.EnsureExists(); await usr.SendMessageAsync($"Your Application to join {ps.PlayerStaticName} has been approved, click here to join: {ps.InviteLink}"); } ps.Applications.Clear(); ps.EnsureExists(); } else { ulong value = ps.Applications[approveResponse.Content.ToLower()]; ps.Members.Add(approveResponse.Content.ToLower(), value); ps.Applications.Remove(approveResponse.Content.ToLower()); var usr = Context.Client.GetUser(value); var player = Player.Load(usr.Id); player.staticId = ps.discordServerID; player.EnsureExists(); await usr.SendMessageAsync($"Your Application to join {ps.PlayerStaticName} has been approved, click here to join: {ps.InviteLink}"); ps.EnsureExists(); } } } //Deny else if (response.Content.ToLower().Contains("deny")) { await Context.User.SendMessageAsync("Type one or more names seperated by commas to deny them, or type `all` to deny all applicants"); var denyResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); if (denyResponse.Content.ToLower().Contains(',')) { var denyList = denyResponse.Content.Split(',').ToList(); foreach (var deny in denyList) { ulong value = ps.Applications[deny.ToLower()]; ps.Members.Add(deny.ToLower(), value); ps.Applications.Remove(deny.ToLower()); } ps.EnsureExists(); await Context.User.SendMessageAsync("Selected applications cleared."); } else { if (denyResponse.Content.ToLower().Substring(0,3) == "all") { ps.Applications.Clear(); ps.EnsureExists(); await Context.User.SendMessageAsync("Applications cleared."); } else { ulong value = ps.Applications[denyResponse.Content.ToLower()]; ps.Applications.Remove(denyResponse.Content.ToLower()); ps.EnsureExists(); } } } } [Command("kick", RunMode = RunMode.Async)] [Alias("k")] public async Task Memberkick() { var playe = Player.Load(Context.User.Id); ulong playerID = 0; PlayerStatic ps = ListOwnerServers(Context).Result; string reply = ""; int i=1; foreach (var member in ps.Members) { reply += $" **{i}**. {member.Key}\n"; Console.WriteLine($""); i++; } await Context.User.SendMessageAsync($"Greetings! here are the current members for {ps.PlayerStaticName}: \n{reply}\n type in a players number to kick them\n"); var kickResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); int responseInt = Convert.ToInt32(kickResponse.Content); var membID = ps.Members.ElementAt(responseInt-1).Value; var membname = ps.Members.ElementAt(responseInt-1).Key; ps.Members.Remove(ps.Members.ElementAt(responseInt-1).Key); ps.EnsureExists(); var targetServ = Context.Client.GetGuild(ps.discordServerID); var botInstance = targetServ.GetUser(Context.Client.CurrentUser.Id); var targetMember = targetServ.GetUser(membID); if (botInstance.GuildPermissions.KickMembers) { if (targetServ.OwnerId == targetMember.Id){ await Context.User.SendMessageAsync("Nero can not kick the owner of that server."); return; } await targetMember.KickAsync(); await ReplyAsync("Nero kicked " + membname); } } [Command("search", RunMode = RunMode.Async)] [Alias("s")] public async Task SearchStatics([Remainder] string input) { var reply = new List<string>(); reply.Add(""); var files = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, $"statics/")); int i=0; int pageIndex = 0; foreach(var file in files) { ulong servId = Convert.ToUInt64(Path.GetFileNameWithoutExtension(file)); var ps = PlayerStatic.Load(servId); if(ps.recruiting == true) { if (ps.PlayerStaticName.ToLower().Contains(input.ToLower())) { if ((i % 10 == 0 && i != 1 && i != 0)) { reply.Add($"{ps.PlayerStaticName}\n"); i++; pageIndex++; } else { reply[pageIndex] += ps.PlayerStaticName + "\n"; i++; } } } } var message = new Discord.Addons.Interactive.PaginatedMessage(); message.Title = $"{files.Count()} Statics"; message.Color = new Color(250, 140, 73); message.Pages = reply; await PagedReplyAsync(reply); } [Command("list", RunMode = RunMode.Async)] [Alias("l")] public async Task ListStatics() { var reply = new List<string>(); reply.Add(""); var files = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, $"statics/")); int i=0; int pageIndex = 0; foreach(var file in files) { ulong servId = Convert.ToUInt64(Path.GetFileNameWithoutExtension(file)); var ps = PlayerStatic.Load(servId); if(ps.recruiting == true) { if ((i % 10 == 0 && i != 1 && i != 0)) { reply.Add($"{ps.PlayerStaticName}\n"); i++; pageIndex++; } else { reply[pageIndex] += ps.PlayerStaticName + "\n"; i++; } } } var message = new Discord.Addons.Interactive.PaginatedMessage(); message.Title = $"{files.Count()} Statics"; message.Color = new Color(250, 140, 73); message.Pages = reply; await PagedReplyAsync(reply); } [Command("list", RunMode = RunMode.Async)] [Alias("l")] public async Task ListStaticsWithJobFilter([Remainder] string job) { var reply = new List<string>(); reply.Add(""); var files = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, $"statics/")); int i = 0; int pageIndex = 0; foreach(var file in files) { ulong servId = Convert.ToUInt64(Path.GetFileNameWithoutExtension(file)); var ps = PlayerStatic.Load(servId); if(ps.recruiting == true) { if (ps.Filters.Contains(job.ToLower())) { if ((i % 10 == 0 && i != 1 && i != 0)) { reply.Add($"{ps.PlayerStaticName}\n"); i++; pageIndex++; } else { reply[pageIndex] += ps.PlayerStaticName + "\n"; i++; } } } } Console.WriteLine($"{files.Count()} files found"); var message = new Discord.Addons.Interactive.PaginatedMessage(); message.Title = $"{files.Count()} Statics"; message.Color = new Color(250, 140, 73); message.Pages = reply; await PagedReplyAsync(reply); } public async Task<PlayerStatic> ListOwnerServers(SocketCommandContext Context) { ulong serverID = 0; string servers = ""; int k = 1; Dictionary<string, ulong> userControlledservers = new Dictionary<string, ulong>(); foreach (var g in Context.Client.Guilds) { if (Context.User.Id == g.Owner.Id){ if (PlayerStatic.DoesProfileExist(g.Id)) { userControlledservers.Add(g.Name, g.Id); servers += $" {k}. {g.Name} \n"; k++; } } } if(userControlledservers.Count > 1) { await Context.User.SendMessageAsync($"You control the following servers:\n{servers} Please enter the number of the server you want to select."); var serverNameResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); int responseInt = Convert.ToInt32(serverNameResponse.Content); serverID = userControlledservers.ElementAt(responseInt-1).Value; await Context.User.SendMessageAsync($"You have selected: **{userControlledservers.ElementAt(responseInt-1).Key}**"); } else { serverID = userControlledservers.Values.First(); } PlayerStatic ps = PlayerStatic.Load(serverID); return ps; } public async Task<PlayerStatic> ListOwnerServersInChannel(SocketCommandContext Context) { ulong serverID = 0; string servers = ""; int k = 1; Dictionary<string, ulong> userControlledservers = new Dictionary<string, ulong>(); foreach (var g in Context.Client.Guilds) { if (Context.User.Id == g.Owner.Id){ if (PlayerStatic.DoesProfileExist(g.Id)) { userControlledservers.Add(g.Name, g.Id); servers += $" * {g.Name} \n"; k++; } } } if(userControlledservers.Count > 1) { await ReplyAsync($"You control the following servers:\n{servers} Please enter the name of the server you want to select, it does not have to be the full name."); var serverNameResponse = await NextMessageAsync(true, false, timeout: TimeSpan.FromMinutes(5)); foreach(var u in userControlledservers) { if (u.Key.ToLower().Contains(serverNameResponse.Content.ToLower())) { serverID = u.Value; break; } } } else { serverID = userControlledservers.Values.First(); } PlayerStatic ps = PlayerStatic.Load(serverID); return ps; } } }
//----------------------------------------------------------------------- // <copyright company="nBuildKit"> // Copyright (c) nBuildKit. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NBuildKit.MsBuild.Tasks.Core; namespace NBuildKit.MsBuild.Tasks.Script { /// <summary> /// Defines a <see cref="ITask"/> that executes steps for nBuildKit. /// </summary> public sealed class InvokeSteps : BaseTask { private const string ErrorIdInvalidConfiguration = "NBuildKit.Steps.InvalidConfiguration"; private const string ErrorIdInvalidDependencies = "NBuildKit.Steps.InvalidDependencies"; private const string ErrorIdPostStepFailure = "NBuildKit.Steps.PostStep"; private const string ErrorIdPreStepFailure = "NBuildKit.Steps.PreStep"; private const string ErrorIdStepFailure = "NBuildKit.Steps.Failure"; private const string StepMetadataDescription = "StepDescription"; private const string StepMetadataId = "StepId"; private const string StepMetadataName = "StepName"; private const string StepMetadataPath = "StepPath"; private static Hashtable GetStepMetadata(string stepPath, ITaskItem[] metadata, bool isFirst, bool isLast) { const string MetadataTagDescription = "Description"; const string MetadataTagId = "Id"; const string MetadataTagName = "Name"; var stepFileName = Path.GetFileName(stepPath); var stepMetadata = metadata.FirstOrDefault(t => string.Equals(stepFileName, t.ItemSpec, StringComparison.OrdinalIgnoreCase)); var result = new Hashtable(StringComparer.OrdinalIgnoreCase); var description = stepMetadata != null ? stepMetadata.GetMetadata(MetadataTagDescription) : string.Empty; result.Add(StepMetadataDescription, description); var id = (stepMetadata != null) && !string.IsNullOrEmpty(stepMetadata.GetMetadata(MetadataTagId)) ? stepMetadata.GetMetadata(MetadataTagId) : stepFileName; result.Add(StepMetadataId, id); var name = (stepMetadata != null) && !string.IsNullOrEmpty(stepMetadata.GetMetadata(MetadataTagName)) ? stepMetadata.GetMetadata(MetadataTagName) : stepFileName; result.Add(StepMetadataName, name); result.Add(StepMetadataPath, stepPath); result.Add("IsFirstStep", isFirst.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture)); result.Add("IsLastStep", isLast.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture)); return result; } private static StepId[] ExecuteAfter(ITaskItem step) { const string MetadataTag = "ExecuteAfter"; var idsText = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTag)) ? step.GetMetadata(MetadataTag) : string.Empty; var ids = idsText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); return ids.Select(id => new StepId(id)).ToArray(); } private static StepId[] ExecuteBefore(ITaskItem step) { const string MetadataTag = "ExecuteBefore"; var idsText = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTag)) ? step.GetMetadata(MetadataTag) : string.Empty; var ids = idsText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); return ids.Select(id => new StepId(id)).ToArray(); } private static ITaskItem[] LocalPreSteps(ITaskItem step) { const string MetadataTag = "PreSteps"; var steps = step.GetMetadata(MetadataTag); return steps.Split(';').Select(s => new TaskItem(s)).ToArray(); } private static ITaskItem[] LocalPostSteps(ITaskItem step) { const string MetadataTag = "PostSteps"; var steps = step.GetMetadata(MetadataTag); return steps.Split(';').Select(s => new TaskItem(s)).ToArray(); } private static IEnumerable<string> StepGroups(ITaskItem step) { const string MetadataTag = "Groups"; var groups = step.GetMetadata(MetadataTag); return groups.ToLower(CultureInfo.InvariantCulture).Split(';'); } private static StepId StepId(ITaskItem step) { const string MetadataTagId = "Id"; var id = (step != null) && !string.IsNullOrEmpty(step.GetMetadata(MetadataTagId)) ? step.GetMetadata(MetadataTagId) : step.ItemSpec; return new StepId(id); } private void AddStepMetadata(ITaskItem subStep, string stepPath, ITaskItem[] metadata, bool isFirst, bool isLast) { const string MetadataTag = "Properties"; var stepMetadata = GetStepMetadata(stepPath, metadata, isFirst, isLast); var stepProperties = subStep.GetMetadata(MetadataTag); if (!string.IsNullOrEmpty(stepProperties)) { Hashtable additionalProjectPropertiesTable = null; if (!PropertyParser.GetTableWithEscaping(new MsBuildLogger(Log), "AdditionalProperties", "AdditionalProperties", stepProperties.Split(';'), out additionalProjectPropertiesTable)) { // Ignore it ... } foreach (DictionaryEntry entry in additionalProjectPropertiesTable) { if (!stepMetadata.ContainsKey(entry.Key)) { stepMetadata.Add(entry.Key, entry.Value); } } } // Turn the hashtable into a properties string again. var builder = new StringBuilder(); foreach (DictionaryEntry entry in stepMetadata) { builder.Append( string.Format( CultureInfo.InvariantCulture, "{0}={1};", entry.Key, EscapingUtilities.UnescapeAll(entry.Value as string))); } subStep.SetMetadata(MetadataTag, builder.ToString()); } /// <inheritdoc/> [SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catching, logging and letting MsBuild deal with the fall out")] public override bool Execute() { if ((Projects == null) || (Projects.Length == 0)) { return true; } // Get groups and determine which steps should be executed var hasFailed = false; var groups = Groups().Select(s => s.ToLower(CultureInfo.InvariantCulture).Trim()); var stepsToExecute = new List<ITaskItem>(); foreach (var step in Projects) { var stepGroups = StepGroups(step); if (!ShouldExecuteStep(groups, stepGroups)) { Log.LogMessage( MessageImportance.Low, "Step {0} has tags {1} none of which are included in execution list of {2}.", step.ItemSpec, string.Join(", ", stepGroups), string.Join(", ", groups)); continue; } stepsToExecute.Add(step); } var orderedStepsToExecute = OrderSteps(stepsToExecute); if (orderedStepsToExecute == null) { return false; } Log.LogMessage( MessageImportance.Normal, "Executing steps in the following order: "); for (int i = 0; i < orderedStepsToExecute.Count; i++) { var step = orderedStepsToExecute[i]; var metadata = GetStepMetadata(step.ItemSpec, StepMetadata, false, false); Log.LogMessage( MessageImportance.Normal, "{0} - {1}: {2}", i, metadata.ContainsKey(StepMetadataName) ? ((string)metadata[StepMetadataName]).Trim() : step.ItemSpec, metadata.ContainsKey(StepMetadataDescription) ? ((string)metadata[StepMetadataDescription]).Trim() : string.Empty); } for (int i = 0; i < orderedStepsToExecute.Count; i++) { var step = orderedStepsToExecute[i]; try { if (!ExecuteStep(step, i == 0, i == orderedStepsToExecute.Count - 1)) { hasFailed = true; if (StopOnFirstFailure) { break; } } } catch (Exception e) { hasFailed = true; Log.LogError( string.Empty, ErrorCodeById(ErrorIdStepFailure), ErrorIdStepFailure, string.Empty, 0, 0, 0, 0, "Execution of steps failed with exception. Exception was: {0}", e); } } if (Log.HasLoggedErrors || hasFailed) { if (FailureSteps != null) { var failureStepsToExecute = new List<ITaskItem>(); foreach (var step in FailureSteps) { if (!string.IsNullOrEmpty(step.ItemSpec)) { var stepGroups = StepGroups(step); if (!ShouldExecuteStep(groups, stepGroups)) { Log.LogMessage( MessageImportance.Low, "Step {0} has tags {1} none of which are included in execution list of {2}.", step.ItemSpec, string.Join(", ", stepGroups), string.Join(", ", groups)); continue; } failureStepsToExecute.Add(step); } } for (int i = 0; i < failureStepsToExecute.Count; i++) { var step = failureStepsToExecute[i]; if (!ExecuteFailureStep(step)) { if (StopOnFirstFailure) { break; } } } } } return !Log.HasLoggedErrors && !hasFailed; } private bool ExecuteFailureStep(ITaskItem step) { var result = InvokeBuildEngine(step); if (!result && StopOnFirstFailure) { return false; } return true; } private bool ExecuteStep(ITaskItem step, bool isFirst, bool isLast) { var stepResult = true; var stepPath = GetAbsolutePath(step.ItemSpec); if (PreSteps != null) { foreach (var globalPreStep in PreSteps) { if (!string.IsNullOrEmpty(globalPreStep.ItemSpec)) { AddStepMetadata(globalPreStep, stepPath, StepMetadata, isFirst, isLast); var result = InvokeBuildEngine(globalPreStep); if (!result) { if (FailOnPreStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPreStepFailure), ErrorIdPreStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing global pre-step action from '{0}'", globalPreStep.ItemSpec); } else { Log.LogWarning( "Failed while executing global pre-step action from '{0}'", globalPreStep.ItemSpec); } if (StopOnPreStepFailure) { return false; } } } } } var localPreSteps = LocalPreSteps(step); if (localPreSteps != null) { foreach (var localPreStep in localPreSteps) { if (!string.IsNullOrEmpty(localPreStep.ItemSpec)) { AddStepMetadata(localPreStep, stepPath, StepMetadata, isFirst, isLast); var result = InvokeBuildEngine(localPreStep); if (!result) { if (FailOnPreStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPreStepFailure), ErrorIdPreStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing step specific pre-step action from '{0}'", localPreStep.ItemSpec); } else { Log.LogWarning( "Failed while executing step specific pre-step action from '{0}'", localPreStep.ItemSpec); } if (StopOnPreStepFailure) { return false; } } } } } // Get the result but always try to excecute the post-step actions var localStepResult = InvokeBuildEngine(step); stepResult = stepResult && localStepResult; var localPostSteps = LocalPostSteps(step); if (localPostSteps != null) { foreach (var localPostStep in localPostSteps) { if (!string.IsNullOrEmpty(localPostStep.ItemSpec)) { AddStepMetadata(localPostStep, stepPath, StepMetadata, isFirst, isLast || !stepResult); var result = InvokeBuildEngine(localPostStep); if (!result) { if (FailOnPostStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPostStepFailure), ErrorIdPostStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing step specific post-step action from '{0}'", localPostStep.ItemSpec); } else { Log.LogWarning( "Failed while executing step specific post-step action from '{0}'", localPostStep.ItemSpec); } if (StopOnPostStepFailure) { return false; } } } } } if (PostSteps != null) { foreach (var globalPostStep in PostSteps) { if (!string.IsNullOrEmpty(globalPostStep.ItemSpec)) { AddStepMetadata(globalPostStep, stepPath, StepMetadata, isFirst, isLast || !stepResult); var result = InvokeBuildEngine(globalPostStep); if (!result && StopOnFirstFailure) { if (FailOnPostStepFailure) { stepResult = false; Log.LogError( string.Empty, ErrorCodeById(ErrorIdPostStepFailure), ErrorIdPostStepFailure, string.Empty, 0, 0, 0, 0, "Failed while executing global post-step action from '{0}'", globalPostStep.ItemSpec); } else { Log.LogWarning( "Failed while executing global post-step action from '{0}'", globalPostStep.ItemSpec); } if (StopOnPostStepFailure) { stepResult = false; } } } } } return stepResult; } /// <summary> /// Gets or sets a value indicating whether the process should fail if a post-step fails. /// </summary> public bool FailOnPostStepFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should fail if a pre-step fails. /// </summary> public bool FailOnPreStepFailure { get; set; } /// <summary> /// Gets or sets the steps that should be taken if a step fails. /// </summary> [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] FailureSteps { get; set; } private IEnumerable<string> Groups() { return GroupsToExecute.Select(t => t.ItemSpec).ToList(); } /// <summary> /// Gets or sets the collection of tags that mark which steps should be executed. If no groups are specified /// it is assumed that all valid steps should be executed. /// </summary> [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] GroupsToExecute { get; set; } private bool InvokeBuildEngine(ITaskItem project) { Hashtable propertiesTable; if (!PropertyParser.GetTableWithEscaping(new MsBuildLogger(Log), "GlobalProperties", "Properties", Properties.Select(t => t.ItemSpec).ToArray(), out propertiesTable)) { return false; } string projectPath = GetAbsolutePath(project.ItemSpec); if (File.Exists(projectPath)) { var toolsVersion = ToolsVersion; if (project != null) { // If the user specified additional properties then add those var projectProperties = project.GetMetadata("Properties"); if (!string.IsNullOrEmpty(projectProperties)) { Hashtable additionalProjectPropertiesTable; if (!PropertyParser.GetTableWithEscaping(new MsBuildLogger(Log), "AdditionalProperties", "AdditionalProperties", projectProperties.Split(';'), out additionalProjectPropertiesTable)) { return false; } var combinedTable = new Hashtable(StringComparer.OrdinalIgnoreCase); // First copy in the properties from the global table that not in the additional properties table if (propertiesTable != null) { foreach (DictionaryEntry entry in propertiesTable) { if (!additionalProjectPropertiesTable.Contains(entry.Key)) { combinedTable.Add(entry.Key, entry.Value); } } } // Add all the additional properties foreach (DictionaryEntry entry in additionalProjectPropertiesTable) { combinedTable.Add(entry.Key, entry.Value); } propertiesTable = combinedTable; } } // Send the project off to the build engine. By passing in null to the // first param, we are indicating that the project to build is the same // as the *calling* project file. BuildEngineResult result = BuildEngine3.BuildProjectFilesInParallel( new[] { projectPath }, null, new IDictionary[] { propertiesTable }, new IList<string>[] { new List<string>() }, new[] { toolsVersion }, false); return result.Result; } else { Log.LogError( string.Empty, ErrorCodeById(Core.ErrorInformation.ErrorIdFileNotFound), Core.ErrorInformation.ErrorIdFileNotFound, string.Empty, 0, 0, 0, 0, "MsBuild script file expected to be at '{0}' but could not be found", projectPath); return false; } } private List<ITaskItem> OrderSteps(IEnumerable<ITaskItem> steps) { var sortedItems = new List<Tuple<StepId, ITaskItem>>(); int IndexOf(StepId id) { return sortedItems.FindIndex(t => t.Item1.Equals(id)); } var unsortedItems = new List<Tuple<StepId, StepId[], StepId[], ITaskItem>>(); foreach (var item in steps) { var id = StepId(item); var executeAfter = ExecuteAfter(item); var executeBefore = ExecuteBefore(item); if ((executeBefore.Length > 0) || (executeAfter.Length > 0)) { unsortedItems.Add(Tuple.Create(id, executeBefore, executeAfter, item)); } else { sortedItems.Add(Tuple.Create(id, item)); } } var lastCount = steps.Count(); while ((unsortedItems.Count > 0) && (lastCount > unsortedItems.Count)) { lastCount = unsortedItems.Count; var toDelete = new List<Tuple<StepId, StepId[], StepId[], ITaskItem>>(); foreach (var unsortedItem in unsortedItems) { var insertBefore = -1; var executeBefore = unsortedItem.Item2; if (executeBefore.Length > 0) { var indices = executeBefore.Select(id => IndexOf(id)).Where(i => i > -1); if (indices.Count() != executeBefore.Length) { continue; } insertBefore = indices.Min(); } var insertAfter = sortedItems.Count; var executeAfter = unsortedItem.Item3; if (executeAfter.Length > 0) { var indices = executeAfter.Select(id => IndexOf(id)).Where(i => i > -1); if (indices.Count() != executeAfter.Length) { continue; } insertAfter = indices.Max(); } if ((executeBefore.Length > 0) && (executeAfter.Length > 0) && (insertBefore < insertAfter)) { Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidDependencies), ErrorIdInvalidDependencies, string.Empty, 0, 0, 0, 0, "At least one dependency needs to be inserted both before an earlier item and after a later item. No suitable place for the insertion could be found."); return null; } if (executeBefore.Length > 0) { sortedItems.Insert(insertBefore, Tuple.Create(unsortedItem.Item1, unsortedItem.Item4)); toDelete.Add(unsortedItem); } else { sortedItems.Insert(insertAfter + 1, Tuple.Create(unsortedItem.Item1, unsortedItem.Item4)); toDelete.Add(unsortedItem); } } foreach (var item in toDelete) { unsortedItems.Remove(item); } } if (unsortedItems.Count > 0) { Log.LogMessage( MessageImportance.Normal, "Failed to sort all the steps. The sorted steps were: "); for (int i = 0; i < sortedItems.Count; i++) { var tuple = sortedItems[i]; Log.LogMessage( MessageImportance.Normal, "{0} - {1}", i, tuple.Item1); } Log.LogMessage( MessageImportance.Normal, "The unsorted steps were: "); for (int i = 0; i < unsortedItems.Count; i++) { var tuple = unsortedItems[i]; Log.LogMessage( MessageImportance.Normal, "{0} - {1}", i, tuple.Item1); } Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidDependencies), ErrorIdInvalidDependencies, string.Empty, 0, 0, 0, 0, "Was not able to order all the steps."); return null; } return sortedItems.Select(t => t.Item2).ToList(); } /// <summary> /// Gets or sets the steps that should be executed after each step. /// </summary> [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] PostSteps { get; set; } /// <summary> /// Gets or sets the steps that should be executed prior to each step. /// </summary> [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] PreSteps { get; set; } /// <summary> /// Gets or sets the steps that should be taken for the current process. /// </summary> [Required] [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] Projects { get; set; } /// <summary> /// Gets or sets the properties for the steps. /// </summary> [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] Properties { get; set; } [SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catching, logging and letting MsBuild deal with the fall out")] private bool ShouldExecuteStep(IEnumerable<string> groupsToExecute, IEnumerable<string> stepGroups) { const string AlwaysExecuteGroup = "all"; try { return !groupsToExecute.Any() || groupsToExecute.Contains(AlwaysExecuteGroup) || (groupsToExecute.Any() && groupsToExecute.Intersect(stepGroups).Any()); } catch (Exception e) { Log.LogError( string.Empty, ErrorCodeById(ErrorIdInvalidConfiguration), ErrorIdInvalidConfiguration, string.Empty, 0, 0, 0, 0, "Failed to determine if the collection contains any of the items. Error was: {0}", e); return false; } } /// <summary> /// Gets or sets the collection containing the metadata describing the different steps. /// </summary> [Required] [SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MsBuild does not understand collections")] public ITaskItem[] StepMetadata { get; set; } /// <summary> /// Gets or sets a value indicating whether or not the process should stop on the first error or continue. /// Default is false. /// </summary> public bool StopOnFirstFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should stop if a pre-step fails. /// </summary> public bool StopOnPreStepFailure { get; set; } /// <summary> /// Gets or sets a value indicating whether the process should stop if a post-step fails. /// </summary> public bool StopOnPostStepFailure { get; set; } /// <summary> /// Gets or sets the version of MsBuild and the build tools that should be used. /// </summary> public string ToolsVersion { get; set; } } }
// jQueryDeferred.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace jQueryApi { /// <summary> /// Represents a deferred value. /// </summary> [ScriptImport] [ScriptIgnoreNamespace] public sealed class jQueryDeferred : IDeferred { private jQueryDeferred() { } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Always(params Action[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Always(params Callback[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Done(params Action[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Done(params Callback[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Fail(params Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Fail(params Callback[] failCallbacks) { return null; } /// <summary> /// Determines whether the deferred object has been rejected. /// </summary> /// <returns>true if it has been rejected; false otherwise.</returns> public bool IsRejected() { return false; } /// <summary> /// Determines whether the deferred object has been resolved. /// </summary> /// <returns>true if it has been resolved; false otherwise.</returns> public bool IsResolved() { return false; } /// <summary> /// Returns a deferred object that can be further composed. /// </summary> /// <returns>A deferred object.</returns> public IDeferred Promise() { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Reject(params object[] args) { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred RejectWith(object context, params object[] args) { return null; } /// <summary> /// Resolves the deferred object and call any done callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Resolve(params object[] args) { return null; } /// <summary> /// Resolves the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred ResolveWith(object context, params object[] args) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Action doneCallback, Action failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Callback doneCallback, Callback failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } #region Implementation of IDeferred IDeferred IDeferred.Always(params Action[] callbacks) { return null; } IDeferred IDeferred.Always(params Callback[] callbacks) { return null; } IDeferred IDeferred.Done(params Action[] doneCallbacks) { return null; } IDeferred IDeferred.Done(params Callback[] doneCallbacks) { return null; } IDeferred IDeferred.Fail(params Action[] failCallbacks) { return null; } IDeferred IDeferred.Fail(params Callback[] failCallbacks) { return null; } bool IDeferred.IsRejected() { return false; } bool IDeferred.IsResolved() { return false; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter) { return null; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter, jQueryDeferredFilter failFilter) { return null; } IDeferred IDeferred.Then(Action doneCallback, Action failCallback) { return null; } IDeferred IDeferred.Then(Callback doneCallback, Callback failCallback) { return null; } IDeferred IDeferred.Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } IDeferred IDeferred.Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } #endregion } /// <summary> /// Represents a deferred value. /// </summary> [ScriptImport] [ScriptIgnoreNamespace] public sealed class jQueryDeferred<TData> : IDeferred<TData> { private jQueryDeferred() { } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Always(params Action[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or /// rejected. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Always(params Action<TData>[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Done(params Action[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Done(params Action<TData>[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Fail(params Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is rejected. If the /// deferred object is already resolved, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Fail(params Action<TData>[] failCallbacks) { return null; } /// <summary> /// Determines whether the deferred object has been rejected. /// </summary> /// <returns>true if it has been rejected; false otherwise.</returns> public bool IsRejected() { return false; } /// <summary> /// Determines whether the deferred object has been resolved. /// </summary> /// <returns>true if it has been resolved; false otherwise.</returns> public bool IsResolved() { return false; } /// <summary> /// Returns a deferred object that can be further composed. /// </summary> /// <returns>A deferred object.</returns> public IDeferred<TData> Promise() { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Reject(params TData[] args) { return null; } /// <summary> /// Rejects the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> RejectWith(object context, params TData[] args) { return null; } /// <summary> /// Resolves the deferred object and call any done callbacks with the specified arguments. /// </summary> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Resolve(params TData[] args) { return null; } /// <summary> /// Resolves the deferred object and call any failure callbacks with the specified arguments /// using the specified context as the this parameter. /// </summary> /// <param name="context">The context in which the callback is invoked.</param> /// <param name="args">The arguments to pass to the callbacks.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> ResolveWith(object context, params TData[] args) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action doneCallback, Action failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the object is resolved.</param> /// <param name="failCallback">The callback to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action<TData> doneCallback, Action<TData> failCallback) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the deferred object is resolved or rejected. /// If the object has already been resolved or rejected, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the object is resolved.</param> /// <param name="failCallbacks">The callbacks to invoke when the object is rejected.</param> /// <returns>The current deferred object.</returns> public jQueryDeferred<TData> Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) { return null; } #region Implementation of IDeferred IDeferred<TData> IDeferred<TData>.Always(params Action[] callbacks) { return null; } IDeferred<TData> IDeferred<TData>.Always(params Action<TData>[] callbacks) { return null; } IDeferred<TData> IDeferred<TData>.Done(params Action[] doneCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Done(params Action<TData>[] doneCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Fail(params Action[] failCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Fail(params Action<TData>[] failCallbacks) { return null; } bool IDeferred<TData>.IsRejected() { return false; } bool IDeferred<TData>.IsResolved() { return false; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(Func<TData, IDeferred<TTargetData>> successChain) { return null; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) { return null; } IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action doneCallback, Action failCallback) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action<TData> doneCallback, Action<TData> failCallback) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } IDeferred<TData> IDeferred<TData>.Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) { return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; namespace System.Diagnostics { /// <devdoc> /// <para>Provides the <see langword='abstract '/>base class for the listeners who /// monitor trace and debug output.</para> /// </devdoc> public abstract class TraceListener : IDisposable { private int _indentLevel; private int _indentSize = 4; private TraceOptions _traceOptions = TraceOptions.None; private bool _needIndent = true; private string _listenerName; private TraceFilter _filter = null; /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Diagnostics.TraceListener'/> class.</para> /// </devdoc> protected TraceListener() { } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Diagnostics.TraceListener'/> class using the specified name as the /// listener.</para> /// </devdoc> protected TraceListener(string name) { _listenerName = name; } /// <devdoc> /// <para> Gets or sets a name for this <see cref='System.Diagnostics.TraceListener'/>.</para> /// </devdoc> public virtual string Name { get { return (_listenerName == null) ? "" : _listenerName; } set { _listenerName = value; } } public virtual bool IsThreadSafe { get { return false; } } /// <devdoc> /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <devdoc> /// </devdoc> protected virtual void Dispose(bool disposing) { return; } /// <devdoc> /// <para>When overridden in a derived class, flushes the output buffer.</para> /// </devdoc> public virtual void Flush() { return; } /// <devdoc> /// <para>Gets or sets the indent level.</para> /// </devdoc> public int IndentLevel { get { return _indentLevel; } set { _indentLevel = (value < 0) ? 0 : value; } } /// <devdoc> /// <para>Gets or sets the number of spaces in an indent.</para> /// </devdoc> public int IndentSize { get { return _indentSize; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(IndentSize), value, SR.TraceListenerIndentSize); _indentSize = value; } } public TraceFilter Filter { get { return _filter; } set { _filter = value; } } /// <devdoc> /// <para>Gets or sets a value indicating whether an indent is needed.</para> /// </devdoc> protected bool NeedIndent { get { return _needIndent; } set { _needIndent = value; } } public TraceOptions TraceOutputOptions { get { return _traceOptions; } set { if (((int)value >> 6) != 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _traceOptions = value; } } /// <devdoc> /// <para>Emits or displays a message for an assertion that always fails.</para> /// </devdoc> public virtual void Fail(string message) { Fail(message, null); } /// <devdoc> /// <para>Emits or displays messages for an assertion that always fails.</para> /// </devdoc> public virtual void Fail(string message, string detailMessage) { StringBuilder failMessage = new StringBuilder(); failMessage.Append(SR.TraceListenerFail); failMessage.Append(" "); failMessage.Append(message); if (detailMessage != null) { failMessage.Append(" "); failMessage.Append(detailMessage); } WriteLine(failMessage.ToString()); } /// <devdoc> /// <para>When overridden in a derived class, writes the specified /// message to the listener you specify in the derived class.</para> /// </devdoc> public abstract void Write(string message); /// <devdoc> /// <para>Writes the name of the <paramref name="o"/> parameter to the listener you specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; if (o == null) return; Write(o.ToString()); } /// <devdoc> /// <para>Writes a category name and a message to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) Write(message); else Write(category + ": " + ((message == null) ? string.Empty : message)); } /// <devdoc> /// <para>Writes a category name and the name of the <paramref name="o"/> parameter to the listener you /// specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class.</para> /// </devdoc> public virtual void Write(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; if (category == null) Write(o); else Write(o == null ? "" : o.ToString(), category); } /// <devdoc> /// <para>Writes the indent to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class, and resets the <see cref='TraceListener.NeedIndent'/> property to <see langword='false'/>.</para> /// </devdoc> protected virtual void WriteIndent() { NeedIndent = false; for (int i = 0; i < _indentLevel; i++) { if (_indentSize == 4) Write(" "); else { for (int j = 0; j < _indentSize; j++) { Write(" "); } } } } /// <devdoc> /// <para>When overridden in a derived class, writes a message to the listener you specify in /// the derived class, followed by a line terminator. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> public abstract void WriteLine(string message); /// <devdoc> /// <para>Writes the name of the <paramref name="o"/> parameter to the listener you specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> class, followed by a line terminator. The default line terminator is a /// carriage return followed by a line feed /// (\r\n).</para> /// </devdoc> public virtual void WriteLine(object o) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, null, null, o)) return; WriteLine(o == null ? "" : o.ToString()); } /// <devdoc> /// <para>Writes a category name and a message to the listener you specify when you /// inherit from the <see cref='System.Diagnostics.TraceListener'/> class, /// followed by a line terminator. The default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> public virtual void WriteLine(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) return; if (category == null) WriteLine(message); else WriteLine(category + ": " + ((message == null) ? string.Empty : message)); } /// <devdoc> /// <para>Writes a category /// name and the name of the <paramref name="o"/>parameter to the listener you /// specify when you inherit from the <see cref='System.Diagnostics.TraceListener'/> /// class, followed by a line terminator. The default line terminator is a carriage /// return followed by a line feed (\r\n).</para> /// </devdoc> public virtual void WriteLine(object o, string category) { if (Filter != null && !Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) return; WriteLine(o == null ? "" : o.ToString(), category); } // new write methods used by TraceSource public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data)) return; WriteHeader(source, eventType, id); string datastring = String.Empty; if (data != null) datastring = data.ToString(); WriteLine(datastring); WriteFooter(eventCache); } public virtual void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); StringBuilder sb = new StringBuilder(); if (data != null) { for (int i = 0; i < data.Length; i++) { if (i != 0) sb.Append(", "); if (data[i] != null) sb.Append(data[i].ToString()); } } WriteLine(sb.ToString()); WriteFooter(eventCache); } public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id) { TraceEvent(eventCache, source, eventType, id, String.Empty); } // All other TraceEvent methods come through this one. public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message)) return; WriteHeader(source, eventType, id); WriteLine(message); WriteFooter(eventCache); } public virtual void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args)) return; WriteHeader(source, eventType, id); if (args != null) WriteLine(String.Format(CultureInfo.InvariantCulture, format, args)); else WriteLine(format); WriteFooter(eventCache); } private void WriteHeader(String source, TraceEventType eventType, int id) { Write(String.Format(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", source, eventType.ToString(), id.ToString(CultureInfo.InvariantCulture))); } private void WriteFooter(TraceEventCache eventCache) { if (eventCache == null) return; _indentLevel++; if (IsEnabled(TraceOptions.ProcessId)) WriteLine("ProcessId=" + eventCache.ProcessId); if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); if (IsEnabled(TraceOptions.Timestamp)) WriteLine("Timestamp=" + eventCache.Timestamp); _indentLevel--; } internal bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } } }
/* * Copyright 2013 ZXing authors * * 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 ZXing.Common; namespace ZXing.PDF417.Internal { /// <summary> /// A Bounding Box helper class /// </summary> /// <author>Guenther Grau</author> public sealed class BoundingBox { private readonly BitMatrix image; public ResultPoint TopLeft { get; private set; } public ResultPoint TopRight { get; private set; } public ResultPoint BottomLeft { get; private set; } public ResultPoint BottomRight { get; private set; } public int MinX { get; private set; } public int MaxX { get; private set; } public int MinY { get; private set; } public int MaxY { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ZXing.PDF417.Internal.BoundingBox"/> class. /// returns null if the corner points don't match up correctly /// </summary> /// <param name="image">The image.</param> /// <param name="topLeft">The top left.</param> /// <param name="bottomLeft">The bottom left.</param> /// <param name="topRight">The top right.</param> /// <param name="bottomRight">The bottom right.</param> /// <returns></returns> public static BoundingBox Create(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint topRight, ResultPoint bottomRight) { if ((topLeft == null && topRight == null) || (bottomLeft == null && bottomRight == null) || (topLeft != null && bottomLeft == null) || (topRight != null && bottomRight == null)) { return null; } return new BoundingBox(image, topLeft, bottomLeft,topRight, bottomRight); } /// <summary> /// Creates the specified box. /// </summary> /// <param name="box">The box.</param> /// <returns></returns> public static BoundingBox Create(BoundingBox box) { return new BoundingBox(box.image, box.TopLeft, box.BottomLeft, box.TopRight, box.BottomRight); } /// <summary> /// Initializes a new instance of the <see cref="ZXing.PDF417.Internal.BoundingBox"/> class. /// Will throw an exception if the corner points don't match up correctly /// </summary> /// <param name="image">Image.</param> /// <param name="topLeft">Top left.</param> /// <param name="topRight">Top right.</param> /// <param name="bottomLeft">Bottom left.</param> /// <param name="bottomRight">Bottom right.</param> private BoundingBox(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint topRight, ResultPoint bottomRight) { this.image = image; this.TopLeft = topLeft; this.TopRight = topRight; this.BottomLeft = bottomLeft; this.BottomRight = bottomRight; calculateMinMaxValues(); } /// <summary> /// Merge two Bounding Boxes, getting the left corners of left, and the right corners of right /// (Images should be the same) /// </summary> /// <param name="leftBox">Left.</param> /// <param name="rightBox">Right.</param> internal static BoundingBox merge(BoundingBox leftBox, BoundingBox rightBox) { if (leftBox == null) return rightBox; if (rightBox == null) return leftBox; return new BoundingBox(leftBox.image, leftBox.TopLeft, leftBox.BottomLeft, rightBox.TopRight, rightBox.BottomRight); } /// <summary> /// Adds the missing rows. /// </summary> /// <returns>The missing rows.</returns> /// <param name="missingStartRows">Missing start rows.</param> /// <param name="missingEndRows">Missing end rows.</param> /// <param name="isLeft">If set to <c>true</c> is left.</param> public BoundingBox addMissingRows(int missingStartRows, int missingEndRows, bool isLeft) { ResultPoint newTopLeft = TopLeft; ResultPoint newBottomLeft = BottomLeft; ResultPoint newTopRight = TopRight; ResultPoint newBottomRight = BottomRight; if (missingStartRows > 0) { ResultPoint top = isLeft ? TopLeft : TopRight; int newMinY = (int) top.Y - missingStartRows; if (newMinY < 0) { newMinY = 0; } ResultPoint newTop = new ResultPoint(top.X, newMinY); if (isLeft) { newTopLeft = newTop; } else { newTopRight = newTop; } } if (missingEndRows > 0) { ResultPoint bottom = isLeft ? BottomLeft : BottomRight; int newMaxY = (int) bottom.Y + missingEndRows; if (newMaxY >= image.Height) { newMaxY = image.Height - 1; } ResultPoint newBottom = new ResultPoint(bottom.X, newMaxY); if (isLeft) { newBottomLeft = newBottom; } else { newBottomRight = newBottom; } } calculateMinMaxValues(); return new BoundingBox(image, newTopLeft, newBottomLeft, newTopRight, newBottomRight); } /// <summary> /// Calculates the minimum and maximum X & Y values based on the corner points. /// </summary> private void calculateMinMaxValues() { // Constructor ensures that either Left or Right is not null if (TopLeft == null) { TopLeft = new ResultPoint(0, TopRight.Y); BottomLeft = new ResultPoint(0, BottomRight.Y); } else if (TopRight == null) { TopRight = new ResultPoint(image.Width - 1, TopLeft.Y); BottomRight = new ResultPoint(image.Width - 1, TopLeft.Y); } MinX = (int) Math.Min(TopLeft.X, BottomLeft.X); MaxX = (int) Math.Max(TopRight.X, BottomRight.X); MinY = (int) Math.Min(TopLeft.Y, TopRight.Y); MaxY = (int) Math.Max(BottomLeft.Y, BottomRight.Y); } /// <summary> /// If we adjust the width, set a new right corner coordinate and recalculate /// </summary> /// <param name="bottomRight">Bottom right.</param> internal void SetBottomRight(ResultPoint bottomRight) { this.BottomRight = bottomRight; calculateMinMaxValues(); } /* /// <summary> /// If we adjust the width, set a new right corner coordinate and recalculate /// </summary> /// <param name="topRight">Top right.</param> internal void SetTopRight(ResultPoint topRight) { this.TopRight = topRight; calculateMinMaxValues(); } */ } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; using Scientia.HtmlRenderer.Core; using Scientia.HtmlRenderer.Core.Entities; using Scientia.HtmlRenderer.WinForms.Utilities; namespace Scientia.HtmlRenderer.WinForms { /// <summary> /// Provides HTML rendering on the tooltips. /// </summary> public class HtmlToolTip : ToolTip { #region Fields and Consts /// <summary> /// the container to render and handle the html shown in the tooltip /// </summary> protected HtmlContainer HtmlContainer; /// <summary> /// the raw base stylesheet data used in the control /// </summary> protected string BaseRawCssData; /// <summary> /// the base stylesheet data used in the panel /// </summary> protected CssData BaseCssData; /// <summary> /// The text rendering hint to be used for text rendering. /// </summary> protected TextRenderingHint _TextRenderingHint = TextRenderingHint.SystemDefault; /// <summary> /// The CSS class used for tooltip html root div /// </summary> private string _TooltipCssClass = "htmltooltip"; #if !MONO /// <summary> /// the control that the tooltip is currently showing on.<br/> /// Used for link handling. /// </summary> private Control AssociatedControl; /// <summary> /// timer used to handle mouse move events when mouse is over the tooltip.<br/> /// Used for link handling. /// </summary> private Timer LinkHandlingTimer; /// <summary> /// the handle of the actual tooltip window used to know when the tooltip is hidden<br/> /// Used for link handling. /// </summary> private IntPtr TooltipHandle; /// <summary> /// If to handle links in the tooltip (default: false).<br/> /// When set to true the mouse pointer will change to hand when hovering over a tooltip and /// if clicked the <see cref="LinkClicked"/> event will be raised although the tooltip will be closed. /// </summary> private bool _AllowLinksHandling = true; #endif #endregion /// <summary> /// Init. /// </summary> public HtmlToolTip() { this.OwnerDraw = true; this.HtmlContainer = new HtmlContainer(); this.HtmlContainer.IsSelectionEnabled = false; this.HtmlContainer.IsContextMenuEnabled = false; this.HtmlContainer.AvoidGeometryAntialias = true; this.HtmlContainer.AvoidImagesLateLoading = true; this.HtmlContainer.RenderError += this.OnRenderError; this.HtmlContainer.StylesheetLoad += this.OnStylesheetLoad; this.HtmlContainer.ImageLoad += this.OnImageLoad; this.Popup += this.OnToolTipPopup; this.Draw += this.OnToolTipDraw; this.Disposed += this.OnToolTipDisposed; #if !MONO this.LinkHandlingTimer = new Timer(); this.LinkHandlingTimer.Tick += this.OnLinkHandlingTimerTick; this.LinkHandlingTimer.Interval = 40; this.HtmlContainer.LinkClicked += this.OnLinkClicked; #endif } #if !MONO /// <summary> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </summary> public event EventHandler<HtmlLinkClickedEventArgs> LinkClicked; #endif /// <summary> /// Raised when an error occurred during html rendering.<br/> /// </summary> public event EventHandler<HtmlRenderErrorEventArgs> RenderError; /// <summary> /// Raised when aa stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </summary> public event EventHandler<HtmlStylesheetLoadEventArgs> StylesheetLoad; /// <summary> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </summary> public event EventHandler<HtmlImageLoadEventArgs> ImageLoad; /// <summary> /// Use GDI+ text rendering to measure/draw text.<br/> /// </summary> /// <remarks> /// <para> /// GDI+ text rendering is less smooth than GDI text rendering but it natively supports alpha channel /// thus allows creating transparent images. /// </para> /// <para> /// While using GDI+ text rendering you can control the text rendering using <see cref="Graphics.TextRenderingHint"/>, note that /// using <see cref="TextRenderingHint.ClearTypeGridFit"/> doesn't work well with transparent background. /// </para> /// </remarks> [Category("Behavior")] [DefaultValue(false)] [EditorBrowsable(EditorBrowsableState.Always)] [Description("If to use GDI+ text rendering to measure/draw text, false - use GDI")] public bool UseGdiPlusTextRendering { get { return this.HtmlContainer.UseGdiPlusTextRendering; } set { this.HtmlContainer.UseGdiPlusTextRendering = value; } } /// <summary> /// The text rendering hint to be used for text rendering. /// </summary> [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DefaultValue(TextRenderingHint.SystemDefault)] [Description("The text rendering hint to be used for text rendering.")] public TextRenderingHint TextRenderingHint { get { return this._TextRenderingHint; } set { this._TextRenderingHint = value; } } /// <summary> /// Set base stylesheet to be used by html rendered in the panel. /// </summary> [Browsable(true)] [Description("Set base stylesheet to be used by html rendered in the tooltip.")] [Category("Appearance")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public virtual string BaseStylesheet { get { return this.BaseRawCssData; } set { this.BaseRawCssData = value; this.BaseCssData = HtmlRender.ParseStyleSheet(value); } } /// <summary> /// The CSS class used for tooltip html root div (default: htmltooltip)<br/> /// Setting to 'null' clear base style on the tooltip.<br/> /// Set custom class found in <see cref="BaseStylesheet"/> to change the base style of the tooltip. /// </summary> [Browsable(true)] [Description("The CSS class used for tooltip html root div.")] [Category("Appearance")] public virtual string TooltipCssClass { get { return this._TooltipCssClass; } set { this._TooltipCssClass = value; } } #if !MONO /// <summary> /// If to handle links in the tooltip (default: false).<br/> /// When set to true the mouse pointer will change to hand when hovering over a tooltip and /// if clicked the <see cref="LinkClicked"/> event will be raised although the tooltip will be closed. /// </summary> [Browsable(true)] [DefaultValue(false)] [Description("If to handle links in the tooltip.")] [Category("Behavior")] public virtual bool AllowLinksHandling { get { return this._AllowLinksHandling; } set { this._AllowLinksHandling = value; } } #endif /// <summary> /// Gets or sets the max size the tooltip. /// </summary> /// <returns>An ordered pair of type <see cref="T:System.Drawing.Size"/> representing the width and height of a rectangle.</returns> [Browsable(true)] [Category("Layout")] [Description("Restrict the max size of the shown tooltip (0 is not restricted)")] public virtual Size MaximumSize { get { return Size.Round(this.HtmlContainer.MaxSize); } set { this.HtmlContainer.MaxSize = value; } } #region Private methods /// <summary> /// On tooltip appear set the html by the associated control, layout and set the tooltip size by the html size. /// </summary> protected virtual void OnToolTipPopup(PopupEventArgs e) { // Create fragment container var cssClass = string.IsNullOrEmpty(this._TooltipCssClass) ? null : string.Format(" class=\"{0}\"", this._TooltipCssClass); var toolipHtml = string.Format("<div{0}>{1}</div>", cssClass, this.GetToolTip(e.AssociatedControl)); this.HtmlContainer.SetHtml(toolipHtml, this.BaseCssData); this.HtmlContainer.MaxSize = this.MaximumSize; // Measure size of the container using (var g = e.AssociatedControl.CreateGraphics()) { g.TextRenderingHint = this._TextRenderingHint; this.HtmlContainer.PerformLayout(g); } // Set the size of the tooltip var desiredWidth = (int)Math.Ceiling(this.MaximumSize.Width > 0 ? Math.Min(this.HtmlContainer.ActualSize.Width, this.MaximumSize.Width) : this.HtmlContainer.ActualSize.Width); var desiredHeight = (int)Math.Ceiling(this.MaximumSize.Height > 0 ? Math.Min(this.HtmlContainer.ActualSize.Height, this.MaximumSize.Height) : this.HtmlContainer.ActualSize.Height); e.ToolTipSize = new Size(desiredWidth, desiredHeight); #if !MONO // start mouse handle timer if (this._AllowLinksHandling) { this.AssociatedControl = e.AssociatedControl; this.LinkHandlingTimer.Start(); } #endif } /// <summary> /// Draw the html using the tooltip graphics. /// </summary> protected virtual void OnToolTipDraw(DrawToolTipEventArgs e) { #if !MONO if (this.TooltipHandle == IntPtr.Zero) { // get the handle of the tooltip window using the graphics device context var hdc = e.Graphics.GetHdc(); this.TooltipHandle = Win32Utils.WindowFromDC(hdc); e.Graphics.ReleaseHdc(hdc); this.AdjustTooltipPosition(e.AssociatedControl, e.Bounds.Size); } #endif e.Graphics.Clear(Color.White); e.Graphics.TextRenderingHint = this._TextRenderingHint; this.HtmlContainer.PerformPaint(e.Graphics); } /// <summary> /// Adjust the location of the tooltip window to the location of the mouse and handle /// if the tooltip window will try to appear outside the boundaries of the control. /// </summary> /// <param name="associatedControl">the control the tooltip is appearing on</param> /// <param name="size">the size of the tooltip window</param> protected virtual void AdjustTooltipPosition(Control associatedControl, Size size) { var mousePos = Control.MousePosition; var screenBounds = Screen.FromControl(associatedControl).WorkingArea; // adjust if tooltip is outside form bounds if (mousePos.X + size.Width > screenBounds.Right) { mousePos.X = Math.Max(screenBounds.Right - size.Width - 5, screenBounds.Left + 3); } const int yOffset = 20; if (mousePos.Y + size.Height + yOffset > screenBounds.Bottom) { mousePos.Y = Math.Max(screenBounds.Bottom - size.Height - yOffset - 3, screenBounds.Top + 2); } #if !MONO // move the tooltip window to new location Win32Utils.MoveWindow(this.TooltipHandle, mousePos.X, mousePos.Y + yOffset, size.Width, size.Height, false); #endif } #if !MONO /// <summary> /// Propagate the LinkClicked event from root container. /// </summary> protected virtual void OnLinkClicked(HtmlLinkClickedEventArgs e) { var handler = this.LinkClicked; if (handler != null) { handler(this, e); } } #endif /// <summary> /// Propagate the Render Error event from root container. /// </summary> protected virtual void OnRenderError(HtmlRenderErrorEventArgs e) { var handler = this.RenderError; if (handler != null) { handler(this, e); } } /// <summary> /// Propagate the stylesheet load event from root container. /// </summary> protected virtual void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e) { var handler = this.StylesheetLoad; if (handler != null) { handler(this, e); } } /// <summary> /// Propagate the image load event from root container. /// </summary> protected virtual void OnImageLoad(HtmlImageLoadEventArgs e) { var handler = this.ImageLoad; if (handler != null) { handler(this, e); } } #if !MONO /// <summary> /// Raised on link handling timer tick, used for: /// 1. Know when the tooltip is hidden by checking the visibility of the tooltip window. /// 2. Call HandleMouseMove so the mouse cursor will react if over a link element. /// 3. Call HandleMouseDown and HandleMouseUp to simulate click on a link if one was clicked. /// </summary> protected virtual void OnLinkHandlingTimerTick(EventArgs e) { try { var handle = this.TooltipHandle; if (handle != IntPtr.Zero && Win32Utils.IsWindowVisible(handle)) { var mPos = Control.MousePosition; var mButtons = Control.MouseButtons; var rect = Win32Utils.GetWindowRectangle(handle); if (rect.Contains(mPos)) { this.HtmlContainer.HandleMouseMove(this.AssociatedControl, new MouseEventArgs(mButtons, 0, mPos.X - rect.X, mPos.Y - rect.Y, 0)); } } else { this.LinkHandlingTimer.Stop(); this.TooltipHandle = IntPtr.Zero; var mPos = Control.MousePosition; var mButtons = Control.MouseButtons; var rect = Win32Utils.GetWindowRectangle(handle); if (rect.Contains(mPos)) { if (mButtons == MouseButtons.Left) { var args = new MouseEventArgs(mButtons, 1, mPos.X - rect.X, mPos.Y - rect.Y, 0); this.HtmlContainer.HandleMouseDown(this.AssociatedControl, args); this.HtmlContainer.HandleMouseUp(this.AssociatedControl, args); } } } } catch (Exception ex) { this.OnRenderError(this, new HtmlRenderErrorEventArgs(HtmlRenderErrorType.General, "Error in link handling for tooltip", ex)); } } #endif /// <summary> /// Unsubscribe from events and dispose of <see cref="HtmlContainer"/>. /// </summary> protected virtual void OnToolTipDisposed(EventArgs e) { this.Popup -= this.OnToolTipPopup; this.Draw -= this.OnToolTipDraw; this.Disposed -= this.OnToolTipDisposed; if (this.HtmlContainer != null) { this.HtmlContainer.RenderError -= this.OnRenderError; this.HtmlContainer.StylesheetLoad -= this.OnStylesheetLoad; this.HtmlContainer.ImageLoad -= this.OnImageLoad; this.HtmlContainer.Dispose(); this.HtmlContainer = null; } #if !MONO if (this.LinkHandlingTimer != null) { this.LinkHandlingTimer.Dispose(); this.LinkHandlingTimer = null; if (this.HtmlContainer != null) { this.HtmlContainer.LinkClicked -= this.OnLinkClicked; } } #endif } #region Private event handlers private void OnToolTipPopup(object sender, PopupEventArgs e) { this.OnToolTipPopup(e); } private void OnToolTipDraw(object sender, DrawToolTipEventArgs e) { this.OnToolTipDraw(e); } private void OnRenderError(object sender, HtmlRenderErrorEventArgs e) { this.OnRenderError(e); } private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e) { this.OnStylesheetLoad(e); } private void OnImageLoad(object sender, HtmlImageLoadEventArgs e) { this.OnImageLoad(e); } #if !MONO private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e) { this.OnLinkClicked(e); } private void OnLinkHandlingTimerTick(object sender, EventArgs e) { this.OnLinkHandlingTimerTick(e); } #endif private void OnToolTipDisposed(object sender, EventArgs e) { this.OnToolTipDisposed(e); } #endregion #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Authorization; namespace Microsoft.Azure.Management.Authorization { public partial class AuthorizationManagementClient : ServiceClient<AuthorizationManagementClient>, IAuthorizationManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IPermissionOperations _permissions; /// <summary> /// Get resource or resource group permissions (see http://TBD for /// more information) /// </summary> public virtual IPermissionOperations Permissions { get { return this._permissions; } } private IRoleAssignmentOperations _roleAssignments; /// <summary> /// TBD (see http://TBD for more information) /// </summary> public virtual IRoleAssignmentOperations RoleAssignments { get { return this._roleAssignments; } } private IRoleDefinitionOperations _roleDefinitions; /// <summary> /// TBD (see http://TBD for more information) /// </summary> public virtual IRoleDefinitionOperations RoleDefinitions { get { return this._roleDefinitions; } } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> public AuthorizationManagementClient() : base() { this._permissions = new PermissionOperations(this); this._roleAssignments = new RoleAssignmentOperations(this); this._roleDefinitions = new RoleDefinitionOperations(this); this._apiVersion = "2014-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public AuthorizationManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public AuthorizationManagementClient(HttpClient httpClient) : base(httpClient) { this._permissions = new PermissionOperations(this); this._roleAssignments = new RoleAssignmentOperations(this); this._roleDefinitions = new RoleDefinitionOperations(this); this._apiVersion = "2014-10-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the AuthorizationManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// AuthorizationManagementClient instance /// </summary> /// <param name='client'> /// Instance of AuthorizationManagementClient to clone to /// </param> protected override void Clone(ServiceClient<AuthorizationManagementClient> client) { base.Clone(client); if (client is AuthorizationManagementClient) { AuthorizationManagementClient clonedClient = ((AuthorizationManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// // 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.Text; namespace Encog.Util { /// <summary> /// Provides the ability for Encog to format numbers and times. /// </summary> public class Format { /// <summary> /// One hundred percent. /// </summary> public const double HundredPercent = 100.0; /// <summary> /// Bytes in a KB. /// </summary> public const long MemoryK = 1024; /// <summary> /// Bytes in a MB. /// </summary> public const long MemoryMeg = (1024*MemoryK); /// <summary> /// Bytes in a GB. /// </summary> public const long MemoryGig = (1024*MemoryMeg); /// <summary> /// Bytes in a TB. /// </summary> public const long MemoryTera = (1024*MemoryGig); /// <summary> /// Seconds in a minute. /// </summary> public const int SecondsInaMinute = 60; /// <summary> /// Seconds in an hour. /// </summary> public const int SecondsInaHour = SecondsInaMinute*60; /// <summary> /// Seconds in a day. /// </summary> public const int SecondsInaDay = SecondsInaHour*24; /// <summary> /// Miliseconds in a day. /// </summary> public const long MiliInSec = 1000; /// <summary> /// Private constructor. /// </summary> private Format() { } /// <summary> /// Format a double. /// </summary> /// <param name="d">The double value to format.</param> /// <param name="i">The number of decimal places.</param> /// <returns>The double as a string.</returns> public static String FormatDouble(double d, int i) { if (Double.IsNaN(d) || Double.IsInfinity(d)) return "NaN"; return d.ToString("N" + i); } /// <summary> /// Format a memory amount, to something like 32 MB. /// </summary> /// <param name="memory">The amount of bytes.</param> /// <returns>The formatted memory size.</returns> public static String FormatMemory(long memory) { if (memory < MemoryK) { return memory + " bytes"; } if (memory < MemoryMeg) { return FormatDouble((memory)/((double) MemoryK), 2) + " KB"; } if (memory < MemoryGig) { return FormatDouble((memory)/((double) MemoryMeg), 2) + " MB"; } if (memory < MemoryTera) { return FormatDouble((memory)/((double) MemoryGig), 2) + " GB"; } return FormatDouble((memory)/((double) MemoryTera), 2) + " TB"; } /// <summary> /// Format an integer. /// </summary> /// <param name="i">The integer.</param> /// <returns>The string.</returns> public static String FormatInteger(int i) { return String.Format("{0:n0}", i); } /// <summary> /// Format a percent. Using 6 decimal places. /// </summary> /// <param name="e">The percent to format.</param> /// <returns>The formatted percent.</returns> public static String FormatPercent(double e) { if( Double.IsNaN(e) || Double.IsInfinity(e) ) return "NaN"; return (e*100.0).ToString("N6") + "%"; } /// <summary> /// Format a percent with no decimal places. /// </summary> /// <param name="e">The format to percent.</param> /// <returns>The formatted percent.</returns> public static String FormatPercentWhole(double e) { if (Double.IsNaN(e) || Double.IsInfinity(e)) return "NaN"; return (e*100.0).ToString("N0") + "%"; } /// <summary> /// Format a time span as seconds, minutes, hours and days. /// </summary> /// <param name="seconds">The number of seconds in the timespan.</param> /// <returns>The formatted timespan.</returns> public static String FormatTimeSpan(int seconds) { int secondsCount = seconds; int days = seconds/SecondsInaDay; secondsCount -= days*SecondsInaDay; int hours = secondsCount/SecondsInaHour; secondsCount -= hours*SecondsInaHour; int minutes = secondsCount/SecondsInaMinute; secondsCount -= minutes*SecondsInaMinute; var result = new StringBuilder(); if (days > 0) { result.Append(days); result.Append(days > 1 ? " days " : " day "); } result.Append(hours.ToString("00")); result.Append(':'); result.Append(minutes.ToString("00")); result.Append(':'); result.Append(secondsCount.ToString("00")); return result.ToString(); } /// <summary> /// Format a boolean to yes/no. /// </summary> /// <param name="p">The default answer.</param> /// <returns>A string form of the boolean.</returns> public static string FormatYesNo(bool p) { return p ? "Yes" : "No"; } } }
#region license /* DirectShowLib - Provide access to DirectShow interfaces via .NET Copyright (C) 2007 http://sourceforge.net/projects/directshownet/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Runtime.InteropServices; namespace DirectShowLib.DMO { #region Declarations sealed public class MediaParamTimeFormat { private MediaParamTimeFormat() { // Prevent people from trying to instantiate this class } /// <summary> GUID_TIME_REFERENCE </summary> public static readonly Guid Reference = new Guid(0x93ad712b, 0xdaa0, 0x4ffe, 0xbc, 0x81, 0xb0, 0xce, 0x50, 0x0f, 0xcd, 0xd9); /// <summary> GUID_TIME_MUSIC </summary> public static readonly Guid Music = new Guid(0x0574c49d, 0x5b04, 0x4b15, 0xa5, 0x42, 0xae, 0x28, 0x20, 0x30, 0x11, 0x7b); /// <summary> GUID_TIME_SAMPLES, audio capture category </summary> public static readonly Guid Samples = new Guid(0xa8593d05, 0x0c43, 0x4984, 0x9a, 0x63, 0x97, 0xaf, 0x9e, 0x02, 0xc4, 0xc0); } /// <summary> /// From MP_DATA /// </summary> [StructLayout(LayoutKind.Explicit)] public struct MPData { [FieldOffset(0)] public bool vBool; [FieldOffset(0)] public float vFloat; [FieldOffset(0)] public int vInt; } /// <summary> /// From MP_ENVELOPE_SEGMENT /// </summary> [StructLayout(LayoutKind.Sequential, Pack=8)] public struct MPEnvelopeSegment { public long rtStart; public long rtEnd; public MPData valStart; public MPData valEnd; public MPCaps iCurve; public MPFlags flags; } /// <summary> /// From MPF_ENVLP_* defines /// </summary> [Flags] public enum MPFlags { Standard = 0x0, BeginCurrentVal = 0x1, BeginNeutralVal = 0x2 } /// <summary> /// From MP_TYPE /// </summary> public enum MPType { // Fields BOOL = 2, ENUM = 3, FLOAT = 1, INT = 0, MAX = 4 } /// <summary> /// From MP_CAPS_CURVE* defines /// </summary> [Flags] public enum MPCaps { None = 0, Jump = 0x1, Linear = 0x2, Square = 0x4, InvSquare = 0x8, Sine = 0x10 } /// <summary> /// From MP_PARAMINFO /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Unicode)] public struct ParamInfo { public MPType mpType; public MPCaps mopCaps; public MPData mpdMinValue; public MPData mpdMaxValue; public MPData mpdNeutralValue; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=0x20)] public string szUnitText; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=0x20)] public string szLabel; } #endregion #region Interfaces [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("6D6CBB60-A223-44AA-842F-A2F06750BE6D")] public interface IMediaParamInfo { [PreserveSig] int GetParamCount( out int pdwParams ); [PreserveSig] int GetParamInfo( [In] int dwParamIndex, out ParamInfo pInfo ); [PreserveSig] int GetParamText( [In] int dwParamIndex, out IntPtr ip ); [PreserveSig] int GetNumTimeFormats( out int pdwNumTimeFormats ); [PreserveSig] int GetSupportedTimeFormat( [In] int dwFormatIndex, out Guid pguidTimeFormat ); [PreserveSig] int GetCurrentTimeFormat( out Guid pguidTimeFormat, out int pTimeData ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("6D6CBB61-A223-44AA-842F-A2F06750BE6E")] public interface IMediaParams { [PreserveSig] int GetParam( [In] int dwParamIndex, out MPData pValue ); [PreserveSig] int SetParam( [In] int dwParamIndex, [In] MPData value ); [PreserveSig] int AddEnvelope( [In] int dwParamIndex, [In] int cSegments, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] MPEnvelopeSegment [] pEnvelopeSegments ); [PreserveSig] int FlushEnvelope( [In] int dwParamIndex, [In] long refTimeStart, [In] long refTimeEnd ); [PreserveSig] int SetTimeFormat( [In] Guid MediaParamTimeFormat, [In] int mpTimeData ); } #endregion }
//------------------------------------------------------------------------------- // <copyright file="EventBrokerLogExtension.cs" company="Appccelerate"> // Copyright (c) 2008-2013 // // 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> //------------------------------------------------------------------------------- namespace SharpFlame.Core.Extensions { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Appccelerate.EventBroker; using Appccelerate.EventBroker.Exceptions; using Appccelerate.EventBroker.Extensions; using Appccelerate.EventBroker.Matchers; using NLog; /// <summary> /// Event broker extension that logs event broker activity. /// </summary> public class EventBrokerLogExtension : EventBrokerExtensionBase { /// <summary> /// Logger of this instance. /// </summary> private readonly Logger log; /// <summary> /// Initializes a new instance of the <see cref="EventBrokerLogExtension"/> class. /// </summary> public EventBrokerLogExtension() { this.log = LogManager.GetCurrentClassLogger(); } /// <summary> /// Initializes a new instance of the <see cref="EventBrokerLogExtension"/> class. /// </summary> /// <param name="logger">The logger to be used for log messages.</param> public EventBrokerLogExtension(string logger) { this.log = LogManager.GetLogger(logger); } /// <summary> /// Called when the event was fired (processing completed). /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public override void FiredEvent(IEventTopicInfo eventTopic, IPublication publication, object sender, EventArgs e) { INamedItem namedItem = publication.Publisher as INamedItem; if (namedItem != null) { this.log.Debug( "Fired event '{0}'. Invoked by publisher '{1}' with name '{2}' with sender '{3}' and EventArgs '{4}'.", eventTopic.Uri, publication.Publisher, namedItem.EventBrokerItemName, sender, e); } else { this.log.Debug( "Fired event '{0}'. Invoked by publisher '{1}' with sender '{2}' and EventArgs '{3}'.", eventTopic.Uri, publication.Publisher, sender, e); } } /// <summary> /// Called when an item was registered. /// </summary> /// <param name="item">The item that was registered.</param> public override void RegisteredItem(object item) { INamedItem namedItem = item as INamedItem; if (namedItem != null) { this.log.Debug("Registered item '{0}' with name '{1}'.", item, namedItem.EventBrokerItemName); } else { this.log.Debug("Registered item '{0}'.", item); } } /// <summary> /// Called when an item was unregistered. /// </summary> /// <param name="item">The item that was unregistered.</param> public override void UnregisteredItem(object item) { INamedItem namedItem = item as INamedItem; if (namedItem != null) { this.log.Debug("Unregistered item '{0}' with name '{1}'.", item, namedItem.EventBrokerItemName); } else { this.log.Debug("Unregistered item '{0}'.", item); } } /// <summary> /// Called after an event topic was created. /// </summary> /// <param name="eventTopic">The event topic.</param> public override void CreatedTopic(IEventTopicInfo eventTopic) { this.log.Debug("Topic created: '{0}'.", eventTopic.Uri); } /// <summary> /// Called after a publication was created. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> public override void CreatedPublication(IEventTopicInfo eventTopic, IPublication publication) { } /// <summary> /// Called after a subscription was created. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="subscription">The subscription.</param> public override void CreatedSubscription(IEventTopicInfo eventTopic, ISubscription subscription) { } /// <summary> /// Called when an event is fired. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public override void FiringEvent(IEventTopicInfo eventTopic, IPublication publication, object sender, EventArgs e) { this.log.Debug( "Firing event '{0}'. Invoked by publisher '{1}' with EventArgs '{2}'.", eventTopic.Uri, sender, e); } /// <summary> /// Called after a publication was added to an event topic. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> public override void AddedPublication(IEventTopicInfo eventTopic, IPublication publication) { using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { foreach (IPublicationMatcher publicationMatcher in publication.PublicationMatchers) { publicationMatcher.DescribeTo(writer); writer.Write(", "); } this.log.Debug( "Added publication '{0}.{1}' to topic '{2}' with matchers '{3}'.", publication.Publisher != null ? publication.Publisher.GetType().FullName : "-", publication.EventName, eventTopic.Uri, writer); } } /// <summary> /// Called after a publication was removed from an event topic. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> public override void RemovedPublication(IEventTopicInfo eventTopic, IPublication publication) { this.log.Debug( "Removed publication '{0}.{1}' from topic '{2}'.", publication.Publisher != null ? publication.Publisher.GetType().FullName : "-", publication.EventName, eventTopic.Uri); } /// <summary> /// Called after a subscription was added to an event topic. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="subscription">The subscription.</param> public override void AddedSubscription(IEventTopicInfo eventTopic, ISubscription subscription) { using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { foreach (ISubscriptionMatcher subscriptionMatcher in subscription.SubscriptionMatchers) { subscriptionMatcher.DescribeTo(writer); writer.Write(", "); } this.log.Debug( "Added subscription '{0}.{1}' to topic '{2}' with matchers '{3}'.", subscription.Subscriber != null ? subscription.Subscriber.GetType().FullName : "-", subscription.HandlerMethodName, eventTopic.Uri, writer); } } /// <summary> /// Called after a subscription was removed from an event topic. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="subscription">The subscription.</param> public override void RemovedSubscription(IEventTopicInfo eventTopic, ISubscription subscription) { this.log.Debug( "Removed subscription '{0}.{1}' from topic '{2}'.", subscription.Subscriber != null ? subscription.Subscriber.GetType().FullName : "-", subscription.HandlerMethodName, eventTopic.Uri); } /// <summary> /// Called before an event is relayed from the publication to the subscribers. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> /// <param name="subscription">The subscription.</param> /// <param name="handler">The handler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public override void RelayingEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, IHandler handler, object sender, EventArgs e) { this.log.Debug( "Relaying event '{6}' from publisher '{0}' [{1}] to subscriber '{2}' [{3}] with EventArgs '{4}' with handler '{5}'.", publication.Publisher, publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty, subscription.Subscriber, subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty, e, handler, eventTopic.Uri); } /// <summary> /// Called after the event was relayed from the publication to the subscribers. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> /// <param name="subscription">The subscription.</param> /// <param name="handler">The handler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public override void RelayedEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, IHandler handler, object sender, EventArgs e) { this.log.Debug( "Relayed event '{6}' from publisher '{0}' [{1}] to subscriber '{2}' [{3}] with EventArgs '{4}' with handler '{5}'.", publication.Publisher, publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty, subscription.Subscriber, subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty, e, handler, eventTopic.Uri); } /// <summary> /// Called when a publication or subscription matcher did not match and the event was not relayed to a subscription. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="publication">The publication.</param> /// <param name="subscription">The subscription.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public override void SkippedEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, object sender, EventArgs e) { List<IMatcher> matchers = new List<IMatcher>(); var publicationMatchers = from matcher in publication.PublicationMatchers where !matcher.Match(publication, subscription, e) select matcher; var subscriptionMatchers = from matcher in subscription.SubscriptionMatchers where !matcher.Match(publication, subscription, e) select matcher; matchers.AddRange(publicationMatchers); matchers.AddRange(subscriptionMatchers); StringBuilder sb = new StringBuilder(); using (TextWriter writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { foreach (IMatcher matcher in matchers) { matcher.DescribeTo(writer); writer.Write(", "); } } if (sb.Length > 0) { sb.Length -= 2; } this.log.Debug( "Skipped event '{0}' from publisher '{1}' [{2}] to subscriber '{3}' [{4}] with EventArgs '{5}' because the matchers '{6}' did not match.", eventTopic.Uri, publication.Publisher, publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty, subscription.Subscriber, subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty, e, sb); } /// <summary> /// Called when an exception occurred during event handling by a subscriber. /// </summary> /// <param name="eventTopic">The event topic.</param> /// <param name="exception">The exception.</param> /// <param name="context">The context providing information whether the exception is handled by an extension or is re-thrown.</param> public override void SubscriberExceptionOccurred(IEventTopicInfo eventTopic, Exception exception, ExceptionHandlingContext context) { this.log.Error( string.Format(CultureInfo.InvariantCulture, "An exception was thrown during handling the topic '{0}'", eventTopic.Uri), exception); } } }
/* * Copyright 2008 ZXing authors * * 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.Globalization; using System.Text; using System.Text.RegularExpressions; namespace ZXing.Client.Result { /// <summary> /// Represents a parsed result that encodes a calendar event at a certain time, optionally with attendees and a location. /// </summary> ///<author>Sean Owen</author> public sealed class CalendarParsedResult : ParsedResult { private static readonly Regex RFC2445_DURATION = new Regex(@"\A(?:" + "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?" + @")\z" #if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2) , RegexOptions.Compiled); #else ); #endif private static readonly long[] RFC2445_DURATION_FIELD_UNITS = { 7*24*60*60*1000L, // 1 week 24*60*60*1000L, // 1 day 60*60*1000L, // 1 hour 60*1000L, // 1 minute 1000L, // 1 second }; private static readonly Regex DATE_TIME = new Regex(@"\A(?:" + "[0-9]{8}(T[0-9]{6}Z?)?" + @")\z" #if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2) , RegexOptions.Compiled); #else ); #endif private readonly String summary; private readonly DateTime start; private readonly bool startAllDay; private readonly DateTime? end; private readonly bool endAllDay; private readonly String location; private readonly String organizer; private readonly String[] attendees; private readonly String description; private readonly double latitude; private readonly double longitude; public CalendarParsedResult(String summary, String startString, String endString, String durationString, String location, String organizer, String[] attendees, String description, double latitude, double longitude) : base(ParsedResultType.CALENDAR) { this.summary = summary; try { this.start = parseDate(startString); } catch (Exception pe) { throw new ArgumentException(pe.ToString()); } if (endString == null) { long durationMS = parseDurationMS(durationString); end = durationMS < 0L ? null : (DateTime?) start + new TimeSpan(0, 0, 0, 0, (int) durationMS); } else { try { this.end = parseDate(endString); } catch (Exception pe) { throw new ArgumentException(pe.ToString()); } } this.startAllDay = startString.Length == 8; this.endAllDay = endString != null && endString.Length == 8; this.location = location; this.organizer = organizer; this.attendees = attendees; this.description = description; this.latitude = latitude; this.longitude = longitude; var result = new StringBuilder(100); maybeAppend(summary, result); maybeAppend(format(startAllDay, start), result); maybeAppend(format(endAllDay, end), result); maybeAppend(location, result); maybeAppend(organizer, result); maybeAppend(attendees, result); maybeAppend(description, result); displayResultValue = result.ToString(); } public String Summary { get { return summary; } } /// <summary> /// Gets the start. /// </summary> public DateTime Start { get { return start; } } /// <summary> /// Determines whether [is start all day]. /// </summary> /// <returns>if start time was specified as a whole day</returns> public bool isStartAllDay() { return startAllDay; } /// <summary> /// event end <see cref="DateTime"/>, or null if event has no duration /// </summary> public DateTime? End { get { return end; } } /// <summary> /// Gets a value indicating whether this instance is end all day. /// </summary> /// <value>true if end time was specified as a whole day</value> public bool isEndAllDay { get { return endAllDay; } } public String Location { get { return location; } } public String Organizer { get { return organizer; } } public String[] Attendees { get { return attendees; } } public String Description { get { return description; } } public double Latitude { get { return latitude; } } public double Longitude { get { return longitude; } } /// <summary> /// Parses a string as a date. RFC 2445 allows the start and end fields to be of type DATE (e.g. 20081021) /// or DATE-TIME (e.g. 20081021T123000 for local time, or 20081021T123000Z for UTC). /// </summary> /// <param name="when">The string to parse</param> /// <returns></returns> /// <exception cref="ArgumentException">if not a date formatted string</exception> private static DateTime parseDate(String when) { if (!DATE_TIME.Match(when).Success) { throw new ArgumentException(String.Format("no date format: {0}", when)); } if (when.Length == 8) { // Show only year/month/day // For dates without a time, for purposes of interacting with Android, the resulting timestamp // needs to be midnight of that day in GMT. See: // http://code.google.com/p/android/issues/detail?id=8330 // format.setTimeZone(TimeZone.getTimeZone("GMT")); return DateTime.ParseExact(when, "yyyyMMdd", CultureInfo.InvariantCulture); } // The when string can be local time, or UTC if it ends with a Z if (when.Length == 16 && when[15] == 'Z') { var milliseconds = parseDateTimeString(when.Substring(0, 15)); //Calendar calendar = new GregorianCalendar(); // Account for time zone difference //milliseconds += calendar.get(Calendar.ZONE_OFFSET); // Might need to correct for daylight savings time, but use target time since // now might be in DST but not then, or vice versa //calendar.setTime(new Date(milliseconds)); //return milliseconds + calendar.get(Calendar.DST_OFFSET); milliseconds = TimeZoneInfo.ConvertTime(milliseconds, TimeZoneInfo.Local); return milliseconds; } return parseDateTimeString(when); } private static String format(bool allDay, DateTime? date) { if (date == null) { return null; } if (allDay) return date.Value.ToString("D", CultureInfo.CurrentCulture); return date.Value.ToString("F", CultureInfo.CurrentCulture); } private static long parseDurationMS(String durationString) { if (durationString == null) { return -1L; } var m = RFC2445_DURATION.Match(durationString); if (!m.Success) { return -1L; } long durationMS = 0L; for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.Length; i++) { String fieldValue = m.Groups[i + 1].Value; if (!String.IsNullOrEmpty(fieldValue)) { durationMS += RFC2445_DURATION_FIELD_UNITS[i]*Int32.Parse(fieldValue); } } return durationMS; } private static DateTime parseDateTimeString(String dateTimeString) { return DateTime.ParseExact(dateTimeString, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture); } } }
// // FacebookProfile.cs // s.im.pl serialization // // Generated by MetaMetadataDotNetTranslator. // Copyright 2017 Interface Ecology Lab. // using Ecologylab.BigSemantics.Generated.Library; using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS; using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.BlogNS; using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.BlogPostNS; using Ecologylab.BigSemantics.Generated.Library.PersonNS.AuthorNS; using Ecologylab.BigSemantics.MetaMetadataNS; using Ecologylab.BigSemantics.MetadataNS; using Ecologylab.BigSemantics.MetadataNS.Builtins; using Ecologylab.Collections; using Simpl.Fundamental.Generic; using Simpl.Serialization; using Simpl.Serialization.Attributes; using System; using System.Collections; using System.Collections.Generic; namespace Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.BlogNS { [SimplInherit] public class FacebookProfile : SocialMediaProfile { [SimplComposite] [SimplTag("coverPhoto")] [MmName("coverPhoto")] private Image coverPhoto; [SimplCollection("facebook_user")] [MmName("facebook")] private List<FacebookUser> facebook; /// <summary> /// mainFeed /// </summary> [SimplCollection("social_media_post")] [MmName("feed")] private List<SocialMediaPost> feed; [SimplCollection("social_media_feed")] [SimplTag("Friends")] [MmName("Friends")] private List<SocialMediaFeed> Friends; [SimplCollection("social_media_feed")] [SimplTag("Photos")] [MmName("Photos")] private List<SocialMediaFeed> Photos; [SimplCollection("social_media_feed")] [SimplTag("Videos")] [MmName("Videos")] private List<SocialMediaFeed> Videos; [SimplCollection("interest_group")] [SimplTag("Sports")] [MmName("Sports")] private List<InterestGroup> Sports; [SimplCollection("interest_group")] [SimplTag("Music")] [MmName("Music")] private List<InterestGroup> Music; [SimplCollection("interest_group")] [SimplTag("Movies")] [MmName("Movies")] private List<InterestGroup> Movies; [SimplCollection("interest_group")] [SimplTag("appsAndGames")] [MmName("appsAndGames")] private List<InterestGroup> appsAndGames; [SimplCollection("interest_group")] [SimplTag("Likes")] [MmName("Likes")] private List<InterestGroup> Likes; [SimplCollection("social_media_feed")] [MmName("check_ins")] private List<SocialMediaFeed> checkIns; public FacebookProfile() { } public FacebookProfile(MetaMetadataCompositeField mmd) : base(mmd) { } public Image CoverPhoto { get{return coverPhoto;} set { if (this.coverPhoto != value) { this.coverPhoto = value; // TODO we need to implement our property change notification mechanism. } } } public List<FacebookUser> Facebook { get{return facebook;} set { if (this.facebook != value) { this.facebook = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaPost> Feed { get{return feed;} set { if (this.feed != value) { this.feed = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaFeed> FriendsProp { get{return Friends;} set { if (this.Friends != value) { this.Friends = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaFeed> PhotosProp { get{return Photos;} set { if (this.Photos != value) { this.Photos = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaFeed> VideosProp { get{return Videos;} set { if (this.Videos != value) { this.Videos = value; // TODO we need to implement our property change notification mechanism. } } } public List<InterestGroup> SportsProp { get{return Sports;} set { if (this.Sports != value) { this.Sports = value; // TODO we need to implement our property change notification mechanism. } } } public List<InterestGroup> MusicProp { get{return Music;} set { if (this.Music != value) { this.Music = value; // TODO we need to implement our property change notification mechanism. } } } public List<InterestGroup> MoviesProp { get{return Movies;} set { if (this.Movies != value) { this.Movies = value; // TODO we need to implement our property change notification mechanism. } } } public List<InterestGroup> AppsAndGames { get{return appsAndGames;} set { if (this.appsAndGames != value) { this.appsAndGames = value; // TODO we need to implement our property change notification mechanism. } } } public List<InterestGroup> LikesProp { get{return Likes;} set { if (this.Likes != value) { this.Likes = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaFeed> CheckIns { get{return checkIns;} set { if (this.checkIns != value) { this.checkIns = value; // TODO we need to implement our property change notification mechanism. } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary>The class that contains the unit tests of the ThreadLocal.</summary> public static class ThreadLocalTests { /// <summary>Tests for the Ctor.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest1_Ctor() { ThreadLocal<object> testObject; testObject = new ThreadLocal<object>(); testObject = new ThreadLocal<object>(true); testObject = new ThreadLocal<object>(() => new object()); testObject = new ThreadLocal<object>(() => new object(), true); } [Fact] public static void RunThreadLocalTest1_Ctor_Negative() { try { new ThreadLocal<object>(null); } catch (ArgumentNullException) { // No other exception should be thrown. // With a previous issue, if the constructor threw an exception, the finalizer would throw an exception as well. } } /// <summary>Tests for the ToString.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest2_ToString() { ThreadLocal<object> tlocal = new ThreadLocal<object>(() => (object)1); Assert.Equal(1.ToString(), tlocal.ToString()); } /// <summary>Tests for the Initialized property.</summary> /// <returns>True if the tests succeeds, false otherwise.</returns> [Fact] public static void RunThreadLocalTest3_IsValueCreated() { ThreadLocal<string> tlocal = new ThreadLocal<string>(() => "Test"); Assert.False(tlocal.IsValueCreated); string temp = tlocal.Value; Assert.True(tlocal.IsValueCreated); } [Fact] public static void RunThreadLocalTest4_Value() { ThreadLocal<string> tlocal = null; // different threads call Value int numOfThreads = 10; Task[] threads = new Task[numOfThreads]; object alock = new object(); List<string> seenValuesFromAllThreads = new List<string>(); int counter = 0; tlocal = new ThreadLocal<string>(() => (++counter).ToString()); //CancellationToken ct = new CancellationToken(); for (int i = 0; i < threads.Length; ++i) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. threads[i] = new Task(() => { string value = tlocal.Value; Debug.WriteLine("Val: " + value); seenValuesFromAllThreads.Add(value); }, TaskCreationOptions.LongRunning); threads[i].Start(TaskScheduler.Default); threads[i].Wait(); } Assert.Equal(Enumerable.Range(1, threads.Length).Select(x => x.ToString()), seenValuesFromAllThreads); } [Fact] public static void RunThreadLocalTest4_Value_NegativeCases() { ThreadLocal<string> tlocal = null; Assert.Throws<InvalidOperationException>(() => { int x = 0; tlocal = new ThreadLocal<string>(delegate { if (x++ < 5) return tlocal.Value; else return "Test"; }); string str = tlocal.Value; }); } [Fact] public static void RunThreadLocalTest5_Dispose() { // test recycling the combination index; ThreadLocal<string> tl = new ThreadLocal<string>(() => null); Assert.False(tl.IsValueCreated); Assert.Null(tl.Value); // Test that a value is not kept alive by a departed thread var threadLocal = new ThreadLocal<SetMreOnFinalize>(); var mres = new ManualResetEventSlim(false); // (Careful when editing this test: saving the created thread into a local variable would likely break the // test in Debug build.) // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. new Task(() => { threadLocal.Value = new SetMreOnFinalize(mres); }, TaskCreationOptions.LongRunning).Start(TaskScheduler.Default); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 5000); Assert.True(mres.IsSet); } [Fact] public static void RunThreadLocalTest5_Dispose_Negative() { ThreadLocal<string> tl = new ThreadLocal<string>(() => "dispose test"); string value = tl.Value; tl.Dispose(); Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.Value; }); // Failure Case: The Value property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { bool tmp = tl.IsValueCreated; }); // Failure Case: The IsValueCreated property of the disposed ThreadLocal object should throw ODE Assert.Throws<ObjectDisposedException>(() => { string tmp = tl.ToString(); }); // Failure Case: The ToString method of the disposed ThreadLocal object should throw ODE } [Fact] public static void RunThreadLocalTest6_SlowPath() { // the maximum fast path instances for each type is 16 ^ 3 = 4096, when this number changes in the product code, it should be changed here as well int MaximumFastPathPerInstance = 4096; ThreadLocal<int>[] locals_int = new ThreadLocal<int>[MaximumFastPathPerInstance + 10]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); var val = locals_int[i].Value; } Assert.Equal(Enumerable.Range(0, locals_int.Length), locals_int.Select(x => x.Value)); // The maximum slowpath for all Ts is MaximumFastPathPerInstance * 4; locals_int = new ThreadLocal<int>[4096]; ThreadLocal<long>[] locals_long = new ThreadLocal<long>[4096]; ThreadLocal<float>[] locals_float = new ThreadLocal<float>[4096]; ThreadLocal<double>[] locals_double = new ThreadLocal<double>[4096]; for (int i = 0; i < locals_int.Length; i++) { locals_int[i] = new ThreadLocal<int>(() => i); locals_long[i] = new ThreadLocal<long>(() => i); locals_float[i] = new ThreadLocal<float>(() => i); locals_double[i] = new ThreadLocal<double>(() => i); } ThreadLocal<string> local = new ThreadLocal<string>(() => "slow path"); Assert.Equal("slow path", local.Value); } private class ThreadLocalWeakReferenceTest { private object _foo; private WeakReference _wFoo; [MethodImplAttribute(MethodImplOptions.NoInlining)] private void Method() { _foo = new object(); _wFoo = new WeakReference(_foo); new ThreadLocal<object>() { Value = _foo }.Dispose(); } public void Run() { Method(); _foo = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // s_foo should have been garbage collected Assert.False(_wFoo.IsAlive); } } [Fact] public static void RunThreadLocalTest7_WeakReference() { var threadLocalWeakReferenceTest = new ThreadLocalWeakReferenceTest(); threadLocalWeakReferenceTest.Run(); } [Fact] public static void RunThreadLocalTest8_Values() { // Test adding values and updating values { var threadLocal = new ThreadLocal<int>(true); Assert.True(threadLocal.Values.Count == 0, "RunThreadLocalTest8_Values: Expected thread local to initially have 0 values"); Assert.True(threadLocal.Value == 0, "RunThreadLocalTest8_Values: Expected initial value of 0"); Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to now be 1 from initialized value"); Assert.True(threadLocal.Values[0] == 0, "RunThreadLocalTest8_Values: Expected values to contain initialized value"); threadLocal.Value = 1000; Assert.True(threadLocal.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to still be 1 after updating existing value"); Assert.True(threadLocal.Values[0] == 1000, "RunThreadLocalTest8_Values: Expected values to contain updated value"); ((IAsyncResult)Task.Run(() => threadLocal.Value = 1001)).AsyncWaitHandle.WaitOne(); Assert.True(threadLocal.Values.Count == 2, "RunThreadLocalTest8_Values: Expected values count to be 2 now that another thread stored a value"); Assert.True(threadLocal.Values.Contains(1000) && threadLocal.Values.Contains(1001), "RunThreadLocalTest8_Values: Expected values to contain both thread's values"); int numTasks = 1000; Task[] allTasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) { // We are creating the task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. var task = Task.Factory.StartNew(() => threadLocal.Value = i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(); } var values = threadLocal.Values; if (values.Count != 1002) { string message = "RunThreadLocalTest8_Values: Expected values to contain both previous values and 1000 new values. Actual count: " + values.Count + '.'; if (values.Count != 0) { message += " Missing items:"; for (int i = 0; i < 1002; i++) { if (!values.Contains(i)) { message += " " + i; } } } Assert.True(false, message); } for (int i = 0; i < 1000; i++) { Assert.True(values.Contains(i), "RunThreadLocalTest8_Values: Expected values to contain value for thread #: " + i); } threadLocal.Dispose(); } // Test that thread values remain after threads depart { var tl = new ThreadLocal<string>(true); var t = Task.Run(() => tl.Value = "Parallel"); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected values count to be 1 from other thread's initialization"); Assert.True(tl.Values.Contains("Parallel"), "RunThreadLocalTest8_Values: Expected values to contain 'Parallel'"); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void RunThreadLocalTest8Helper(ManualResetEventSlim mres) { var tl = new ThreadLocal<object>(true); var t = Task.Run(() => tl.Value = new SetMreOnFinalize(mres)); t.Wait(); t = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(tl.Values.Count == 1, "RunThreadLocalTest8_Values: Expected other thread to have set value"); Assert.True(tl.Values[0] is SetMreOnFinalize, "RunThreadLocalTest8_Values: Expected other thread's value to be of the right type"); tl.Dispose(); object values; Assert.Throws<ObjectDisposedException>(() => values = tl.Values); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "This test requires precise stack scanning")] public static void RunThreadLocalTest8_Values_NegativeCases() { // Test that Dispose works and that objects are released on dispose { var mres = new ManualResetEventSlim(); RunThreadLocalTest8Helper(mres); SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return mres.IsSet; }, 5000); Assert.True(mres.IsSet, "RunThreadLocalTest8_Values: Expected thread local to release the object and for it to be finalized"); } // Test that Values property throws an exception unless true was passed into the constructor { ThreadLocal<int> t = new ThreadLocal<int>(); t.Value = 5; Exception exceptionCaught = null; try { var randomValue = t.Values.Count; } catch (Exception ex) { exceptionCaught = ex; } Assert.True(exceptionCaught != null, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. No exception was thrown."); Assert.True( exceptionCaught != null && exceptionCaught is InvalidOperationException, "RunThreadLocalTest8_Values: Expected Values to throw an InvalidOperationException. Wrong exception was thrown: " + exceptionCaught.GetType().ToString()); } } [Fact] public static void RunThreadLocalTest9_Uninitialized() { for (int iter = 0; iter < 10; iter++) { ThreadLocal<int> t1 = new ThreadLocal<int>(); t1.Value = 177; ThreadLocal<int> t2 = new ThreadLocal<int>(); Assert.True(!t2.IsValueCreated, "RunThreadLocalTest9_Uninitialized: The ThreadLocal instance should have been uninitialized."); } } [Fact] [OuterLoop] public static void ValuesGetterDoesNotThrowUnexpectedExceptionWhenDisposed() { var startTest = new ManualResetEvent(false); var gotUnexpectedException = new ManualResetEvent(false); ThreadLocal<int> threadLocal = null; bool stop = false; Action waitForCreatorDisposer; Thread creatorDisposer = ThreadTestHelpers.CreateGuardedThread(out waitForCreatorDisposer, () => { startTest.CheckedWait(); do { var tl = new ThreadLocal<int>(trackAllValues: true); Volatile.Write(ref threadLocal, tl); tl.Value = 1; tl.Dispose(); } while (!Volatile.Read(ref stop)); }); creatorDisposer.IsBackground = true; creatorDisposer.Start(); int readerCount = Math.Max(1, Environment.ProcessorCount - 1); var waitsForReader = new Action[readerCount]; for (int i = 0; i < readerCount; ++i) { Thread reader = ThreadTestHelpers.CreateGuardedThread(out waitsForReader[i], () => { startTest.CheckedWait(); do { var tl = Volatile.Read(ref threadLocal); if (tl == null) { continue; } try { IList<int> values = tl.Values; } catch (ObjectDisposedException) { } catch { gotUnexpectedException.Set(); throw; } } while (!Volatile.Read(ref stop)); }); reader.IsBackground = true; reader.Start(); } startTest.Set(); bool failed = gotUnexpectedException.WaitOne(500); Volatile.Write(ref stop, true); foreach (Action waitForReader in waitsForReader) { waitForReader(); } waitForCreatorDisposer(); Assert.False(failed); } private class SetMreOnFinalize { private ManualResetEventSlim _mres; public SetMreOnFinalize(ManualResetEventSlim mres) { _mres = mres; } ~SetMreOnFinalize() { _mres.Set(); } } } }
using System; using System.IO; using EarLab.Analysis; using EarLab.ReaderWriters; namespace EarLab.Analysis { struct AnalysisResults { public double [,] Output; public double MinValue, MaxValue, MinX, MaxX, MinY, MaxY; public string ColorbarName, XAxisName, YAxisName, Title; } class AnalysisTools { public static string [] GetAnalysisMenus() { string [] ReturnValue = new string [5]; ReturnValue[0] = "Fourier Transform"; ReturnValue[1] = "Synchronization"; ReturnValue[2] = "Auto Correlation"; ReturnValue[3] = "Spatial Frequency"; ReturnValue[4] = "Period Histogram"; return ReturnValue; } public static string GetAnalysisMenuQuestion(int theAnalysis, out double defaultValue) { defaultValue = 0; AnalysisType whichAnalysis = (AnalysisType)theAnalysis; switch (whichAnalysis) { case AnalysisType.FourierTransform: defaultValue = 2000; return "Please enter the cutoff frequency, in Hertz"; case AnalysisType.Synchronization: defaultValue = 2000; return "Please enter the cutoff frequency, in Hertz"; case AnalysisType.AutoCorrelation: defaultValue = 20; return "Please enter the cutoff delay, in milliseconds"; case AnalysisType.SpatialFrequency: return ""; case AnalysisType.PeriodHistogram: defaultValue = 10; return "Please enter the period, in milliseconds"; default: return ""; } } // Waveform analysis public static void Analyze(int theAnalysis, double [,] Input, double SampleRate_Hz, double Parameter, out AnalysisResults Results) { Results = new AnalysisResults(); Results.MinY = 0; Results.MaxY = Input.GetLength(1); Results.Output = Analyze(theAnalysis, Input, SampleRate_Hz, Parameter, out Results.MinValue, out Results.MaxValue, out Results.ColorbarName, out Results.MinX, out Results.MaxX, out Results.XAxisName, out Results.MinY, out Results.MaxY, out Results.YAxisName, out Results.Title); } // Spike analysis public static void Analyze(int theAnalysis, ReaderWriterBinarySpikes.SpikeItem[] Input, double SampleRate_Hz, double Parameter, out AnalysisResults Results) { Results = new AnalysisResults(); Results.MinY = 0; Results.MaxY = Input.GetLength(1); //Results.Output = Analyze(theAnalysis, Input, SampleRate_Hz, Parameter, // out Results.MinValue, out Results.MaxValue, out Results.ColorbarName, // out Results.MinX, out Results.MaxX, out Results.XAxisName, // out Results.MinY, out Results.MaxY, out Results.YAxisName, // out Results.Title); } public static double [,] Analyze(int theAnalysis, double [,] Input, double SampleRate_Hz, double Parameter, out double MinValue, out double MaxValue, out string ColorbarName, out double MinX, out double MaxX, out string XAxisName, out double MinY, out double MaxY, out string YAxisName, out string Title) { int InputXSize, InputYSize; int OutputXSize, OutputYSize; int Period_Samples; double FrequencyStepSize_Hz; int CutoffFrequencyIndex; double [,] Output = null; double [] IntermediateOutput = null; double [] IntermediateInput; AnalysisType whichAnalysis = (AnalysisType)theAnalysis; MinValue = double.MaxValue; MaxValue = double.MinValue; ColorbarName = ""; MinX = 0; MaxX = Input.GetLength(0); MinY = 1; MaxY = Input.GetLength(1); YAxisName = ""; XAxisName = ""; Title = "Analysis"; InputXSize = Input.GetLength(0); InputYSize = Input.GetLength(1); if (whichAnalysis == AnalysisType.SpatialFrequency) { IntermediateInput = new double [InputYSize]; OutputXSize = Input.GetLength(0); ColorbarName = "Amplitude"; XAxisName = "Sample Number"; YAxisName = "Spatial Frequency (Cycles)"; Title = "Spatial Frequency"; for (int x = 0; x < InputXSize; x++) { for (int y = 0; y < InputYSize; y++) IntermediateInput[y] = Input[x, y]; IntermediateOutput = SpatialFrequency(IntermediateInput); OutputYSize = IntermediateOutput.Length; if (Output == null) Output = new double [OutputXSize, OutputYSize]; for (int y = 0; y < OutputYSize; y++) { MinValue = Math.Min(MinValue, IntermediateOutput[y]); MaxValue = Math.Max(MaxValue, IntermediateOutput[y]); Output[x, y] = IntermediateOutput[y]; } // for (int y = 0; y < OutputYSize; y++) } // for (int x = 0; x < InputXSize; x++) MaxY = Output.GetLength(1); } // if (whichAnalysis == AnalysisType.SpatialFrequency) else { IntermediateInput = new double [InputXSize]; OutputYSize = InputYSize; for (int y = 0; y < InputYSize; y++) { for (int x = 0; x < InputXSize; x++) IntermediateInput[x] = Input[x, y]; switch (whichAnalysis) { case AnalysisType.FourierTransform: IntermediateOutput = RFFT(IntermediateInput); FrequencyStepSize_Hz = (SampleRate_Hz / 2.0) / IntermediateOutput.Length; CutoffFrequencyIndex = (int)(Parameter / FrequencyStepSize_Hz) + 1; ColorbarName = "Amplitude"; XAxisName = "Frequency (Hz)"; YAxisName = "Frequency Channel"; MaxX = SampleRate_Hz / 2.0; YAxisName = "Frequency Channel"; Title = "Fourier Analysis"; if (CutoffFrequencyIndex < 2) CutoffFrequencyIndex = 2; if ((CutoffFrequencyIndex > 0) && (CutoffFrequencyIndex < IntermediateOutput.Length)) { // In this case, parameter is used as a cutoff freq for display double [] Temp = null; Temp = new double [CutoffFrequencyIndex]; for (int i = 0; i < Temp.Length; i++) Temp[i] = IntermediateOutput[i]; IntermediateOutput = Temp; Temp = null; } // if ((CutoffFrequencyIndex > 0) && (CutoffFrequencyIndex < IntermediateOutput.Length)) MaxX = Parameter; break; case AnalysisType.Synchronization: IntermediateOutput = SyncCoefficients(IntermediateInput); FrequencyStepSize_Hz = (SampleRate_Hz / 2.0) / IntermediateOutput.Length; CutoffFrequencyIndex = (int)(Parameter / FrequencyStepSize_Hz) + 1; ColorbarName = "Sync Coefficient"; XAxisName = "Frequency (Hz)"; YAxisName = "Frequency Channel"; Title = "Synchronization"; if (CutoffFrequencyIndex < 2) CutoffFrequencyIndex = 2; if ((CutoffFrequencyIndex > 0) && (CutoffFrequencyIndex < IntermediateOutput.Length)) { // In this case, parameter is used as a cutoff freq for display double [] Temp = null; Temp = new double [CutoffFrequencyIndex]; for (int i = 0; i < Temp.Length; i++) Temp[i] = IntermediateOutput[i]; IntermediateOutput = Temp; Temp = null; } // if ((CutoffFrequencyIndex > 0) && (CutoffFrequencyIndex < IntermediateOutput.Length)) MaxX = Parameter; break; case AnalysisType.AutoCorrelation: Period_Samples = (int)((Parameter / 1000) * SampleRate_Hz); IntermediateOutput = Autocorrelation(IntermediateInput); ColorbarName = "Energy"; MaxX = Parameter; XAxisName = "Delay (mS)"; YAxisName = "Frequency Channel"; Title = "Auto Correlation"; if ((Period_Samples > 0) && (Period_Samples < IntermediateOutput.Length)) { double [] Temp; Temp = new double [Period_Samples]; for (int i = 0; i < Temp.Length; i++) Temp[i] = IntermediateOutput[i]; IntermediateOutput = Temp; Temp = null; } // if ((Parameter > 0) && (Parameter < MaxX)) break; case AnalysisType.PeriodHistogram: Period_Samples = (int)((Parameter / 1000) * SampleRate_Hz); IntermediateOutput = PeriodHistogram(IntermediateInput, Period_Samples); ColorbarName = "Amplitude"; MaxX = Parameter; XAxisName = "Time (mS)"; YAxisName = "Frequency Channel"; Title = "Period Histogram"; break; default: break; } // switch (whichAnalysis) OutputXSize = IntermediateOutput.Length; if (Output == null) Output = new double [OutputXSize, OutputYSize]; for (int x = 0; x < OutputXSize; x++) { MinValue = Math.Min(MinValue, IntermediateOutput[x]); MaxValue = Math.Max(MaxValue, IntermediateOutput[x]); Output[x, y] = IntermediateOutput[x]; } // for (int x = 0; x < OutputXSize; x++) } // for (int y = 0; y < InputYSize; y++) } // if (whichAnalysis == AnalysisType.SpatialFrequency) else return Output; } // Analyze() public static double [] PeriodHistogram(double [] Signal, int Period_Samples) { if (Period_Samples < 1) Period_Samples = 2; if (Signal.Length < Period_Samples) Period_Samples = Signal.Length; int nPeriods = Signal.Length / Period_Samples; double [] ReturnValue = new double[Period_Samples]; for (int j = 0; j < nPeriods; j++) for (int i = 0; i < Period_Samples; i++) ReturnValue[i] += Signal[(j * Period_Samples) + i]; for (int i = 0; i < Period_Samples; i++) ReturnValue[i] /= nPeriods; return ReturnValue; } public static double [] RFFT(double [] Signal) { Complex [] CompSignal; CompSignal = ConvertToComplex(HanningWindow(Signal)); Fourier.FFT(CompSignal, FourierDirection.Forward); return NormalizedPositiveFrequencies(CompSignal); } public static double [] SyncCoefficients(double [] Signal) { Complex [] CompSignal; double Sync; double [] ReturnValue; CompSignal = ConvertToComplex(HanningWindow(Signal)); Fourier.FFT(CompSignal, FourierDirection.Forward); Sync = CompSignal[0].Magnitude; ReturnValue = new double [CompSignal.Length / 2]; for (int i = 0; i < ReturnValue.Length; i++) ReturnValue[i] = CompSignal[i].Magnitude / Sync; ReturnValue[0] = 0; return ReturnValue; } public static double [] Autocorrelation(double [] Signal) { Complex [] InputSignal; Complex [] Correlation; InputSignal = ConvertToComplex(HanningWindow(Signal)); Fourier.FFT(InputSignal, FourierDirection.Forward); InputSignal[0].Re = 0; InputSignal[0].Im = 0; Correlation = new Complex[InputSignal.Length]; for (int i = 0; i < InputSignal.Length; i++) { InputSignal[i] = InputSignal[i] / InputSignal.Length; Correlation[i] = InputSignal[i] * InputSignal[i].Conjugate; } Fourier.FFT(Correlation, FourierDirection.Backward); // Normalize by the value in the zeroth element of the array return MagnitudeAndSign(Correlation); } public static double [] Crosscorrelation(Complex [] SignalConjugate, double [] Signal) { Complex [] InputSignal; Complex [] Correlation; InputSignal = ConvertToComplex(HanningWindow(Signal)); Fourier.FFT(InputSignal, FourierDirection.Forward); InputSignal[0].Re = 0; InputSignal[0].Im = 0; SignalConjugate[0].Re = 0; SignalConjugate[0].Im = 0; Correlation = new Complex[InputSignal.Length]; for (int i = 0; i < InputSignal.Length; i++) { InputSignal[i] = InputSignal[i] / InputSignal.Length; Correlation[i] = InputSignal[i] * SignalConjugate[i]; } Fourier.FFT(Correlation, FourierDirection.Backward); // Normalize by the product of the standard deviations of the signal return MagnitudeAndSign(Correlation); } private static double [] MagnitudeAndSign(Complex [] Signal) { double [] ReturnValue; ReturnValue = new double [Signal.Length / 2]; for (int i = 0; i < ReturnValue.Length; i++) ReturnValue[i] = Signal[i].Magnitude * Math.Cos(Signal[i].Phase); return ReturnValue; } private static double [] SpatialFrequency(double [] Signal) { Complex [] CompSignal; CompSignal = ConvertToComplex(HanningWindow(Signal)); Fourier.FFT(CompSignal, FourierDirection.Forward); return NormalizedPositiveFrequencies(CompSignal); } private static Complex [] ConvertToComplex(double [] Signal) { Complex [] Temp = new Complex[Signal.Length]; for (int i = 0; i < Signal.Length; i++) Temp[i].Re = Signal[i]; return Temp; } private static double [] NormalizedPositiveFrequencies(Complex [] Data) { double [] Output = new double[Data.Length / 2]; for (int i = 0; i < Output.Length; i++) Output[i] = (Data[i].Magnitude / Output.Length) * 2; return Output; } private static double [] HanningWindow(double [] InputData) { int InputLength, OutputLength; int i, n, last1 = 0; double [] Window; double [] OutputData; double theta; InputLength = InputData.Length; n = InputLength; if (n == 0) return null; // Find the smallest array whose length is a power of two that will contain the data vector. // This means that if 'InputData' is 500 points long, we want to put it into a 512-point array for (i = 0; i < 32; i++) { if ((n & 0x00000001) == 0x00000001) last1 = i; // last1 gets the index of the highest bit set in the size of the array n = n >> 1; } n = InputLength; if ((1 << last1) < n) // If the length of the array is not a power of two last1++; // bump the index up one more bit if (last1 > 32) throw new ApplicationException("HanningWindow: Maximum array size exceeded"); OutputLength = 1 << last1; // Now, OutputLength contains the length of the smallest power-of-two array that will contain the passed-in data OutputData = new double [OutputLength]; Window = new double [OutputLength]; theta = (2.0 * Math.PI) / OutputLength; for (i = 0; i < OutputLength; i++) { OutputData[i] = 0; Window[i] = (1.0 - Math.Cos(theta * i)) / 2.0; } n = (OutputLength - InputLength) / 2; for (i = 0; i < InputLength; i++) OutputData[i + n] = InputData[i]; for (i = 0; i < OutputLength; i++) OutputData[i] *= Window[i]; return OutputData; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using NUnit.Framework; using NServiceKit.CacheAccess; using NServiceKit.Common; using NServiceKit.DesignPatterns.Model; using NServiceKit.Logging; using NServiceKit.Logging.Support.Logging; namespace NServiceKit.Redis.Tests { [TestFixture, Category("Integration")] public class UserSessionTests { static UserSessionTests() { LogManager.LogFactory = new ConsoleLogFactory(); } //MasterUser master; static readonly Guid UserClientGlobalId1 = new Guid("71A30DE3-D7AF-4B8E-BCA2-AB646EE1F3E9"); static readonly Guid UserClientGlobalId2 = new Guid("A8D300CF-0414-4C99-A495-A7F34C93CDE1"); static readonly string UserClientKey = new Guid("10B7D0F7-4D4E-4676-AAC7-CF0234E9133E").ToString("N"); static readonly Guid UserId = new Guid("5697B030-A369-43A2-A842-27303A0A62BC"); private const string UserName = "User1"; private const string ShardId = "0"; readonly UserClientSession session = new UserClientSession( Guid.NewGuid(), UserId, "192.168.0.1", UserClientKey, UserClientGlobalId1); private RedisClient redisCache; [SetUp] public void OnBeforeEachTest() { redisCache = new RedisClient(TestConfig.SingleHost); redisCache.FlushAll(); //master = UserMasterDataAccessModel.Instance.MasterUsers.NewDataAccessObject(true); } public CachedUserSessionManager GetCacheManager(ICacheClient cacheClient) { return new CachedUserSessionManager(cacheClient); } private static void AssertClientSessionsAreEqual( UserClientSession clientSession, UserClientSession resolvedClientSession) { Assert.That(resolvedClientSession.Id, Is.EqualTo(clientSession.Id)); Assert.That(resolvedClientSession.Base64ClientModulus, Is.EqualTo(clientSession.Base64ClientModulus)); Assert.That(resolvedClientSession.IPAddress, Is.EqualTo(clientSession.IPAddress)); Assert.That(resolvedClientSession.UserClientGlobalId, Is.EqualTo(clientSession.UserClientGlobalId)); Assert.That(resolvedClientSession.UserId, Is.EqualTo(clientSession.UserId)); } [Test] public void Can_add_single_UserSession() { var cacheManager = GetCacheManager(redisCache); var clientSession = cacheManager.StoreClientSession( UserId, UserName, ShardId, session.IPAddress, UserClientKey, UserClientGlobalId1); var resolvedClientSession = cacheManager.GetUserClientSession( clientSession.UserId, clientSession.Id); AssertClientSessionsAreEqual(clientSession, resolvedClientSession); } [Test] public void Can_add_multiple_UserClientSessions() { var cacheManager = GetCacheManager(redisCache); var clientSession1 = cacheManager.StoreClientSession( UserId, UserName, ShardId, session.IPAddress, UserClientKey, UserClientGlobalId1); var clientSession2 = cacheManager.StoreClientSession( UserId, UserName, ShardId, session.IPAddress, UserClientKey, UserClientGlobalId2); var resolvedClientSession1 = cacheManager.GetUserClientSession( clientSession1.UserId, clientSession1.Id); var resolvedClientSession2 = cacheManager.GetUserClientSession( clientSession2.UserId, clientSession2.Id); AssertClientSessionsAreEqual(clientSession1, resolvedClientSession1); AssertClientSessionsAreEqual(clientSession2, resolvedClientSession2); } [Test] public void Does_remove_UserClientSession() { var cacheManager = GetCacheManager(redisCache); var clientSession1 = cacheManager.StoreClientSession( UserId, UserName, ShardId, session.IPAddress, UserClientKey, UserClientGlobalId1); var userSession = cacheManager.GetUserSession(UserId); var resolvedClientSession1 = userSession.GetClientSession(clientSession1.Id); AssertClientSessionsAreEqual(resolvedClientSession1, clientSession1); resolvedClientSession1.ExpiryDate = DateTime.UtcNow.AddSeconds(-1); cacheManager.UpdateUserSession(userSession); userSession = cacheManager.GetUserSession(UserId); Assert.That(userSession, Is.Null); } } public class CachedUserSessionManager { private static readonly ILog Log = LogManager.GetLogger(typeof(CachedUserSessionManager)); /// <summary> /// Google/Yahoo seems to make you to login every 2 weeks?? /// </summary> private readonly ICacheClient cacheClient; /// <summary> /// Big perf hit if we Log on every session change /// </summary> /// <param name="fmt">The FMT.</param> /// <param name="args">The args.</param> [Conditional("DEBUG")] protected void LogIfDebug(string fmt, params object[] args) { if (args.Length > 0) Log.DebugFormat(fmt, args); else Log.Debug(fmt); } public CachedUserSessionManager(ICacheClient cacheClient) { this.cacheClient = cacheClient; } /// <summary> /// Removes the client session. /// </summary> /// <param name="userId">The user global id.</param> /// <param name="clientSessionIds">The client session ids.</param> public void RemoveClientSession(Guid userId, ICollection<Guid> clientSessionIds) { var userSession = this.GetUserSession(userId); if (userSession == null) return; foreach (var clientSessionId in clientSessionIds) { userSession.RemoveClientSession(clientSessionId); } this.UpdateUserSession(userSession); } /// <summary> /// Adds a new client session. /// Should this be changed to GetOrCreateClientSession? /// </summary> /// <param name="userId">The user global id.</param> /// <param name="userName">Title of the user.</param> /// <param name="shardId"></param> /// <param name="ipAddress">The ip address.</param> /// <param name="base64ClientModulus">The base64 client modulus.</param> /// <param name="userClientGlobalId">The user client global id.</param> /// <returns></returns> public UserClientSession StoreClientSession(Guid userId, string userName, string shardId, string ipAddress, string base64ClientModulus, Guid userClientGlobalId) { var userSession = this.GetOrCreateSession(userId, userName, shardId); var existingClientSession = userSession.GetClientSessionWithClientId(userClientGlobalId); if (existingClientSession != null) { userSession.RemoveClientSession(existingClientSession.Id); } var newClientSession = userSession.CreateNewClientSession( ipAddress, base64ClientModulus, userClientGlobalId); this.UpdateUserSession(userSession); return newClientSession; } /// <summary> /// Updates the UserSession in the cache, or removes expired ones. /// </summary> /// <param name="userSession">The user session.</param> public void UpdateUserSession(UserSession userSession) { var hasSessionExpired = userSession.HasExpired(); if (hasSessionExpired) { LogIfDebug("Session has expired, removing: " + userSession.ToCacheKey()); this.cacheClient.Remove(userSession.ToCacheKey()); } else { LogIfDebug("Updating session: " + userSession.ToCacheKey()); this.cacheClient.Replace(userSession.ToCacheKey(), userSession, userSession.ExpiryDate.Value); } } /// <summary> /// Gets the user session if it exists or null. /// </summary> /// <param name="userId">The user global id.</param> /// <returns></returns> public UserSession GetUserSession(Guid userId) { var cacheKey = UserSession.ToCacheKey(userId); var bytes = this.cacheClient.Get<byte[]>(cacheKey); if (bytes != null) { var modelStr = Encoding.UTF8.GetString(bytes); LogIfDebug("UserSession => " + modelStr); } return this.cacheClient.Get<UserSession>(cacheKey); } /// <summary> /// Gets or create a user session if one doesn't exist. /// </summary> /// <param name="userId">The user global id.</param> /// <param name="userName">Title of the user.</param> /// <param name="shardId"></param> /// <returns></returns> public UserSession GetOrCreateSession(Guid userId, string userName, string shardId) { var userSession = this.GetUserSession(userId); if (userSession == null) { userSession = new UserSession(userId, userName, shardId); this.cacheClient.Add(userSession.ToCacheKey(), userSession, userSession.ExpiryDate.GetValueOrDefault(DateTime.UtcNow) + TimeSpan.FromHours(1)); } return userSession; } /// <summary> /// Gets the user client session identified by the id if exists otherwise null. /// </summary> /// <param name="userId">The user global id.</param> /// <param name="clientSessionId">The client session id.</param> /// <returns></returns> public UserClientSession GetUserClientSession(Guid userId, Guid clientSessionId) { var userSession = this.GetUserSession(userId); return userSession != null ? userSession.GetClientSession(clientSessionId) : null; } } [Serializable /* was required when storing in memcached, not required in Redis */] public class UserSession { //Empty constructor required for TypeSerializer public UserSession() { this.PublicClientSessions = new Dictionary<Guid, UserClientSession>(); } public Guid UserId { get; private set; } public string UserName { get; private set; } public string ShardId { get; private set; } public Dictionary<Guid, UserClientSession> PublicClientSessions { get; private set; } public UserSession(Guid userId, string userName, string shardId) : this() { this.UserId = userId; this.UserName = userName; this.ShardId = shardId; } /// <summary> /// Gets the max expiry date of all the users client sessions. /// If the user has no more active client sessions we can remove them from the cache. /// </summary> /// <value>The expiry date.</value> public DateTime? ExpiryDate { get { DateTime? maxExpiryDate = null; foreach (var session in this.PublicClientSessions.Values) { if (maxExpiryDate == null || session.ExpiryDate > maxExpiryDate) { maxExpiryDate = session.ExpiryDate; } } return maxExpiryDate; } } /// <summary> /// Creates a new client session for the user. /// </summary> /// <param name="ipAddress">The ip address.</param> /// <param name="base64ClientModulus">The base64 client modulus.</param> /// <param name="userClientGlobalId">The user client global id.</param> /// <returns></returns> public UserClientSession CreateNewClientSession(string ipAddress, string base64ClientModulus, Guid userClientGlobalId) { return this.CreateClientSession(Guid.NewGuid(), ipAddress, base64ClientModulus, userClientGlobalId); } public UserClientSession CreateClientSession(Guid sessionId, string ipAddress, string base64ClientModulus, Guid userClientGlobalId) { var clientSession = new UserClientSession( sessionId, this.UserId, ipAddress, base64ClientModulus, userClientGlobalId); this.PublicClientSessions[clientSession.Id] = clientSession; return clientSession; } /// <summary> /// Removes the client session. /// </summary> /// <param name="clientSessionId">The client session id.</param> public void RemoveClientSession(Guid clientSessionId) { if (this.PublicClientSessions.ContainsKey(clientSessionId)) { this.PublicClientSessions.Remove(clientSessionId); } } public UserClientSession GetClientSessionWithClientId(Guid userClientId) { foreach (var entry in this.PublicClientSessions) { if (entry.Value.UserClientGlobalId == userClientId) { return entry.Value; } } return null; } /// <summary> /// Verifies this UserSession, removing any expired sessions. /// Returns true to keep the UserSession in the cache. /// </summary> /// <returns> /// <c>true</c> if this session has any active client sessions; otherwise, <c>false</c>. /// </returns> public bool HasExpired() { RemoveExpiredSessions(this.PublicClientSessions); //If there are no more active client sessions we can remove the entire UserSessions var sessionHasExpired = this.ExpiryDate == null //There are no UserClientSessions || this.ExpiryDate.Value <= DateTime.UtcNow; //The max UserClientSession ExpiryDate has expired return sessionHasExpired; } private static void RemoveExpiredSessions(IDictionary<Guid, UserClientSession> clientSessions) { var expiredSessionKeys = new List<Guid>(); foreach (var clientSession in clientSessions) { if (clientSession.Value.ExpiryDate < DateTime.UtcNow) { expiredSessionKeys.Add(clientSession.Key); } } foreach (var sessionKey in expiredSessionKeys) { clientSessions.Remove(sessionKey); } } public void RemoveAllSessions() { this.PublicClientSessions.Clear(); } public UserClientSession GetClientSession(Guid clientSessionId) { UserClientSession session; if (this.PublicClientSessions.TryGetValue(clientSessionId, out session)) { return session; } return null; } public string ToCacheKey() { return ToCacheKey(this.UserId); } public static string ToCacheKey(Guid userId) { return UrnId.Create<UserSession>(userId.ToString()); } } [Serializable] public class UserClientSession : IHasGuidId { private const int ValidForTwoWeeks = 14; public string IPAddress { get; private set; } public DateTime ExpiryDate { get; set; } //Empty constructor required for TypeSerializer public UserClientSession() { } public UserClientSession(Guid sessionId, Guid userId, string ipAddress, string base64ClientModulus, Guid userClientGlobalId) { this.Id = sessionId; this.UserId = userId; this.IPAddress = ipAddress; this.Base64ClientModulus = base64ClientModulus; this.UserClientGlobalId = userClientGlobalId; this.ExpiryDate = DateTime.UtcNow.AddDays(ValidForTwoWeeks); } public Guid Id { get; set; } public Guid UserId { get; set; } public string Base64ClientModulus { get; set; } public Guid UserClientGlobalId { get; set; } } }
// // Util.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin 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 Xwt.Drawing; using Xwt.Backends; using System.Collections.Generic; using System.Linq; namespace Xwt.GtkBackend { public static class Util { static uint targetIdCounter = 0; static Dictionary<TransferDataType, Gtk.TargetEntry[]> dragTargets = new Dictionary<TransferDataType, Gtk.TargetEntry[]> (); static Dictionary<string, TransferDataType> atomToType = new Dictionary<string, TransferDataType> (); static Size[] iconSizes = new Size[7]; static Util () { for (int i = 0; i < iconSizes.Length; i++) { int w, h; if (!Gtk.Icon.SizeLookup ((Gtk.IconSize)i, out w, out h)) w = h = -1; iconSizes[i].Width = w; iconSizes[i].Height = h; } if (Platform.IsWindows) { // Workaround for an issue in GTK for Windows. In windows Menu-sized icons are not 16x16, but 14x14 iconSizes[(int)Gtk.IconSize.Menu].Width = 16; iconSizes[(int)Gtk.IconSize.Menu].Height = 16; } } public static void SetDragData (TransferDataSource data, Gtk.DragDataGetArgs args) { foreach (var t in data.DataTypes) { object val = data.GetValue (t); SetSelectionData (args.SelectionData, t.Id, val); } } public static void SetSelectionData (Gtk.SelectionData data, string atomType, object val) { if (val == null) return; if (val is string) data.Text = (string)val; else if (val is Xwt.Drawing.Image) { var bmp = ((Image)val).ToBitmap (); data.SetPixbuf (((GtkImage)Toolkit.GetBackend (bmp)).Frames[0].Pixbuf); } else if (val is Uri) data.SetUris(new string[] { ((Uri)val).AbsolutePath }); else { var at = Gdk.Atom.Intern (atomType, false); data.Set (at, 0, TransferDataSource.SerializeValue (val)); } } public static bool GetSelectionData (ApplicationContext context, Gtk.SelectionData data, TransferDataStore target) { TransferDataType type = Util.AtomToType (data.Target.Name); if (type == null || data.Length <= 0) return false; if (type == TransferDataType.Text) target.AddText (data.Text); else if (data.TargetsIncludeImage (false)) target.AddImage (context.Toolkit.WrapImage (data.Pixbuf)); else if (type == TransferDataType.Uri) target.AddUris (data.GetUris().Where(u => !string.IsNullOrEmpty(u)).Select(u => new Uri(u)).ToArray()); else target.AddValue (type, data.Data); return true; } internal static TransferDataType AtomToType (string targetName) { TransferDataType type; atomToType.TryGetValue (targetName, out type); return type; } internal static TransferDataType[] GetDragTypes (Gdk.Atom[] dropTypes) { List<TransferDataType> types = new List<TransferDataType> (); foreach (var dt in dropTypes) { TransferDataType type; if (atomToType.TryGetValue (dt.Name, out type)) types.Add (type); } return types.ToArray (); } public static Gtk.TargetList BuildTargetTable (TransferDataType[] types) { var tl = new Gtk.TargetList (); foreach (var tt in types) tl.AddTable (CreateTargetEntries (tt)); return tl; } static Gtk.TargetEntry[] CreateTargetEntries (TransferDataType type) { lock (dragTargets) { Gtk.TargetEntry[] entries; if (dragTargets.TryGetValue (type, out entries)) return entries; uint id = targetIdCounter++; if (type == TransferDataType.Uri) { Gtk.TargetList list = new Gtk.TargetList (); list.AddUriTargets (id); entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Text) { Gtk.TargetList list = new Gtk.TargetList (); list.AddTextTargets (id); //HACK: work around gtk_selection_data_set_text causing crashes on Mac w/ QuickSilver, Clipbard History etc. if (Platform.IsMac) { list.Remove ("COMPOUND_TEXT"); list.Remove ("TEXT"); list.Remove ("STRING"); } entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Rtf) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("NSRTFPboardType", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("Rich Text Format", false); } else { atom = Gdk.Atom.Intern ("text/rtf", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else if (type == TransferDataType.Html) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("Apple HTML pasteboard type", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("HTML Format", false); } else { atom = Gdk.Atom.Intern ("text/html", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else if (type == TransferDataType.Image) { Gtk.TargetList list = new Gtk.TargetList (); list.AddImageTargets (id, true); entries = (Gtk.TargetEntry[])list; } else { entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (Gdk.Atom.Intern ("application/" + type.Id, false), 0, id) }; } foreach (var a in entries.Select (e => e.Target)) atomToType [a] = type; return dragTargets [type] = entries; } } static Dictionary<string,string> icons; public static GtkImage ToGtkStock (string id) { if (icons == null) { icons = new Dictionary<string, string> (); icons [StockIconId.ZoomIn] = Gtk.Stock.ZoomIn; icons [StockIconId.ZoomOut] = Gtk.Stock.ZoomOut; icons [StockIconId.Zoom100] = Gtk.Stock.Zoom100; icons [StockIconId.ZoomFit] = Gtk.Stock.ZoomFit; icons [StockIconId.OrientationPortrait] = Gtk.Stock.OrientationPortrait; icons [StockIconId.OrientationLandscape] = Gtk.Stock.OrientationLandscape; icons [StockIconId.Add] = Gtk.Stock.Add; icons [StockIconId.Remove] = Gtk.Stock.Remove; icons [StockIconId.Warning] = Gtk.Stock.DialogWarning; icons [StockIconId.Error] = Gtk.Stock.DialogError; icons [StockIconId.Information] = Gtk.Stock.DialogInfo; icons [StockIconId.Question] = Gtk.Stock.DialogQuestion; icons [StockIconId.Calendar] = Gtk.Stock.GotoBottom; } string res; if (!icons.TryGetValue (id, out res)) throw new NotSupportedException ("Unknown image: " + id); return new GtkImage (res); } public static Gtk.IconSize GetBestSizeFit (double size, Gtk.IconSize[] availablesizes = null) { // Find the size that better fits the requested size for (int n=0; n<iconSizes.Length; n++) { if (availablesizes != null && !availablesizes.Contains ((Gtk.IconSize)n)) continue; if (size <= iconSizes [n].Width) return (Gtk.IconSize)n; } if (availablesizes == null || availablesizes.Contains (Gtk.IconSize.Dialog)) return Gtk.IconSize.Dialog; else return Gtk.IconSize.Invalid; } public static double GetBestSizeFitSize (double size) { var s = GetBestSizeFit (size); return iconSizes [(int)s].Width; } public static ImageDescription WithDefaultSize (this ImageDescription image, Gtk.IconSize defaultIconSize) { if (image.Size.IsZero) { var s = iconSizes [(int)defaultIconSize]; image.Size = s; } return image; } public static double GetScaleFactor (Gtk.Widget w) { return GtkWorkarounds.GetScaleFactor (w); } public static double GetDefaultScaleFactor () { return 1; } internal static void SetSourceColor (this Cairo.Context cr, Cairo.Color color) { cr.SetSourceRGBA (color.R, color.G, color.B, color.A); } //this is needed for building against old Mono.Cairo versions [Obsolete] internal static void SetSource (this Cairo.Context cr, Cairo.Pattern pattern) { cr.Pattern = pattern; } [Obsolete] internal static Cairo.Surface GetTarget (this Cairo.Context cr) { return cr.Target; } [Obsolete] internal static void Dispose (this Cairo.Context cr) { ((IDisposable)cr).Dispose (); } } }
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using Microsoft.WindowsAPICodePack.Shell.PropertySystem; using Microsoft.WindowsAPICodePack.Taskbar; using MS.WindowsAPICodePack.Internal; using Microsoft.WindowsAPICodePack.Shell; namespace wallpaper_receiver { /// <summary> /// A property store /// </summary> [ComImport] [Guid(ShellIIDGuid.IPropertyStore)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IPropertyStore { /// <summary> /// Gets the number of properties contained in the property store. /// </summary> /// <param name="propertyCount"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetCount([Out] out uint propertyCount); /// <summary> /// Get a property key located at a specific index. /// </summary> /// <param name="propertyIndex"></param> /// <param name="key"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetAt([In] uint propertyIndex, out PropertyKey key); /// <summary> /// Gets the value of a property from the store /// </summary> /// <param name="key"></param> /// <param name="pv"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetValue([In] ref PropertyKey key, [Out] PropVariant pv); /// <summary> /// Sets the value of a property in the store /// </summary> /// <param name="key"></param> /// <param name="pv"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] HResult SetValue([In] ref PropertyKey key, [In] PropVariant pv); /// <summary> /// Commits the changes. /// </summary> /// <returns></returns> [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Commit(); } internal enum SICHINTF { SICHINT_DISPLAY = 0x00000000, SICHINT_CANONICAL = 0x10000000, SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000, SICHINT_ALLFIELDS = unchecked((int)0x80000000) } // Disable warning if a method declaration hides another inherited from a parent COM interface // To successfully import a COM interface, all inherited methods need to be declared again with // the exception of those already declared in "IUnknown" #pragma warning disable 108 #region COM Interfaces [ComImport(), Guid(ShellIIDGuid.IModalWindow), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IModalWindow { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] int Show([In] IntPtr parent); } [ComImport, Guid(ShellIIDGuid.IShellItem), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItem { // Not supported: IBindCtx. [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult BindToHandler( [In] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetDisplayName( [In] ShellNativeMethods.ShellItemDesignNameOptions sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributes([In] ShellNativeMethods.ShellFileGetAttributesOptions sfgaoMask, out ShellNativeMethods.ShellFileGetAttributesOptions psfgaoAttribs); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Compare( [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] SICHINTF hint, out int piOrder); } [ComImport, Guid(ShellIIDGuid.IShellItem2), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItem2 : IShellItem { // Not supported: IBindCtx. [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult BindToHandler( [In] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetDisplayName( [In] ShellNativeMethods.ShellItemDesignNameOptions sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributes([In] ShellNativeMethods.ShellFileGetAttributesOptions sfgaoMask, out ShellNativeMethods.ShellFileGetAttributesOptions psfgaoAttribs); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Compare( [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] int GetPropertyStore( [In] ShellNativeMethods.GetPropertyStoreOptions Flags, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IPropertyStore ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyStoreWithCreateObject([In] ShellNativeMethods.GetPropertyStoreOptions Flags, [In, MarshalAs(UnmanagedType.IUnknown)] object punkCreateObject, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyStoreForKeys([In] ref PropertyKey rgKeys, [In] uint cKeys, [In] ShellNativeMethods.GetPropertyStoreOptions Flags, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.IUnknown)] out IPropertyStore ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyDescriptionList([In] ref PropertyKey keyType, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Update([In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetProperty([In] ref PropertyKey key, [Out] PropVariant ppropvar); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCLSID([In] ref PropertyKey key, out Guid pclsid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetFileTime([In] ref PropertyKey key, out System.Runtime.InteropServices.ComTypes.FILETIME pft); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetInt32([In] ref PropertyKey key, out int pi); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetString([In] ref PropertyKey key, [MarshalAs(UnmanagedType.LPWStr)] out string ppsz); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUInt32([In] ref PropertyKey key, out uint pui); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUInt64([In] ref PropertyKey key, out ulong pull); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetBool([In] ref PropertyKey key, out int pf); } [ComImport, Guid(ShellIIDGuid.IShellItemArray), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItemArray { // Not supported: IBindCtx. [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult BindToHandler( [In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, out IntPtr ppvOut); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetPropertyStore( [In] int Flags, [In] ref Guid riid, out IntPtr ppv); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetPropertyDescriptionList( [In] ref PropertyKey keyType, [In] ref Guid riid, out IntPtr ppv); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetAttributes( [In] ShellNativeMethods.ShellItemAttributeOptions dwAttribFlags, [In] ShellNativeMethods.ShellFileGetAttributesOptions sfgaoMask, out ShellNativeMethods.ShellFileGetAttributesOptions psfgaoAttribs); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetCount(out uint pdwNumItems); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetItemAt( [In] uint dwIndex, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); // Not supported: IEnumShellItems (will use GetCount and GetItemAt instead). [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult EnumItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenumShellItems); } [ComImport, Guid(ShellIIDGuid.IShellLibrary), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellLibrary { [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult LoadLibraryFromItem( [In, MarshalAs(UnmanagedType.Interface)] IShellItem library, [In] AccessModes grfMode); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void LoadLibraryFromKnownFolder( [In] ref Guid knownfidLibrary, [In] AccessModes grfMode); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void AddFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem location); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RemoveFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem location); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetFolders( [In] ShellNativeMethods.LibraryFolderFilter lff, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ResolveFolder( [In, MarshalAs(UnmanagedType.Interface)] IShellItem folderToResolve, [In] uint timeout, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDefaultSaveFolder( [In] ShellNativeMethods.DefaultSaveFolderType dsft, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetDefaultSaveFolder( [In] ShellNativeMethods.DefaultSaveFolderType dsft, [In, MarshalAs(UnmanagedType.Interface)] IShellItem si); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetOptions( out ShellNativeMethods.LibraryOptions lofOptions); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetOptions( [In] ShellNativeMethods.LibraryOptions lofMask, [In] ShellNativeMethods.LibraryOptions lofOptions); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetFolderType(out Guid ftid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetFolderType([In] ref Guid ftid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetIcon([MarshalAs(UnmanagedType.LPWStr)] out string icon); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetIcon([In, MarshalAs(UnmanagedType.LPWStr)] string icon); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Commit(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Save( [In, MarshalAs(UnmanagedType.Interface)] IShellItem folderToSaveIn, [In, MarshalAs(UnmanagedType.LPWStr)] string libraryName, [In] ShellNativeMethods.LibrarySaveOptions lsf, [MarshalAs(UnmanagedType.Interface)] out IShellItem2 savedTo); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SaveInKnownFolder( [In] ref Guid kfidToSaveIn, [In, MarshalAs(UnmanagedType.LPWStr)] string libraryName, [In] ShellNativeMethods.LibrarySaveOptions lsf, [MarshalAs(UnmanagedType.Interface)] out IShellItem2 savedTo); }; [ComImport, Guid(ShellIIDGuid.IShellFolder), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComConversionLoss] internal interface IShellFolder { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ParseDisplayName(IntPtr hwnd, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In, MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, [In, Out] ref uint pchEaten, [Out] IntPtr ppidl, [In, Out] ref uint pdwAttributes); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult EnumObjects([In] IntPtr hwnd, [In] ShellNativeMethods.ShellFolderEnumerationOptions grfFlags, [MarshalAs(UnmanagedType.Interface)] out IEnumIDList ppenumIDList); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult BindToObject([In] IntPtr pidl, /*[In, MarshalAs(UnmanagedType.Interface)] IBindCtx*/ IntPtr pbc, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToStorage([In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CompareIDs([In] IntPtr lParam, [In] ref IntPtr pidl1, [In] ref IntPtr pidl2); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CreateViewObject([In] IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributesOf([In] uint cidl, [In] IntPtr apidl, [In, Out] ref uint rgfInOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUIObjectOf([In] IntPtr hwndOwner, [In] uint cidl, [In] IntPtr apidl, [In] ref Guid riid, [In, Out] ref uint rgfReserved, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDisplayNameOf([In] ref IntPtr pidl, [In] uint uFlags, out IntPtr pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetNameOf([In] IntPtr hwnd, [In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, [In] uint uFlags, [Out] IntPtr ppidlOut); } [ComImport, Guid(ShellIIDGuid.IShellFolder2), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComConversionLoss] internal interface IShellFolder2 : IShellFolder { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ParseDisplayName([In] IntPtr hwnd, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In, MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, [In, Out] ref uint pchEaten, [Out] IntPtr ppidl, [In, Out] ref uint pdwAttributes); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void EnumObjects([In] IntPtr hwnd, [In] ShellNativeMethods.ShellFolderEnumerationOptions grfFlags, [MarshalAs(UnmanagedType.Interface)] out IEnumIDList ppenumIDList); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToObject([In] IntPtr pidl, /*[In, MarshalAs(UnmanagedType.Interface)] IBindCtx*/ IntPtr pbc, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToStorage([In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CompareIDs([In] IntPtr lParam, [In] ref IntPtr pidl1, [In] ref IntPtr pidl2); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CreateViewObject([In] IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributesOf([In] uint cidl, [In] IntPtr apidl, [In, Out] ref uint rgfInOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUIObjectOf([In] IntPtr hwndOwner, [In] uint cidl, [In] IntPtr apidl, [In] ref Guid riid, [In, Out] ref uint rgfReserved, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDisplayNameOf([In] ref IntPtr pidl, [In] uint uFlags, out IntPtr pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetNameOf([In] IntPtr hwnd, [In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, [In] uint uFlags, [Out] IntPtr ppidlOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDefaultSearchGUID(out Guid pguid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void EnumSearches([Out] out IntPtr ppenum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDefaultColumn([In] uint dwRes, out uint pSort, out uint pDisplay); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDefaultColumnState([In] uint iColumn, out uint pcsFlags); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDetailsEx([In] ref IntPtr pidl, [In] ref PropertyKey pscid, [MarshalAs(UnmanagedType.Struct)] out object pv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDetailsOf([In] ref IntPtr pidl, [In] uint iColumn, out IntPtr psd); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void MapColumnToSCID([In] uint iColumn, out PropertyKey pscid); } [ComImport, Guid(ShellIIDGuid.IEnumIDList), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IEnumIDList { [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Next(uint celt, out IntPtr rgelt, out uint pceltFetched); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Skip([In] uint celt); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Reset(); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult Clone([MarshalAs(UnmanagedType.Interface)] out IEnumIDList ppenum); } [ComImport, Guid(ShellIIDGuid.IShellLinkW), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellLinkW { void GetPath( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, //ref _WIN32_FIND_DATAW pfd, IntPtr pfd, uint fFlags); void GetIDList(out IntPtr ppidl); void SetIDList(IntPtr pidl); void GetDescription( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxName); void SetDescription( [MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetWorkingDirectory( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath ); void SetWorkingDirectory( [MarshalAs(UnmanagedType.LPWStr)] string pszDir); void GetArguments( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); void SetArguments( [MarshalAs(UnmanagedType.LPWStr)] string pszArgs); void GetHotKey(out short wHotKey); void SetHotKey(short wHotKey); void GetShowCmd(out uint iShowCmd); void SetShowCmd(uint iShowCmd); void GetIconLocation( [Out(), MarshalAs(UnmanagedType.LPWStr)] out StringBuilder pszIconPath, int cchIconPath, out int iIcon); void SetIconLocation( [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); void SetRelativePath( [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved); void Resolve(IntPtr hwnd, uint fFlags); void SetPath( [MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport, Guid(ShellIIDGuid.CShellLink), ClassInterface(ClassInterfaceType.None)] internal class CShellLink { } // Summary: // Provides the managed definition of the IPersistStream interface, with functionality // from IPersist. [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("00000109-0000-0000-C000-000000000046")] internal interface IPersistStream { // Summary: // Retrieves the class identifier (CLSID) of an object. // // Parameters: // pClassID: // When this method returns, contains a reference to the CLSID. This parameter // is passed uninitialized. [PreserveSig] void GetClassID(out Guid pClassID); // // Summary: // Checks an object for changes since it was last saved to its current file. // // Returns: // S_OK if the file has changed since it was last saved; S_FALSE if the file // has not changed since it was last saved. [PreserveSig] HResult IsDirty(); [PreserveSig] HResult Load([In, MarshalAs(UnmanagedType.Interface)] IStream stm); [PreserveSig] HResult Save([In, MarshalAs(UnmanagedType.Interface)] IStream stm, bool fRemember); [PreserveSig] HResult GetSizeMax(out ulong cbSize); } [ComImport(), Guid(ShellIIDGuid.ICondition), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ICondition : IPersistStream { // Summary: // Retrieves the class identifier (CLSID) of an object. // // Parameters: // pClassID: // When this method returns, contains a reference to the CLSID. This parameter // is passed uninitialized. [PreserveSig] void GetClassID(out Guid pClassID); // // Summary: // Checks an object for changes since it was last saved to its current file. // // Returns: // S_OK if the file has changed since it was last saved; S_FALSE if the file // has not changed since it was last saved. [PreserveSig] HResult IsDirty(); [PreserveSig] HResult Load([In, MarshalAs(UnmanagedType.Interface)] IStream stm); [PreserveSig] HResult Save([In, MarshalAs(UnmanagedType.Interface)] IStream stm, bool fRemember); [PreserveSig] HResult GetSizeMax(out ulong cbSize); // For any node, return what kind of node it is. [PreserveSig] HResult GetConditionType([Out()] out SearchConditionType pNodeType); // riid must be IID_IEnumUnknown, IID_IEnumVARIANT or IID_IObjectArray, or in the case of a negation node IID_ICondition. // If this is a leaf node, E_FAIL will be returned. // If this is a negation node, then if riid is IID_ICondition, *ppv will be set to a single ICondition, otherwise an enumeration of one. // If this is a conjunction or a disjunction, *ppv will be set to an enumeration of the subconditions. [PreserveSig] HResult GetSubConditions([In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppv); // If this is not a leaf node, E_FAIL will be returned. // Retrieve the property name, operation and value from the leaf node. // Any one of ppszPropertyName, pcop and ppropvar may be NULL. [PreserveSig] HResult GetComparisonInfo( [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszPropertyName, [Out] out SearchConditionOperation pcop, [Out] PropVariant ppropvar); // If this is not a leaf node, E_FAIL will be returned. // *ppszValueTypeName will be set to the semantic type of the value, or to NULL if this is not meaningful. [PreserveSig] HResult GetValueType([Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszValueTypeName); // If this is not a leaf node, E_FAIL will be returned. // If the value of the leaf node is VT_EMPTY, *ppszNormalization will be set to an empty string. // If the value is a string (VT_LPWSTR, VT_BSTR or VT_LPSTR), then *ppszNormalization will be set to a // character-normalized form of the value. // Otherwise, *ppszNormalization will be set to some (character-normalized) string representation of the value. [PreserveSig] HResult GetValueNormalization([Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszNormalization); // Return information about what parts of the input produced the property, the operation and the value. // Any one of ppPropertyTerm, ppOperationTerm and ppValueTerm may be NULL. // For a leaf node returned by the parser, the position information of each IRichChunk identifies the tokens that // contributed the property/operation/value, the string value is the corresponding part of the input string, and // the PROPVARIANT is VT_EMPTY. [PreserveSig] HResult GetInputTerms([Out] out IRichChunk ppPropertyTerm, [Out] out IRichChunk ppOperationTerm, [Out] out IRichChunk ppValueTerm); // Make a deep copy of this ICondition. [PreserveSig] HResult Clone([Out()] out ICondition ppc); }; [ComImport, Guid(ShellIIDGuid.IRichChunk), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IRichChunk { // The position *pFirstPos is zero-based. // Any one of pFirstPos, pLength, ppsz and pValue may be NULL. [PreserveSig] HResult GetData(/*[out, annotation("__out_opt")] ULONG* pFirstPos, [out, annotation("__out_opt")] ULONG* pLength, [out, annotation("__deref_opt_out_opt")] LPWSTR* ppsz, [out, annotation("__out_opt")] PROPVARIANT* pValue*/); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid(ShellIIDGuid.IEnumUnknown)] internal interface IEnumUnknown { [PreserveSig] HResult Next(UInt32 requestedNumber, ref IntPtr buffer, ref UInt32 fetchedNumber); [PreserveSig] HResult Skip(UInt32 number); [PreserveSig] HResult Reset(); [PreserveSig] HResult Clone(out IEnumUnknown result); } [ComImport, Guid(ShellIIDGuid.IConditionFactory), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IConditionFactory { [PreserveSig] HResult MakeNot([In] ICondition pcSub, [In] bool fSimplify, [Out] out ICondition ppcResult); [PreserveSig] HResult MakeAndOr([In] SearchConditionType ct, [In] IEnumUnknown peuSubs, [In] bool fSimplify, [Out] out ICondition ppcResult); [PreserveSig] HResult MakeLeaf( [In, MarshalAs(UnmanagedType.LPWStr)] string pszPropertyName, [In] SearchConditionOperation cop, [In, MarshalAs(UnmanagedType.LPWStr)] string pszValueType, [In] PropVariant ppropvar, IRichChunk richChunk1, IRichChunk richChunk2, IRichChunk richChunk3, [In] bool fExpand, [Out] out ICondition ppcResult); [PreserveSig] HResult Resolve(/*[In] ICondition pc, [In] STRUCTURED_QUERY_RESOLVE_OPTION sqro, [In] ref SYSTEMTIME pstReferenceTime, [Out] out ICondition ppcResolved*/); }; [ComImport, Guid(ShellIIDGuid.IConditionFactory), CoClass(typeof(ConditionFactoryCoClass))] internal interface INativeConditionFactory : IConditionFactory { } [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid(ShellCLSIDGuid.ConditionFactory)] internal class ConditionFactoryCoClass { } [ComImport, Guid(ShellIIDGuid.ISearchFolderItemFactory), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISearchFolderItemFactory { [PreserveSig] HResult SetDisplayName([In, MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName); [PreserveSig] HResult SetFolderTypeID([In] Guid ftid); [PreserveSig] HResult SetFolderLogicalViewMode([In] FolderLogicalViewMode flvm); [PreserveSig] HResult SetIconSize([In] int iIconSize); [PreserveSig] HResult SetVisibleColumns([In] uint cVisibleColumns, [In, MarshalAs(UnmanagedType.LPArray)] PropertyKey[] rgKey); [PreserveSig] HResult SetSortColumns([In] uint cSortColumns, [In, MarshalAs(UnmanagedType.LPArray)] SortColumn[] rgSortColumns); [PreserveSig] HResult SetGroupColumn([In] ref PropertyKey keyGroup); [PreserveSig] HResult SetStacks([In] uint cStackKeys, [In, MarshalAs(UnmanagedType.LPArray)] PropertyKey[] rgStackKeys); [PreserveSig] HResult SetScope([In, MarshalAs(UnmanagedType.Interface)] IShellItemArray ppv); [PreserveSig] HResult SetCondition([In] ICondition pCondition); [PreserveSig] int GetShellItem(ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellItem ppv); [PreserveSig] HResult GetIDList([Out] IntPtr ppidl); }; [ComImport, Guid(ShellIIDGuid.ISearchFolderItemFactory), CoClass(typeof(SearchFolderItemFactoryCoClass))] internal interface INativeSearchFolderItemFactory : ISearchFolderItemFactory { } [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid(ShellCLSIDGuid.SearchFolderItemFactory)] internal class SearchFolderItemFactoryCoClass { } [ComImport, Guid(ShellIIDGuid.IQuerySolution), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IQuerySolution : IConditionFactory { [PreserveSig] HResult MakeNot([In] ICondition pcSub, [In] bool fSimplify, [Out] out ICondition ppcResult); [PreserveSig] HResult MakeAndOr([In] SearchConditionType ct, [In] IEnumUnknown peuSubs, [In] bool fSimplify, [Out] out ICondition ppcResult); [PreserveSig] HResult MakeLeaf( [In, MarshalAs(UnmanagedType.LPWStr)] string pszPropertyName, [In] SearchConditionOperation cop, [In, MarshalAs(UnmanagedType.LPWStr)] string pszValueType, [In] PropVariant ppropvar, IRichChunk richChunk1, IRichChunk richChunk2, IRichChunk richChunk3, [In] bool fExpand, [Out] out ICondition ppcResult); [PreserveSig] HResult Resolve(/*[In] ICondition pc, [In] int sqro, [In] ref SYSTEMTIME pstReferenceTime, [Out] out ICondition ppcResolved*/); // Retrieve the condition tree and the "main type" of the solution. // ppQueryNode and ppMainType may be NULL. [PreserveSig] HResult GetQuery([Out, MarshalAs(UnmanagedType.Interface)] out ICondition ppQueryNode, [Out, MarshalAs(UnmanagedType.Interface)] out IEntity ppMainType); // Identify parts of the input string not accounted for. // Each parse error is represented by an IRichChunk where the position information // reflect token counts, the string is NULL and the value is a VT_I4 // where lVal is from the ParseErrorType enumeration. The valid // values for riid are IID_IEnumUnknown and IID_IEnumVARIANT. [PreserveSig] HResult GetErrors([In] ref Guid riid, [Out] out /* void** */ IntPtr ppParseErrors); // Report the query string, how it was tokenized and what LCID and word breaker were used (for recognizing keywords). // ppszInputString, ppTokens, pLocale and ppWordBreaker may be NULL. [PreserveSig] HResult GetLexicalData([MarshalAs(UnmanagedType.LPWStr)] out string ppszInputString, [Out] /* ITokenCollection** */ out IntPtr ppTokens, [Out] out uint plcid, [Out] /* IUnknown** */ out IntPtr ppWordBreaker); } [ComImport, Guid(ShellIIDGuid.IQueryParser), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IQueryParser { // Parse parses an input string, producing a query solution. // pCustomProperties should be an enumeration of IRichChunk objects, one for each custom property // the application has recognized. pCustomProperties may be NULL, equivalent to an empty enumeration. // For each IRichChunk, the position information identifies the character span of the custom property, // the string value should be the name of an actual property, and the PROPVARIANT is completely ignored. [PreserveSig] HResult Parse([In, MarshalAs(UnmanagedType.LPWStr)] string pszInputString, [In] IEnumUnknown pCustomProperties, [Out] out IQuerySolution ppSolution); // Set a single option. See STRUCTURED_QUERY_SINGLE_OPTION above. [PreserveSig] HResult SetOption([In] StructuredQuerySingleOption option, [In] PropVariant pOptionValue); [PreserveSig] HResult GetOption([In] StructuredQuerySingleOption option, [Out] PropVariant pOptionValue); // Set a multi option. See STRUCTURED_QUERY_MULTIOPTION above. [PreserveSig] HResult SetMultiOption([In] StructuredQueryMultipleOption option, [In, MarshalAs(UnmanagedType.LPWStr)] string pszOptionKey, [In] PropVariant pOptionValue); // Get a schema provider for browsing the currently loaded schema. [PreserveSig] HResult GetSchemaProvider([Out] out /*ISchemaProvider*/ IntPtr ppSchemaProvider); // Restate a condition as a query string according to the currently selected syntax. // The parameter fUseEnglish is reserved for future use; must be FALSE. [PreserveSig] HResult RestateToString([In] ICondition pCondition, [In] bool fUseEnglish, [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszQueryString); // Parse a condition for a given property. It can be anything that would go after 'PROPERTY:' in an AQS expession. [PreserveSig] HResult ParsePropertyValue([In, MarshalAs(UnmanagedType.LPWStr)] string pszPropertyName, [In, MarshalAs(UnmanagedType.LPWStr)] string pszInputString, [Out] out IQuerySolution ppSolution); // Restate a condition for a given property. If the condition contains a leaf with any other property name, or no property name at all, // E_INVALIDARG will be returned. [PreserveSig] HResult RestatePropertyValueToString([In] ICondition pCondition, [In] bool fUseEnglish, [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszPropertyName, [Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszQueryString); } [ComImport, Guid(ShellIIDGuid.IQueryParserManager), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IQueryParserManager { // Create a query parser loaded with the schema for a certain catalog localize to a certain language, and initialized with // standard defaults. One valid value for riid is IID_IQueryParser. [PreserveSig] HResult CreateLoadedParser([In, MarshalAs(UnmanagedType.LPWStr)] string pszCatalog, [In] ushort langidForKeywords, [In] ref Guid riid, [Out] out IQueryParser ppQueryParser); // In addition to setting AQS/NQS and automatic wildcard for the given query parser, this sets up standard named entity handlers and // sets the keyboard locale as locale for word breaking. [PreserveSig] HResult InitializeOptions([In] bool fUnderstandNQS, [In] bool fAutoWildCard, [In] IQueryParser pQueryParser); // Change one of the settings for the query parser manager, such as the name of the schema binary, or the location of the localized and unlocalized // schema binaries. By default, the settings point to the schema binaries used by Windows Shell. [PreserveSig] HResult SetOption([In] QueryParserManagerOption option, [In] PropVariant pOptionValue); }; [ComImport, Guid(ShellIIDGuid.IQueryParserManager), CoClass(typeof(QueryParserManagerCoClass))] internal interface INativeQueryParserManager : IQueryParserManager { } [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid(ShellCLSIDGuid.QueryParserManager)] internal class QueryParserManagerCoClass { } [ComImport, Guid("24264891-E80B-4fd3-B7CE-4FF2FAE8931F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IEntity { // TODO } #endregion #pragma warning restore 108 }
// Type.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Collections; using System.ComponentModel; using System.Reflection; using System.Runtime.CompilerServices; namespace System { /// <summary> /// The Type data type which is mapped to the Function type in Javascript. /// </summary> [IgnoreNamespace] [Imported(ObeysTypeSystem = true)] [ScriptName("Function")] public sealed class Type { #region .Net reflection public Type BaseType { [InlineCode("{$System.Script}.getBaseType({this})")] get { return null; } } public string FullName { [InlineCode("{$System.Script}.getTypeFullName({this})")] get { return null; } } public string Name { [InlineCode("{$System.Script}.getTypeName({this})")] get { return null; } } [InlineCode("{$System.Script}.getType({typeName})")] public static Type GetType(string typeName) { return null; } [InlineCode("{$System.Script}.makeGenericType({genericType}, {typeArguments})")] public static Type MakeGenericType(Type genericType, Type[] typeArguments) { return null; } [InlineCode("{$System.Script}.getGenericTypeDefinition({this})")] public Type GetGenericTypeDefinition() { return null; } public bool IsGenericTypeDefinition { [InlineCode("{$System.Script}.isGenericTypeDefinition({this})")] get { return false; } } public int GenericParameterCount { [InlineCode("{$System.Script}.getGenericParameterCount({this})")] get { return 0; } } [InlineCode("{$System.Script}.getGenericArguments({this})")] public Type[] GetGenericArguments() { return null; } [InlineCode("{$System.Script}.getInterfaces({this})")] public Type[] GetInterfaces() { return null; } [InlineCode("{$System.Script}.isAssignableFrom({this}, {type})")] public bool IsAssignableFrom(Type type) { return false; } public bool IsClass { [InlineCode("{$System.Script}.isClass({this})")] get { return false; } } public bool IsEnum { [InlineCode("{$System.Script}.isEnum({this})")] get { return false; } } public bool IsFlags { [InlineCode("{$System.Script}.isFlags({this})")] get { return false; } } public bool IsInterface { [InlineCode("{$System.Script}.isInterface({this})")] get { return false; } } [InlineCode("{$System.Script}.getAttributes({this}, null, {inherit})")] public object[] GetCustomAttributes(bool inherit) { return null; } [InlineCode("{$System.Script}.getAttributes({this}, {attributeType}, {inherit})")] public object[] GetCustomAttributes(Type attributeType, bool inherit) { return null; } [InlineCode("{$System.Script}.isInstanceOfType({instance}, {this})")] public bool IsInstanceOfType(object instance) { return false; } [InlineCode("{$System.Script}.isInstanceOfType({instance}, {type})")] public static bool IsInstanceOfType(object instance, Type type) { return false; } [InlineCode("{$System.Script}.getMembers({this}, 31, 28)")] public MemberInfo[] GetMembers() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 31, {bindingAttr})")] public MemberInfo[] GetMembers(BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 31, 28, {name})")] public MemberInfo[] GetMember(string name) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 31, {bindingAttr}, {name})")] public MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 1, 28)")] public ConstructorInfo[] GetConstructors() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 1, 284, null, {parameterTypes})")] public ConstructorInfo GetConstructor(Type[] parameterTypes) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, 28)")] public MethodInfo[] GetMethods() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, {bindingAttr})")] public MethodInfo[] GetMethods(BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, 284, {name})")] public MethodInfo GetMethod(string name) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, {bindingAttr} | 256, {name})")] public MethodInfo GetMethod(string name, BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, 284, {name}, {parameterTypes})")] public MethodInfo GetMethod(string name, Type[] parameterTypes) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 8, {bindingAttr} | 256, {name}, {parameterTypes})")] public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Type[] parameterTypes) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, 28)")] public PropertyInfo[] GetProperties() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, {bindingAttr})")] public PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, 284, {name})")] public PropertyInfo GetProperty(string name) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, {bindingAttr} | 256, {name})")] public PropertyInfo GetProperty(string name, BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, 284, {name}, {parameterTypes})")] public PropertyInfo GetProperty(string name, Type[] parameterTypes) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 16, {bindingAttr} | 256, {name}, {parameterTypes})")] public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Type[] parameterTypes) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 2, 28)")] public EventInfo[] GetEvents() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 2, {bindingAttr})")] public EventInfo[] GetEvents(BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 2, 284, {name})")] public EventInfo GetEvent(string name) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 2, {bindingAttr} | 256, {name})")] public EventInfo GetEvent(string name, BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 4, 28)")] public FieldInfo[] GetFields() { return null; } [InlineCode("{$System.Script}.getMembers({this}, 4, {bindingAttr})")] public FieldInfo[] GetFields(BindingFlags bindingAttr) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 4, 284, {name})")] public FieldInfo GetField(string name) { return null; } [InlineCode("{$System.Script}.getMembers({this}, 4, {bindingAttr} | 256, {name})")] public FieldInfo GetField(string name, BindingFlags bindingAttr) { return null; } #endregion #region Script# reflection [InlineCode("{instance}['add_' + {name}]({handler})")] public static void AddHandler(object instance, string name, Delegate handler) { } [InlineCode("delete {instance}[{name}]")] public static void DeleteField(object instance, string name) { } [InlineCode("{instance}[{name}]")] public static object GetField(object instance, string name) { return null; } [InlineCode("{instance}['get_' + {name}]()")] public static object GetProperty(object instance, string name) { return null; } [ScriptAlias("typeof")] public static string GetScriptType(object instance) { return null; } [InlineCode("({name} in {instance})")] public static bool HasField(object instance, string name) { return false; } [InlineCode("(typeof({instance}[{name}]) === 'function')")] public static bool HasMethod(object instance, string name) { return false; } [InlineCode("{$System.Script}.hasProperty({instance}, {name})")] public static bool HasProperty(object instance, string name) { return false; } [InlineCode("{instance}[{name}]({*args})")] [Obsolete("Script# allows the instance parameter to be null, which is not supported by Saltarelle. Ensure that you are not using a null instance argument. It is recommended to modify your code to use 'dynamic' instead.")] public static object InvokeMethod(object instance, string name, params object[] args) { return null; } [InlineCode("{instance}['remove_' + {name}]({handler})")] public static void RemoveHandler(object instance, string name, Delegate handler) { } [InlineCode("{instance}[{name}] = {value}")] public static void SetField(object instance, string name, object value) { } [InlineCode("{instance}['set_' + {name}]({value})")] public static void SetProperty(object instance, string name, object value) { } #endregion /// <summary> /// Gets the prototype associated with the type. /// </summary> [IntrinsicProperty] public JsDictionary Prototype { get { return null; } } [Obsolete("Use Activator.CreateInstance() instead", true)] public static object CreateInstance(Type type, params object[] arguments) { return null; } [Obsolete("Use Activator.CreateInstance<T>() instead", true)] [IncludeGenericArguments] public static T CreateInstance<T>(params object[] arguments) where T : class { return null; } [EditorBrowsable(EditorBrowsableState.Never)] [NonScriptable] public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle) { return null; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests { public class Verify : ServiceManagementTest { /// <summary> /// /// </summary> /// <param name="vm"></param> /// <param name="availabilitySetName"></param> /// <returns></returns> internal static bool AzureAvailabilitySet(PersistentVM vm, string availabilitySetName) { try { if (string.IsNullOrEmpty(vm.AvailabilitySetName)) { Assert.IsTrue(string.IsNullOrEmpty(availabilitySetName)); } else { Assert.IsTrue(vm.AvailabilitySetName.Equals(availabilitySetName, StringComparison.InvariantCultureIgnoreCase)); } return true; } catch (Exception e) { Console.WriteLine(e.ToString()); if (e is AssertFailedException) { return false; } else { throw; } } } /// <summary> /// /// </summary> /// <param name="svc"></param> /// <param name="expThumbprint"></param> /// <param name="expAlgorithm"></param> /// <param name="expData"></param> /// <returns></returns> internal static bool AzureCertificate(string svc, string expThumbprint, string expAlgorithm, string expData) { try { CertificateContext result = vmPowershellCmdlets.GetAzureCertificate(svc)[0]; Assert.AreEqual(expThumbprint, result.Thumbprint); Assert.AreEqual(expAlgorithm, result.ThumbprintAlgorithm); Assert.AreEqual(expData, result.Data); Assert.AreEqual(svc, result.ServiceName); //Assert.AreEqual(expUrl, result.Url); return true; } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } } /// <summary> /// /// </summary> /// <param name="vm"></param> /// <param name="expLabel"></param> /// <param name="expSize"></param> /// <param name="expLun"></param> /// <param name="hc"></param> /// <returns></returns> internal static bool AzureDataDisk(PersistentVM vm, string expLabel, int expSize, int expLun, HostCaching hc) { bool found = false; foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(vm)) { if (CheckDataDisk(disk, expLabel, expSize, expLun, hc)) { found = true; break; } } return found; } private static bool CheckDataDisk(DataVirtualHardDisk disk, string expLabel, int expSize, int expLun, HostCaching hc) { Console.WriteLine("DataDisk - Name:{0}, Label:{1}, Size:{2}, LUN:{3}, HostCaching: {4}", disk.DiskName, disk.DiskLabel, disk.LogicalDiskSizeInGB, disk.Lun, disk.HostCaching); try { Assert.AreEqual(expLabel, disk.DiskLabel); Assert.AreEqual(expSize, disk.LogicalDiskSizeInGB); Assert.AreEqual(expLun, disk.Lun); if (disk.HostCaching == null && hc == HostCaching.None || disk.HostCaching == hc.ToString()) { Console.WriteLine("DataDisk found: {0}", disk.DiskLabel); } else { Assert.Fail("HostCaching is not matched!"); } } catch (Exception e) { Console.WriteLine(e.ToString()); if (e is AssertFailedException) { return false; } else { throw; } } return true; } /// <summary> /// /// </summary> /// <param name="resultSettings"></param> /// <param name="expDns"></param> /// <returns></returns> internal static bool AzureDns(DnsSettings resultSettings, DnsServer expDns) { try { DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(resultSettings); foreach (DnsServer dnsServer in dnsList) { Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address); if (MatchDns(expDns, dnsServer)) { Console.WriteLine("Matched Dns found!"); return true; } } return false; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } } private static bool MatchDns(DnsServer expDns, DnsServer actualDns) { try { Assert.AreEqual(expDns.Name, actualDns.Name); Assert.AreEqual(expDns.Address, actualDns.Address); return true; } catch (Exception e) { Console.WriteLine(e.ToString()); if (e is AssertFailedException) { return false; } else { throw; } } } /// <summary> /// /// </summary> /// <param name="vm"></param> /// <param name="epInfos"></param> /// <returns></returns> internal static bool AzureEndpoint(PersistentVM vm, AzureEndPointConfigInfo[] epInfos) { try { var serverEndpoints = vmPowershellCmdlets.GetAzureEndPoint(vm); // List the endpoints found for debugging. Console.WriteLine("***** Checking for Endpoints **************************************************"); Console.WriteLine("***** Listing Returned Endpoints"); foreach (InputEndpointContext ep in serverEndpoints) { Console.WriteLine("Endpoint - Name:{0} Protocol:{1} Port:{2} LocalPort:{3} Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip); if (!string.IsNullOrEmpty(ep.LBSetName)) { Console.WriteLine("\t- LBSetName:{0}", ep.LBSetName); Console.WriteLine("\t- Probe - Port:{0} Protocol:{1} Interval:{2} Timeout:{3}", ep.ProbePort, ep.ProbeProtocol, ep.ProbeIntervalInSeconds, ep.ProbeTimeoutInSeconds); } } Console.WriteLine("*******************************************************************************"); // Check if the specified endpoints were found. foreach (AzureEndPointConfigInfo epInfo in epInfos) { bool found = false; foreach (InputEndpointContext ep in serverEndpoints) { if (epInfo.CheckInputEndpointContext(ep)) { found = true; Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName); break; } } Assert.IsTrue(found, string.Format("Error: Endpoint '{0}' was not found!", epInfo.EndpointName)); } return true; } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } } /// <summary> /// /// </summary> /// <param name="vm"></param> /// <param name="expOS"></param> /// <param name="expHC"></param> /// <returns></returns> internal static bool AzureOsDisk(PersistentVM vm, string expOS, HostCaching expHC) { try { OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm); Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS); Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!"); Assert.AreEqual(expOS, osdisk.OS); Assert.AreEqual(expHC.ToString(), osdisk.HostCaching); return true; } catch (Exception e) { Console.WriteLine(e.ToString()); if (e is AssertFailedException) { return false; } else { throw; } } } /// <summary> /// /// </summary> /// <param name="svc"></param> /// <param name="expLabel"></param> /// <param name="expLocation"></param> /// <param name="expAff"></param> /// <param name="expDescription"></param> /// <param name="expStatus"></param> /// <returns></returns> internal static bool AzureService(string svc, string expLabel, string expLocation = "West US", string expAff = null, string expDescription = null, string expStatus = "Created") { try { HostedServiceDetailedContext result = vmPowershellCmdlets.GetAzureService(svc); Assert.AreEqual(expLabel, result.Label); Assert.AreEqual(expDescription, result.Description); Assert.AreEqual(expAff, result.AffinityGroup); Assert.AreEqual(expLocation, result.Location); Assert.AreEqual(expStatus, result.Status); Assert.AreEqual(svc, result.ServiceName); //Assert.AreEqual(expDateCreated, result.DateCreated); //Assert.AreEqual(expDateModified, result.DateModified); //Assert.AreEqual(expUrl, result.Url); return true; } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } } internal static bool AzureAclConfig(NetworkAclObject expectedAcl, NetworkAclObject actualAcl) { for (int i = 0; i < expectedAcl.Rules.Count; i++) { Assert.IsTrue(CompareContext(expectedAcl.Rules[i], actualAcl.Rules[i])); } return true; } internal static bool AzureReservedIP(ReservedIPContext rsvIP, string name, string label, string affname, string ip, string dep, string svcName, string id) { Utilities.PrintContext(rsvIP); Assert.AreEqual(name, rsvIP.ReservedIPName, "Reserved IP names are not equal!"); Assert.AreEqual(label, rsvIP.Label, "Reserved IP labels are not equal!"); Assert.AreEqual(affname, rsvIP.Location, "Reserved IP affinity groups are not equal!"); if (!string.IsNullOrEmpty(ip)) { Assert.AreEqual(ip, rsvIP.Address, "Reserved IP addresses are not equal!"); } Assert.AreEqual(dep, rsvIP.DeploymentName, "Reserved IP deployment names are not equal!"); Assert.AreEqual(svcName, rsvIP.ServiceName, "Reserved IP service names are not equal!"); if (!string.IsNullOrEmpty(id)) { Assert.AreEqual(id, rsvIP.Id, "Reserved IP IDs are not equal!"); } return true; } internal static bool AzureReservedIPNotInUse(ReservedIPContext rsvIP, string name, string label, string affname, string id = null) { AzureReservedIP(rsvIP, name, label, affname, null, null, null, id); Assert.AreEqual(false, rsvIP.InUse); return true; } internal static bool AzureReservedIPInUse(ReservedIPContext rsvIP, string name, string label, string affname, string ip = null, string deploymentName =null, string svcName = null) { AzureReservedIP(rsvIP, name, label, affname, ip, deploymentName, svcName, null); Assert.AreEqual(true, rsvIP.InUse); return true; } private static bool CompareContext<T>(T obj1, T obj2) { bool result = true; Type type = typeof(T); foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { if (typeName.Contains("System.DateTime")) { continue; } var obj1Value = property.GetValue(obj1, null); var obj2Value = property.GetValue(obj2, null); Console.WriteLine("Expected: {0}", obj1Value); Console.WriteLine("Acutal: {0}", obj2Value); if (obj1Value == null) { result &= (obj2Value == null); } else if (typeName.Contains("System.String")) { result &= (string.Compare(obj1Value.ToString(), obj2Value.ToString(), StringComparison.CurrentCultureIgnoreCase) == 0); } else { result &= (obj1Value.Equals(obj2Value)); } } else { Console.WriteLine("This type is not compared: {0}", typeName); } } return result; } } }
using UnityEngine; using Pathfinding.RVO.Sampled; namespace Pathfinding.RVO { /** Quadtree for quick nearest neighbour search of rvo agents. * \see Pathfinding.RVO.Simulator */ public class RVOQuadtree { const int LeafSize = 15; float maxRadius = 0; /** Node in a quadtree for storing RVO agents. * \see Pathfinding.GraphNode for the node class that is used for pathfinding data. */ struct Node { public int child00; public int child01; public int child10; public int child11; public Agent linkedList; public byte count; /** Maximum speed of all agents inside this node */ public float maxSpeed; public void Add (Agent agent) { agent.next = linkedList; linkedList = agent; } /** Distribute the agents in this node among the children. * Used after subdividing the node. */ public void Distribute (Node[] nodes, Rect r) { Vector2 c = r.center; while (linkedList != null) { Agent nx = linkedList.next; if (linkedList.position.x > c.x) { if (linkedList.position.y > c.y) { nodes[child11].Add(linkedList); } else { nodes[child10].Add(linkedList); } } else { if (linkedList.position.y > c.y) { nodes[child01].Add(linkedList); } else { nodes[child00].Add(linkedList); } } linkedList = nx; } count = 0; } public float CalculateMaxSpeed (Node[] nodes, int index) { if (child00 == index) { // Leaf node for (var agent = linkedList; agent != null; agent = agent.next) { maxSpeed = System.Math.Max(maxSpeed, agent.CalculatedSpeed); } } else { maxSpeed = System.Math.Max(nodes[child00].CalculateMaxSpeed(nodes, child00), nodes[child01].CalculateMaxSpeed(nodes, child01)); maxSpeed = System.Math.Max(maxSpeed, nodes[child10].CalculateMaxSpeed(nodes, child10)); maxSpeed = System.Math.Max(maxSpeed, nodes[child11].CalculateMaxSpeed(nodes, child11)); } return maxSpeed; } } Node[] nodes = new Node[42]; int filledNodes = 1; Rect bounds; /** Removes all agents from the tree */ public void Clear () { nodes[0] = new Node(); filledNodes = 1; maxRadius = 0; } public void SetBounds (Rect r) { bounds = r; } int GetNodeIndex () { if (filledNodes == nodes.Length) { var nds = new Node[nodes.Length*2]; for (int i = 0; i < nodes.Length; i++) nds[i] = nodes[i]; nodes = nds; } nodes[filledNodes] = new Node(); nodes[filledNodes].child00 = filledNodes; filledNodes++; return filledNodes-1; } /** Add a new agent to the tree. * \warning Agents must not be added multiple times to the same tree */ public void Insert (Agent agent) { int i = 0; Rect r = bounds; Vector2 p = new Vector2(agent.position.x, agent.position.y); agent.next = null; maxRadius = System.Math.Max(agent.radius, maxRadius); int depth = 0; while (true) { depth++; if (nodes[i].child00 == i) { // Leaf node. Break at depth 10 in case lots of agents ( > LeafSize ) are in the same spot if (nodes[i].count < LeafSize || depth > 10) { nodes[i].Add(agent); nodes[i].count++; break; } else { // Split Node node = nodes[i]; node.child00 = GetNodeIndex(); node.child01 = GetNodeIndex(); node.child10 = GetNodeIndex(); node.child11 = GetNodeIndex(); nodes[i] = node; nodes[i].Distribute(nodes, r); } } // Note, no else if (nodes[i].child00 != i) { // Not a leaf node Vector2 c = r.center; if (p.x > c.x) { if (p.y > c.y) { i = nodes[i].child11; r = Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax); } else { i = nodes[i].child10; r = Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y); } } else { if (p.y > c.y) { i = nodes[i].child01; r = Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax); } else { i = nodes[i].child00; r = Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y); } } } } } public void CalculateSpeeds () { nodes[0].CalculateMaxSpeed(nodes, 0); } public void Query (Vector2 p, float speed, float timeHorizon, float agentRadius, Agent agent) { new QuadtreeQuery { p = p, speed = speed, timeHorizon = timeHorizon, maxRadius = float.PositiveInfinity, agentRadius = agentRadius, agent = agent, nodes = nodes }.QueryRec(0, bounds); } struct QuadtreeQuery { public Vector2 p; public float speed, timeHorizon, agentRadius, maxRadius; public Agent agent; public Node[] nodes; public void QueryRec (int i, Rect r) { // Determine the radius that we need to search to take all agents into account // Note: the second agentRadius usage should actually be the radius of the other agents, not this agent // but for performance reasons and for simplicity we assume that agents have approximately the same radius. // Thus an agent with a very small radius may in some cases detect an agent with a very large radius too late // however this effect should be minor. var radius = System.Math.Min(System.Math.Max((nodes[i].maxSpeed + speed)*timeHorizon, agentRadius) + agentRadius, maxRadius); if (nodes[i].child00 == i) { // Leaf node for (Agent a = nodes[i].linkedList; a != null; a = a.next) { float v = agent.InsertAgentNeighbour(a, radius*radius); // Limit the search if the agent has hit the max number of nearby agents threshold if (v < maxRadius*maxRadius) { maxRadius = Mathf.Sqrt(v); } } } else { // Not a leaf node Vector2 c = r.center; if (p.x-radius < c.x) { if (p.y-radius < c.y) { QueryRec(nodes[i].child00, Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y)); radius = System.Math.Min(radius, maxRadius); } if (p.y+radius > c.y) { QueryRec(nodes[i].child01, Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax)); radius = System.Math.Min(radius, maxRadius); } } if (p.x+radius > c.x) { if (p.y-radius < c.y) { QueryRec(nodes[i].child10, Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y)); radius = System.Math.Min(radius, maxRadius); } if (p.y+radius > c.y) { QueryRec(nodes[i].child11, Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax)); } } } } } public void DebugDraw () { DebugDrawRec(0, bounds); } void DebugDrawRec (int i, Rect r) { Debug.DrawLine(new Vector3(r.xMin, 0, r.yMin), new Vector3(r.xMax, 0, r.yMin), Color.white); Debug.DrawLine(new Vector3(r.xMax, 0, r.yMin), new Vector3(r.xMax, 0, r.yMax), Color.white); Debug.DrawLine(new Vector3(r.xMax, 0, r.yMax), new Vector3(r.xMin, 0, r.yMax), Color.white); Debug.DrawLine(new Vector3(r.xMin, 0, r.yMax), new Vector3(r.xMin, 0, r.yMin), Color.white); if (nodes[i].child00 != i) { // Not a leaf node Vector2 c = r.center; DebugDrawRec(nodes[i].child11, Rect.MinMaxRect(c.x, c.y, r.xMax, r.yMax)); DebugDrawRec(nodes[i].child10, Rect.MinMaxRect(c.x, r.yMin, r.xMax, c.y)); DebugDrawRec(nodes[i].child01, Rect.MinMaxRect(r.xMin, c.y, c.x, r.yMax)); DebugDrawRec(nodes[i].child00, Rect.MinMaxRect(r.xMin, r.yMin, c.x, c.y)); } for (Agent a = nodes[i].linkedList; a != null; a = a.next) { var p = nodes[i].linkedList.position; Debug.DrawLine(new Vector3(p.x, 0, p.y)+Vector3.up, new Vector3(a.position.x, 0, a.position.y)+Vector3.up, new Color(1, 1, 0, 0.5f)); } } } }
namespace iTin.Export.Model { using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; using Helpers; /// <summary> /// Base class for the different types of lines supported by <strong><c>iTin Export Engine</c></strong>.<br/> /// Which acts as the base class for different types of lines. /// </summary> /// <remarks> /// <para> /// The following table shows different types of lines. /// </para> /// <list type="table"> /// <listheader> /// <term>Class</term> /// <description>Description</description> /// </listheader> /// <item> /// <term><see cref="T:iTin.Export.Model.EmptyLineModel"/></term> /// <description>Represents a data field.</description> /// </item> /// <item> /// <term><see cref="T:iTin.Export.Model.TextLineModel"/></term> /// <description>Represents a piece of a field fixed-width data.</description> /// </item> /// </list> /// </remarks> public abstract partial class BaseLineModel { #region private constants [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const int DefaultRepeat = 0; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const YesNo DefaultShow = YesNo.Yes; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultStyle = "Default"; #endregion #region field members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private YesNo _show; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string _style; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private LinesModel _owner; #endregion #region constructor/s #region [protected] BaseLineModel(): Initializes a new instance of this class /// <summary> /// Initializes a new instance of the <see cref="T:iTin.Export.Model.BaseLineModel" /> class. /// </summary> protected BaseLineModel() { Show = DefaultShow; Style = DefaultStyle; Repeat = DefaultRepeat; } #endregion #endregion #region public abstract properties #region [public] {override} (KnownLineType) LineType: Gets a value indicating line type /// <summary> /// Gets a value indicating line type. /// </summary> /// <value> /// One of the <see cref="T:iTin.Export.Model.KnownLineType" /> values. /// </value> public abstract KnownLineType LineType { get; } #endregion #endregion #region public properties #region [public] (string) Key: Gets or sets [XmlAttribute] public string Key { get; set; } #endregion #region [public] (int) Repeat: Gets or sets [XmlAttribute] [DefaultValue(DefaultRepeat)] public int Repeat { get; set; } #endregion #region [public] (LinesModel) Owner: Gets the element that owns this /// <summary> /// Gets the element that owns this data field. /// </summary> /// <value> /// The <see cref="T:iTin.Export.Model.LinesModel" /> that owns this data field. /// </value> [XmlIgnore] [Browsable(false)] public LinesModel Owner => _owner; #endregion [XmlAttribute] [DefaultValue(DefaultShow)] public YesNo Show { get => GetStaticBindingValue(_show.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes; set { SentinelHelper.IsEnumValid(value); _show = value; } } #region [public] (string) Style: Gets or sets one of the styles defined in the element styles [XmlAttribute] [DefaultValue(DefaultStyle)] public string Style { get => _style; set { SentinelHelper.ArgumentNull(value); SentinelHelper.IsFalse(RegularExpressionHelper.IsValidIdentifier(value), new InvalidIdentifierNameException(ErrorMessageHelper.ModelIdentifierNameErrorMessage("Header", "Style", value))); _style = value; } } #endregion #endregion #region public override properties #region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default /// <inheritdoc /> /// <summary> /// Gets a value indicating whether this instance is default. /// </summary> /// <value> /// <strong>true</strong> if this instance contains the default; otherwise, <strong>false</strong>. /// </value> public override bool IsDefault => Show.Equals(DefaultShow) && Style.Equals(DefaultStyle) && Repeat.Equals(DefaultRepeat); #endregion #endregion #region public methods #region [public] (void) SetOwner(LinesModel): Sets the element that owns this /// <summary> /// Sets the element that owns this data field. /// </summary> /// <param name="reference">Reference to owner.</param> public void SetOwner(LinesModel reference) { _owner = reference; } #endregion #region [public] (StyleModel) GetStyle(): Gets a reference to the style /// <summary> /// Gets a reference to the <see cref="T:iTin.Export.Model.StyleModel" /> from global resources. /// </summary> /// <returns> /// <strong>true</strong> if returns the style from resource; otherwise, <strong>false</strong>. /// </returns> public StyleModel GetStyle() { var hasStyle = TryGetStyle(out var tempStyle); return hasStyle ? tempStyle : StyleModel.Default; } #endregion #region [public] (bool) TryGetResourceInformation(out StyleModel): Gets a reference to the image resource information. /// <summary> /// Gets a reference to the image resource information. /// </summary> /// <param name="resource">Resource information.</param> /// <returns> /// <strong>true</strong> if exist available information about resource; otherwise, <strong>false</strong>. /// </returns> public bool TryGetResourceInformation(out StyleModel resource) { bool result; resource = StyleModel.Empty; if (string.IsNullOrEmpty(Style)) { return false; } try { if (Style == "Default") { resource = StyleModel.Default; } else { var globalresources = _owner.Parent; var export = globalresources.Parent; resource = export.Resources.GetStyleResourceByName(Style); } result = true; } catch { result = false; } return result; } #endregion #region [public] (bool) TryGetStyle(out Style): Gets a reference to the style from resource. /// <summary> /// Gets a reference to the <see cref="T:iTin.Export.Model.StyleModel" /> from global resources. /// </summary> /// <param name="style">A <see cref="T:iTin.Export.Model.StyleModel" /> resource.</param> /// <returns> /// <strong>true</strong> if returns the style from resource; otherwise, <strong>false</strong>. /// </returns> public bool TryGetStyle(out StyleModel style) { style = StyleModel.Empty; var foudResource = TryGetResourceInformation(out var resource); if (!foudResource) { return true; } ////var logo = this.parent; ////var table = logo.Parent; ////var export = table.Parent; style = resource; return true; } #endregion #endregion #region public override methods #region [public] {override} (string) ToString(): Returns a string that represents the current object. /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String" /> that represents the current object. /// </returns> /// <remarks> /// This method <see cref="BaseLineModel.ToString()"/> returns a string that includes field alias. /// </remarks> public override string ToString() { return $"Key=\"{Key}\""; } #endregion #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // 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 Microsoft.PackageManagement.SwidTag { using System; using System.Xml.Linq; using Utility; /// <summary> /// From the schema: /// A reference to any another item (can include details that are /// related to the SWID tag such as details on where software /// downloads can be found, vulnerability database associations, /// use rights, etc). /// This is modeled directly to match the HTML [LINK] element; it is /// critical for streamlining software discovery scenarios that /// these are kept consistent. /// </summary> public class Link : BaseElement { internal Link(XElement element) : base(element) { if (element.Name != Iso19770_2.Elements.Link) { throw new ArgumentException("Element is not of type 'Link'", "element"); } } internal Link(Uri href, string relationship) : base(new XElement(Iso19770_2.Elements.Link)) { HRef = href; Relationship = relationship; } /// <summary> /// For installation media (rel="installationmedia") - dictates the /// canonical name for the file. /// Items with the same artifact name should be considered mirrors /// of each other (so download from wherever works). /// </summary> public string Artifact { get { return GetAttribute(Iso19770_2.Attributes.Artifact); } set { AddAttribute(Iso19770_2.Attributes.Artifact, value); } } /// <summary> /// From the schema: /// The link to the item being referenced. /// The href can point to several different things, and can be any /// of the following: /// - a RELATIVE URI (no scheme) - which is interpreted depending on /// context (ie, "./folder/supplemental.swidtag" ) /// - a physical file location with any system-acceptable /// URI scheme (ie, file:// http:// https:// ftp:// ... etc ) /// - an URI with "swid:" as the scheme, which refers to another /// swid by tagId. This URI would need to be resolved in the /// context of the system by software that can lookup other /// swidtags.( ie, "swid:2df9de35-0aff-4a86-ace6-f7dddd1ade4c" ) /// - an URI with "swidpath:" as the scheme, which refers to another /// swid by an XPATH query. This URI would need to be resolved in /// the context of the system by software that can lookup other /// swidtags, and select the appropriate one based on an XPATH /// query. Examples: /// swidpath://SoftwareIdentity[Entity/@regid='http://contoso.com'] /// would retrieve all swidtags that had an entity where the /// regid was Contoso /// swidpath://SoftwareIdentity[Meta/@persistentId='b0c55172-38e9-4e36-be86-92206ad8eddb'] /// would retrieve swidtags that matched a specific persistentId /// See XPATH query standard : http://www.w3.org/TR/xpath20/ /// </summary> public Uri HRef { get { var v = GetAttribute(Iso19770_2.Attributes.HRef); Uri result; if (v != null && Uri.TryCreate(v, UriKind.Absolute, out result)) { return result; } return null; } set { AddAttribute(Iso19770_2.Attributes.HRef, value.ToString()); } } /// <summary> /// An attribute defined by the W3C Media Queries Recommendation /// (see http://www.w3.org/TR/css3-mediaqueries/). /// A hint to the consumer of the link to what the target item is /// applicable for. /// </summary> public string Media { get { return GetAttribute(Iso19770_2.Attributes.Media); } set { AddAttribute(Iso19770_2.Attributes.Media, value); } } /// <summary> /// Determines the relative strength of ownership of the target piece of software. /// </summary> public string Ownership { get { return GetAttribute(Iso19770_2.Attributes.Ownership); } set { AddAttribute(Iso19770_2.Attributes.Ownership, value); } } /// <summary> /// The relationship between this SWID and the target file. /// </summary> public string Relationship { get { return GetAttribute(Iso19770_2.Attributes.Relationship); } set { AddAttribute(Iso19770_2.Attributes.Relationship, value); } } /// <summary> /// The IANA MediaType for the target file; this provides the consumer /// with intelligence of what to expect. /// See http://www.iana.org/assignments/media-types/media-types.xhtml /// for more details on link type. /// </summary> public string MediaType { get { return GetAttribute(Iso19770_2.Attributes.MediaType); } set { AddAttribute(Iso19770_2.Attributes.MediaType, value); } } /// <summary> /// Determines if the target software is a hard requirement or not /// </summary> public string Use { get { return GetAttribute(Iso19770_2.Attributes.Use); } set { AddAttribute(Iso19770_2.Attributes.Use, value); } } public string MinimumName { get { return GetAttribute(Iso19770_2.Discovery.MinimumName); } set { AddAttribute(Iso19770_2.Discovery.MinimumName, value); } } public string MaximumName { get { return GetAttribute(Iso19770_2.Discovery.MaximumName); } set { AddAttribute(Iso19770_2.Discovery.MaximumName, value); } } public string MinimumVersion { get { return GetAttribute(Iso19770_2.Discovery.MinimumVersion); } set { AddAttribute(Iso19770_2.Discovery.MinimumVersion, value); } } public string MaximumVersion { get { return GetAttribute(Iso19770_2.Discovery.MaximumVersion); } set { AddAttribute(Iso19770_2.Discovery.MaximumVersion, value); } } public string Keyword { get { return GetAttribute(Iso19770_2.Discovery.Keyword); } set { AddAttribute(Iso19770_2.Discovery.Keyword, value); } } public string Version { get { return GetAttribute(Iso19770_2.Discovery.Version); } set { AddAttribute(Iso19770_2.Discovery.Version, value); } } public string Latest { get { return GetAttribute(Iso19770_2.Discovery.Latest); } set { AddAttribute(Iso19770_2.Discovery.Latest, value); } } public string Type { get { return GetAttribute(Iso19770_2.Discovery.Type); } set { AddAttribute(Iso19770_2.Discovery.Type, value); } } public string InstallParameters { get { return GetAttribute(Iso19770_2.Installation.InstallParameters); } set { AddAttribute(Iso19770_2.Installation.InstallParameters, value); } } public string InstallScript { get { return GetAttribute(Iso19770_2.Installation.InstallScript); } set { AddAttribute(Iso19770_2.Installation.InstallScript, value); } } public override string ToString() { return "{0}:{1}".format(Relationship, HRef); } } }
using System; using System.Collections.Generic; using System.Linq; using Chutzpah.BatchProcessor; using Chutzpah.Exceptions; using Chutzpah.Models; using Chutzpah.Wrappers; using Moq; using Xunit; using Chutzpah.FileProcessors; using System.IO; namespace Chutzpah.Facts { public class BatchCompilerServiceFacts { public class TestableBatchCompilerService : Testable<BatchCompilerService> { public TestableBatchCompilerService() { Mock<IProcessHelper>().Setup(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>())).Returns(new BatchCompileResult()); Mock<ISourceMapDiscoverer>().Setup(x => x.FindSourceMap(@"C:\src\a.js")).Returns(@"C:\src\a.js.map"); } public TestContext BuildContext() { var context = new TestContext(); context.TestFileSettings = new ChutzpahTestSettingsFile { SettingsFileDirectory = @"C:\src", Compile = new BatchCompileConfiguration { Mode = BatchCompileMode.Executable, Executable = "compile.bat", SkipIfUnchanged = true, WorkingDirectory = @"C:\src", Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\src", OutputPath = @"C:\src" } } } }.InheritFromDefault(); return context; } } [Fact] public void Will_not_compile_if_no_compile_setting() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile = null; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))).Returns(false).Returns(true); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Never()); Assert.Null(context.ReferencedFiles.ElementAt(0).GeneratedFilePath); } [Fact] public void Will_compile_and_mark_generate_paths_from_one_context_when_output_missing() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.js" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false) .Returns(false) .Returns(true) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>())); Assert.Equal(@"C:\src\a.js", context.ReferencedFiles.ElementAt(0).GeneratedFilePath); Assert.Equal(@"C:\src\b.js", context.ReferencedFiles.ElementAt(1).GeneratedFilePath); Assert.Null(context.ReferencedFiles.ElementAt(2).GeneratedFilePath); } [Fact] public void Will_throw_if_file_is_missing() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.Mode = BatchCompileMode.External; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.js" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false) .Returns(true) .Returns(false) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); var ex = Record.Exception( () => service.ClassUnderTest.Compile(new[] { context })); Assert.IsType<FileNotFoundException>(ex); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Never()); } [Fact] public void Will_mark_generated_path_when_output_folder_is_set() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\src", OutputPath = @"C:\out" } }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); Assert.Equal(@"C:\out\a.js", context.ReferencedFiles.ElementAt(0).GeneratedFilePath); } [Fact] public void Will_mark_generated_path_when_source_folder_is_set() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\other", OutputPath = @"C:\src" } }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\other\a.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".js")))) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); Assert.Equal(@"C:\src\a.js", context.ReferencedFiles.ElementAt(0).GeneratedFilePath); } [Fact] public void Will_set_source_map_path_when_UseSourceMap_setting_enabled() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\other", OutputPath = @"C:\src" } }; context.TestFileSettings.Compile.UseSourceMaps = true; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\other\a.ts" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".js")))) .Returns(false) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); Assert.Equal(@"C:\src\a.js.map", context.ReferencedFiles.ElementAt(0).SourceMapFilePath); } [Fact] public void Will_not_set_source_map_path_when_UseSourceMap_setting_disabled() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\other", OutputPath = @"C:\src" } }; context.TestFileSettings.Compile.UseSourceMaps = false; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\other\a.ts" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".js")))) .Returns(false) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f != null && f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); Assert.Null(context.ReferencedFiles.ElementAt(0).SourceMapFilePath); service.Mock<ISourceMapDiscoverer>().Verify(x => x.FindSourceMap(It.IsAny<string>()), Times.Never()); } [Fact] public void Will_not_look_for_generate_output_for_extensions_which_wont_have() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.ExtensionsWithNoOutput = new[] { ".d.ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.d.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IFileSystemWrapper>().Verify(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js"))), Times.Never()); Assert.Null(context.ReferencedFiles.ElementAt(0).GeneratedFilePath); } [Fact] public void Will_skip_compile_if_all_files_have_up_to_date_output() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.ts")).Returns(DateTime.Now.AddDays(-1)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.js")).Returns(DateTime.Now); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.ts")).Returns(DateTime.Now); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.js")).Returns(DateTime.Now); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Never()); } [Fact] public void Will_compile_if_source_file_is_newer_than_output() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.ts")).Returns(DateTime.Now.AddDays(1)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.js")).Returns(DateTime.Now); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.ts")).Returns(DateTime.Now); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.js")).Returns(DateTime.Now); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>())); } [Fact] public void Will_compile_if_souce_who_makes_no_output_is_newer_than_oldest_output() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.ExtensionsWithNoOutput = new[] { ".d.ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.d.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\c.d.ts")).Returns(DateTime.Now.AddDays(-2)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.ts")).Returns(DateTime.Now.AddDays(-4)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.js")).Returns(DateTime.Now.AddDays(-3)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.ts")).Returns(DateTime.Now.AddDays(-5)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.js")).Returns(DateTime.Now.AddDays(-1)); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>())); } [Fact] public void Will_not_compile_if_souce_who_makes_no_output_is_not_newer_than_oldest_output() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.TestFileSettings.Compile.ExtensionsWithNoOutput = new[] { ".d.ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.d.ts" }); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\c.d.ts")).Returns(DateTime.Now.AddDays(-3)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.ts")).Returns(DateTime.Now.AddDays(-4)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\a.js")).Returns(DateTime.Now.AddDays(-2)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.ts")).Returns(DateTime.Now.AddDays(-5)); service.Mock<IFileSystemWrapper>().Setup(x => x.GetLastWriteTime(@"C:\src\b.js")).Returns(DateTime.Now.AddDays(-1)); service.ClassUnderTest.Compile(new[] { context }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Never()); } [Fact] public void Will_throw_if_process_returns_non_zero_exit_code() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false) .Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.Mock<IProcessHelper>() .Setup(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>())) .Returns(new BatchCompileResult { ExitCode = 1 }); var ex = Record.Exception(() => service.ClassUnderTest.Compile(new[] { context })); Assert.IsType<ChutzpahCompilationFailedException>(ex); } [Fact] public void Will_compile_multiple_contexts_which_have_one_settings_file() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.js" }); var context2 = service.BuildContext(); context2.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context2.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context2.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\d.ts" }); context2.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\c.js" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false).Returns(false).Returns(false) .Returns(true).Returns(true).Returns(true).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context, context2 }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Once()); Assert.Equal(@"C:\src\a.js", context.ReferencedFiles.ElementAt(0).GeneratedFilePath); Assert.Equal(@"C:\src\b.js", context.ReferencedFiles.ElementAt(1).GeneratedFilePath); Assert.Null(context.ReferencedFiles.ElementAt(2).GeneratedFilePath); Assert.Equal(@"C:\src\a.js", context2.ReferencedFiles.ElementAt(0).GeneratedFilePath); Assert.Equal(@"C:\src\d.js", context2.ReferencedFiles.ElementAt(1).GeneratedFilePath); Assert.Null(context2.ReferencedFiles.ElementAt(2).GeneratedFilePath); } [Fact] public void Will_compile_multiple_contexts_which_have_different_settings_file() { var service = new TestableBatchCompilerService(); var context = service.BuildContext(); context.TestFileSettings.SettingsFileDirectory = @"C:\src"; context.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\a.ts" }); context.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\src\b.ts" }); var context2 = service.BuildContext(); context2.TestFileSettings.SettingsFileDirectory = @"C:\other"; context2.TestFileSettings.Compile.Paths = new List<CompilePathMap> { new CompilePathMap { SourcePath = @"C:\other", OutputPath = @"C:\other" } }; context2.TestFileSettings.Compile.Extensions = new[] { ".ts" }; context2.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\other\a.ts" }); context2.ReferencedFiles.Add(new ReferencedFile { Path = @"C:\other\d.ts" }); service.Mock<IFileSystemWrapper>().SetupSequence(x => x.FileExists(It.Is<string>(f => f.EndsWith(".js")))) .Returns(false).Returns(false).Returns(true).Returns(true) .Returns(false).Returns(false).Returns(true).Returns(true); service.Mock<IFileSystemWrapper>().Setup(x => x.FileExists(It.Is<string>(f => f.EndsWith(".ts")))).Returns(true); service.ClassUnderTest.Compile(new[] { context, context2 }); service.Mock<IProcessHelper>().Verify(x => x.RunBatchCompileProcess(It.IsAny<BatchCompileConfiguration>()), Times.Exactly(2)); Assert.Equal(@"C:\src\a.js", context.ReferencedFiles.ElementAt(0).GeneratedFilePath); Assert.Equal(@"C:\src\b.js", context.ReferencedFiles.ElementAt(1).GeneratedFilePath); Assert.Equal(@"C:\other\a.js", context2.ReferencedFiles.ElementAt(0).GeneratedFilePath); Assert.Equal(@"C:\other\d.js", context2.ReferencedFiles.ElementAt(1).GeneratedFilePath); } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Reflection; using Irony.Ast; namespace Irony.Parsing { [Flags] public enum TermFlags { None = 0, IsOperator = 0x01, IsOpenBrace = 0x02, IsCloseBrace = 0x04, IsBrace = IsOpenBrace | IsCloseBrace, IsLiteral = 0x08, IsConstant = 0x10, IsPunctuation = 0x20, IsDelimiter = 0x40, IsReservedWord = 0x080, IsMemberSelect = 0x100, InheritPrecedence = 0x200, // Signals that non-terminal must inherit precedence and assoc values from its children. // Typically set for BinOp nonterminal (where BinOp.Rule = '+' | '-' | ...) IsNonScanner = 0x01000, // indicates that tokens for this terminal are NOT produced by scanner IsNonGrammar = 0x02000, // if set, parser would eliminate the token from the input stream; terms in Grammar.NonGrammarTerminals have this flag set IsTransient = 0x04000, // Transient non-terminal - should be replaced by it's child in the AST tree. IsNotReported = 0x08000, // Exclude from expected terminals list on syntax error //calculated flags IsNullable = 0x010000, IsVisible = 0x020000, IsKeyword = 0x040000, IsMultiline = 0x100000, //internal flags IsList = 0x200000, IsListContainer = 0x400000, //Indicates not to create AST node; mainly to suppress warning message on some special nodes that AST node type is not specified //Automatically set by MarkTransient method NoAstNode = 0x800000, //A flag to suppress automatic AST creation for child nodes in global AST construction. Will be used to supress full // "compile" of method bodies in modules. The module might be large, but the running code might // be actually using only a few methods or global members; so in this case it makes sense to "compile" only global/public // declarations, including method headers but not full bodies. The body will be compiled on the first call. // This makes even more sense when processing module imports. AstDelayChildren = 0x1000000, } //Basic Backus-Naur Form element. Base class for Terminal, NonTerminal, BnfExpression, GrammarHint public abstract class BnfTerm { #region consructors public BnfTerm(string name) : this(name, name) { } public BnfTerm(string name, string errorAlias, Type nodeType) : this(name, errorAlias) { this.AstConfig.NodeType = nodeType; } public BnfTerm(string name, string errorAlias, AstNodeCreator nodeCreator) : this(name, errorAlias) { this.AstConfig.NodeCreator = nodeCreator; } public BnfTerm(string name, string errorAlias) { this.Name = name; this.ErrorAlias = errorAlias; this._hashCode = (_hashCounter++).GetHashCode(); } #endregion #region virtuals and overrides public virtual void Init(GrammarData grammarData) { this.GrammarData = grammarData; } public virtual string GetParseNodeCaption(ParseTreeNode node) { if (this.GrammarData != null) { return this.GrammarData.Grammar.GetParseNodeCaption(node); } else { return this.Name; } } public override string ToString() { return this.Name; } //Hash code - we use static counter to generate hash codes private static int _hashCounter; private int _hashCode; public override int GetHashCode() { return this._hashCode; } #endregion public const int NoPrecedence = 0; #region properties: Name, DisplayName, Key, Options public string Name; //ErrorAlias is used in error reporting, e.g. "Syntax error, expected <list-of-display-names>". public string ErrorAlias; public TermFlags Flags; protected GrammarData GrammarData; public int Precedence = NoPrecedence; public Associativity Associativity = Associativity.Neutral; public Grammar Grammar { get { return this.GrammarData.Grammar; } } public void SetFlag(TermFlags flag) { this.SetFlag(flag, true); } public void SetFlag(TermFlags flag, bool value) { if (value) { this.Flags |= flag; } else { this.Flags &= ~flag; } } #endregion #region events: Shifting public event EventHandler<ParsingEventArgs> Shifting; public event EventHandler<AstNodeEventArgs> AstNodeCreated; //an event fired after AST node is created. protected internal void OnShifting(ParsingEventArgs args) { if (this.Shifting != null) { this.Shifting(this, args); } } protected internal void OnAstNodeCreated(ParseTreeNode parseNode) { if (this.AstNodeCreated == null || parseNode.AstNode == null) { return; } AstNodeEventArgs args = new AstNodeEventArgs(parseNode); this.AstNodeCreated(this, args); } #endregion #region AST node creations: AstNodeType, AstNodeCreator, AstNodeCreated //We autocreate AST config on first GET; public AstNodeConfig AstConfig { get { if (this._astConfig == null) { this._astConfig = new Ast.AstNodeConfig(); } return this._astConfig; } set { this._astConfig = value; } } private AstNodeConfig _astConfig; public bool HasAstConfig() { return this._astConfig != null; } #endregion #region Kleene operator Q() private NonTerminal _q; public BnfExpression Q() { if (this._q != null) { return this._q; } this._q = new NonTerminal(this.Name + "?"); this._q.Rule = this | Grammar.CurrentGrammar.Empty; return this._q; } #endregion #region Operators: +, |, implicit public static BnfExpression operator +(BnfTerm term1, BnfTerm term2) { return Op_Plus(term1, term2); } public static BnfExpression operator +(BnfTerm term1, string symbol2) { return Op_Plus(term1, Grammar.CurrentGrammar.ToTerm(symbol2)); } public static BnfExpression operator +(string symbol1, BnfTerm term2) { return Op_Plus(Grammar.CurrentGrammar.ToTerm(symbol1), term2); } //Alternative public static BnfExpression operator |(BnfTerm term1, BnfTerm term2) { return Op_Pipe(term1, term2); } public static BnfExpression operator |(BnfTerm term1, string symbol2) { return Op_Pipe(term1, Grammar.CurrentGrammar.ToTerm(symbol2)); } public static BnfExpression operator |(string symbol1, BnfTerm term2) { return Op_Pipe(Grammar.CurrentGrammar.ToTerm(symbol1), term2); } //BNF operations implementation ----------------------- // Plus/sequence internal static BnfExpression Op_Plus(BnfTerm term1, BnfTerm term2) { //Check term1 and see if we can use it as result, simply adding term2 as operand BnfExpression expr1 = term1 as BnfExpression; if (expr1 == null || expr1.Data.Count > 1) { //either not expression at all, or Pipe-type expression (count > 1) expr1 = new BnfExpression(term1); } expr1.Data[expr1.Data.Count - 1].Add(term2); return expr1; } //Pipe/Alternative //New version proposed by the codeplex user bdaugherty internal static BnfExpression Op_Pipe(BnfTerm term1, BnfTerm term2) { BnfExpression expr1 = term1 as BnfExpression; if (expr1 == null) { expr1 = new BnfExpression(term1); } BnfExpression expr2 = term2 as BnfExpression; if (expr2 == null) { expr2 = new BnfExpression(term2); } expr1.Data.AddRange(expr2.Data); return expr1; } #endregion }//class public class BnfTermList : List<BnfTerm> { } public class BnfTermSet : HashSet<BnfTerm> { } }//namespace
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: IntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public struct IntPtr : ISerializable { [SecurityCritical] unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior public static readonly IntPtr Zero; // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access [System.Security.SecuritySafeCritical] // auto-generated [Pure] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe bool IsNull() { return (this.m_value == null); } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(int value) { #if WIN32 m_value = (void *)value; #else m_value = (void *)(long)value; #endif } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(long value) { #if WIN32 m_value = (void *)checked((int)value); #else m_value = (void *)value; #endif } [System.Security.SecurityCritical] [CLSCompliant(false)] [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public unsafe IntPtr(void* value) { m_value = value; } [System.Security.SecurityCritical] // auto-generated private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long l = info.GetInt64("value"); if (Size==4 && (l>Int32.MaxValue || l<Int32.MinValue)) { throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue")); } m_value = (void *)l; } #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); #if WIN32 info.AddValue("value", (long)((int)m_value)); #else info.AddValue("value", (long)(m_value)); #endif } #endif [System.Security.SecuritySafeCritical] // auto-generated public unsafe override bool Equals(Object obj) { if (obj is IntPtr) { return (m_value == ((IntPtr)obj).m_value); } return false; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override int GetHashCode() { return unchecked((int)((long)m_value)); } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe int ToInt32() { #if WIN32 return (int)m_value; #else long l = (long)m_value; return checked((int)l); #endif } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe long ToInt64() { #if WIN32 return (long)(int)m_value; #else return (long)m_value; #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override String ToString() { #if WIN32 return ((int)m_value).ToString(CultureInfo.InvariantCulture); #else return ((long)m_value).ToString(CultureInfo.InvariantCulture); #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); #if WIN32 return ((int)m_value).ToString(format, CultureInfo.InvariantCulture); #else return ((long)m_value).ToString(format, CultureInfo.InvariantCulture); #endif } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr (int value) { return new IntPtr(value); } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static explicit operator IntPtr (long value) { return new IntPtr(value); } [System.Security.SecurityCritical] [CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator IntPtr (void* value) { return new IntPtr(value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] public static unsafe explicit operator void* (IntPtr value) { return value.m_value; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator int (IntPtr value) { #if WIN32 return (int)value.m_value; #else long l = (long)value.m_value; return checked((int)l); #endif } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static explicit operator long (IntPtr value) { #if WIN32 return (long)(int)value.m_value; #else return (long)value.m_value; #endif } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator == (IntPtr value1, IntPtr value2) { return value1.m_value == value2.m_value; } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool operator != (IntPtr value1, IntPtr value2) { return value1.m_value != value2.m_value; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr operator +(IntPtr pointer, int offset) { #if WIN32 return new IntPtr(pointer.ToInt32() + offset); #else return new IntPtr(pointer.ToInt64() + offset); #endif } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] [System.Runtime.Versioning.NonVersionable] public static IntPtr operator -(IntPtr pointer, int offset) { #if WIN32 return new IntPtr(pointer.ToInt32() - offset); #else return new IntPtr(pointer.ToInt64() - offset); #endif } public static int Size { [Pure] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] get { #if WIN32 return 4; #else return 8; #endif } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public unsafe void* ToPointer() { return m_value; } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using NLog.Common; using NLog.LogReceiverService; using NLog.Config; using NLog.Targets; using Xunit; using NLog.Targets.Wrappers; using System.Threading; public class LogReceiverWebServiceTargetTests : NLogTestBase { [Fact] public void LogReceiverWebServiceTargetSingleEventTest() { var logger = LogManager.GetLogger("loggerName"); var target = new MyLogReceiverWebServiceTarget(); target.EndpointAddress = "http://notimportant:9999/"; target.Parameters.Add(new MethodCallParameter("message", "${message}")); target.Parameters.Add(new MethodCallParameter("lvl", "${level}")); SimpleConfigurator.ConfigureForTargetLogging(target); logger.Info("message text"); var payload = target.LastPayload; Assert.Equal(2, payload.LayoutNames.Count); Assert.Equal("message", payload.LayoutNames[0]); Assert.Equal("lvl", payload.LayoutNames[1]); Assert.Equal(3, payload.Strings.Count); Assert.Single(payload.Events); Assert.Equal("message text", payload.Strings[payload.Events[0].ValueIndexes[0]]); Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]); Assert.Equal("loggerName", payload.Strings[payload.Events[0].LoggerOrdinal]); } [Fact] public void LogReceiverWebServiceTargetMultipleEventTest() { var target = new MyLogReceiverWebServiceTarget(); target.EndpointAddress = "http://notimportant:9999/"; target.Parameters.Add(new MethodCallParameter("message", "${message}")); target.Parameters.Add(new MethodCallParameter("lvl", "${level}")); var exceptions = new List<Exception>(); var events = new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add), LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add), LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add), }; var configuration = new LoggingConfiguration(); target.Initialize(configuration); target.WriteAsyncLogEvents(events); // with multiple events, we should get string caching var payload = target.LastPayload; Assert.Equal(2, payload.LayoutNames.Count); Assert.Equal("message", payload.LayoutNames[0]); Assert.Equal("lvl", payload.LayoutNames[1]); // 7 strings instead of 9 since 'logger1' and 'message2' are being reused Assert.Equal(7, payload.Strings.Count); Assert.Equal(3, payload.Events.Length); Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]); Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]); Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]); Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]); Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]); Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]); Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]); Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]); Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]); Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal); } [Fact] public void LogReceiverWebServiceTargetMultipleEventWithPerEventPropertiesTest() { var target = new MyLogReceiverWebServiceTarget(); target.IncludeEventProperties = true; target.EndpointAddress = "http://notimportant:9999/"; target.Parameters.Add(new MethodCallParameter("message", "${message}")); target.Parameters.Add(new MethodCallParameter("lvl", "${level}")); var exceptions = new List<Exception>(); var events = new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add), LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add), LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add), }; events[0].LogEvent.Properties["prop1"] = "value1"; events[1].LogEvent.Properties["prop1"] = "value2"; events[2].LogEvent.Properties["prop1"] = "value3"; events[0].LogEvent.Properties["prop2"] = "value2a"; var configuration = new LoggingConfiguration(); target.Initialize(configuration); target.WriteAsyncLogEvents(events); // with multiple events, we should get string caching var payload = target.LastPayload; // 4 layout names - 2 from Parameters, 2 from unique properties in events Assert.Equal(4, payload.LayoutNames.Count); Assert.Equal("message", payload.LayoutNames[0]); Assert.Equal("lvl", payload.LayoutNames[1]); Assert.Equal("prop1", payload.LayoutNames[2]); Assert.Equal("prop2", payload.LayoutNames[3]); Assert.Equal(12, payload.Strings.Count); Assert.Equal(3, payload.Events.Length); Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]); Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]); Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]); Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]); Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]); Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]); Assert.Equal("value1", payload.Strings[payload.Events[0].ValueIndexes[2]]); Assert.Equal("value2", payload.Strings[payload.Events[1].ValueIndexes[2]]); Assert.Equal("value3", payload.Strings[payload.Events[2].ValueIndexes[2]]); Assert.Equal("value2a", payload.Strings[payload.Events[0].ValueIndexes[3]]); Assert.Equal("", payload.Strings[payload.Events[1].ValueIndexes[3]]); Assert.Equal("", payload.Strings[payload.Events[2].ValueIndexes[3]]); Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]); Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]); Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]); Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal); } [Fact] public void NoEmptyEventLists() { var configuration = new LoggingConfiguration(); var target = new MyLogReceiverWebServiceTarget(); target.EndpointAddress = "http://notimportant:9999/"; target.Initialize(configuration); var asyncTarget = new AsyncTargetWrapper(target) { Name = "NoEmptyEventLists_wrapper" }; try { asyncTarget.Initialize(configuration); asyncTarget.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(ex => { }) }); Thread.Sleep(1000); Assert.Equal(1, target.SendCount); } finally { asyncTarget.Close(); target.Close(); } } public class MyLogReceiverWebServiceTarget : LogReceiverWebServiceTarget { public NLogEvents LastPayload; public int SendCount; public MyLogReceiverWebServiceTarget() : base() { } public MyLogReceiverWebServiceTarget(string name) : base(name) { } protected internal override bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { LastPayload = events; ++SendCount; foreach (var ac in asyncContinuations) { ac.Continuation(null); } return false; } } } }
namespace Nancy.Tests.Unit { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using FakeItEasy; using Nancy.IO; using Xunit; using Xunit.Extensions; public class RequestFixture { [Fact] public void Should_dispose_request_stream_when_being_disposed() { // Given var stream = A.Fake<RequestStream>(x => { x.Implements(typeof(IDisposable)); x.WithArgumentsForConstructor(() => new RequestStream(0, false)); }); var url = new Url() { Scheme = "http", Path = "localhost" }; var request = new Request("GET", url, stream); // When request.Dispose(); // Then A.CallTo(() => ((IDisposable)stream).Dispose()).MustHaveHappened(); } [Fact] public void Should_be_disposable() { // Given, When, Then typeof(Request).ShouldImplementInterface<IDisposable>(); } [Fact] public void Should_override_request_method_on_post() { // Given const string bodyContent = "_method=GET"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", "/", headers, memory, "http"); // Then request.Method.ShouldEqual("GET"); } [Theory] [InlineData("GET")] [InlineData("PUT")] [InlineData("DELETE")] [InlineData("HEAD")] public void Should_only_override_method_on_post(string method) { // Given const string bodyContent = "_method=TEST"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request(method, "/", headers, memory, "http"); // Then request.Method.ShouldEqual(method); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_method() { // Given, When var exception = Record.Exception(() => new Request(null, "/", "http")); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method() { // Given, When var exception = Record.Exception(() => new Request(string.Empty, "/", "http")); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_null_exception_when_initialized_with_null_uri() { // Given, When var exception = Record.Exception(() => new Request("GET", null, "http")); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_set_method_parameter_value_to_method_property_when_initialized() { // Given const string method = "GET"; // When var request = new Request(method, "/", "http"); // Then request.Method.ShouldEqual(method); } [Fact] public void Should_set_uri_parameter_value_to_uri_property_when_initialized() { // Given const string path = "/"; // When var request = new Request("GET", path, "http"); // Then request.Path.ShouldEqual(path); } [Fact] public void Should_set_header_parameter_value_to_header_property_when_initialized() { // Given var headers = new Dictionary<string, IEnumerable<string>>() { { "content-type", new[] {"foo"} } }; // When var request = new Request("GET", "/", headers, CreateRequestStream(), "http"); // Then request.Headers.ContentType.ShouldNotBeEmpty(); } [Fact] public void Should_set_body_parameter_value_to_body_property_when_initialized() { // Given var body = CreateRequestStream(); // When var request = new Request("GET", "/", new Dictionary<string, IEnumerable<string>>(), body, "http"); // Then request.Body.ShouldBeSameAs(body); } [Fact] public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", "/", headers, memory, "http"); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded_with_character_set() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } } }; // When var request = new Request("POST", "/", headers, memory, "http"); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_set_extracted_form_data_from_body_when_content_type_is_multipart_form_data() { // Given var memory = new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string> { { "name", "John Doe"}, { "age", "42"} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then ((string)request.Form.name).ShouldEqual("John Doe"); ((string)request.Form.age).ShouldEqual("42"); } [Fact] public void Should_set_extracted_files_to_files_collection_when_body_content_type_is_multipart_form_data() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "test", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then request.Files.ShouldHaveCount(1); } [Fact] public void Should_set_content_type_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then request.Files.First().ContentType.ShouldEqual("content/type"); } [Fact] public void Should_set_name_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then request.Files.First().Name.ShouldEqual("sample.txt"); } [Fact] public void Should_value_on_file_extracted_from_multipart_form_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then GetStringValue(request.Files.First().Value).ShouldEqual("some test content"); } [Fact] public void Should_set_key_on_file_extracted_from_multipart_data_body() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "fieldname")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then request.Files.First().Key.ShouldEqual("fieldname"); } private static string GetStringValue(Stream stream) { var reader = new StreamReader(stream); return reader.ReadToEnd(); } [Fact] public void Should_be_able_to_invoke_form_repeatedly() { const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = new MemoryStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then ((string)request.Form.name).ShouldEqual("John Doe"); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_protocol() { // Given, When var exception = Record.Exception(() => new Request("GET", "/", null)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_throw_argumentoutofrangeexception_when_initialized_with_an_empty_protocol() { // Given, When var exception = Record.Exception(() => new Request("GET", "/", string.Empty)); // Then exception.ShouldBeOfType<ArgumentOutOfRangeException>(); } [Fact] public void Should_set_protocol_parameter_value_to_protocol_property_when_initialized() { // Given const string protocol = "http"; // When var request = new Request("GET", "/", protocol); // Then request.Url.Scheme.ShouldEqual(protocol); } [Fact] public void Should_split_cookie_in_two_parts_only() { // Given, when var cookieName = "_nc"; var cookieData = "Y+M3rcC/7ssXvHTx9pwCbwQVV4g=sp0hUZVApYgGbKZIU4bvXbBCVl9fhSEssEXSGdrt4jVag6PO1oed8lSd+EJD1nzWx4OTTCTZKjYRWeHE97QVND4jJIl+DuKRgJnSl3hWI5gdgGjcxqCSTvMOMGmW3NHLVyKpajGD8tq1DXhXMyXHjTzrCAYl8TGzwyJJGx/gd7VMJeRbAy9JdHOxEUlCKUnPneWN6q+/ITFryAa5hAdfcjXmh4Fgym75whKOMkWO+yM2icdsciX0ShcvnEQ/bXcTHTya6d7dJVfZl7qQ8AgIQv8ucQHxD3NxIvHNPBwms2ClaPds0HG5N+7pu7eMSFZjUHpDrrCnFvYN+JDiG3GMpf98LuCCvxemvipJo2MUkY4J1LvaDFoWA5tIxAfItZJkSIW2d8JPDwFk8OHJy8zhyn8AjD2JFqWaUZr4y9KZOtgI0V0Qlq0mS3mDSlLn29xapgoPHBvykwQjR6TwF2pBLpStsfZa/tXbEv2mc3VO3CnErIA1lEfKNqn9C/Dw6hqW"; var headers = new Dictionary<string, IEnumerable<string>>(); var cookies = new List<string>(); cookies.Add(string.Format("{0}={1}", cookieName, cookieData)); headers.Add("cookie", cookies); var newUrl = new Url { Path = "/" }; var request = new Request("GET", newUrl, null, headers); // Then request.Cookies[cookieName].ShouldEqual(cookieData); } [Fact] public void Should_move_request_body_position_to_zero_after_parsing_url_encoded_data() { // Given const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(bodyContent); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } } }; // When var request = new Request("POST", "/", headers, memory, "http"); // Then memory.Position.ShouldEqual(0L); } [Fact] public void Should_move_request_body_position_to_zero_after_parsing_multipart_encoded_data() { // Given var memory = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>> { { "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")} })); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then memory.Position.ShouldEqual(0L); } [Fact] public void Should_preserve_all_values_when_multiple_are_posted_using_same_name_after_parsing_multipart_encoded_data() { // Given var memory = new MemoryStream(BuildMultipartFormValues( new KeyValuePair<string, string>("age", "32"), new KeyValuePair<string, string>("age", "42"), new KeyValuePair<string, string>("age", "52") )); var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } } }; // When var request = new Request("POST", "/", headers, CreateRequestStream(memory), "http"); // Then ((string)request.Form.age).ShouldEqual("32,42,52"); } [Fact] public void Should_limit_the_amount_of_form_fields_parsed() { // Given var sb = new StringBuilder(); for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++) { if (i > 0) { sb.Append('&'); } sb.AppendFormat("Field{0}=Value{0}", i); } var memory = CreateRequestStream(); var writer = new StreamWriter(memory); writer.Write(sb.ToString()); writer.Flush(); memory.Position = 0; var headers = new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } }; // When var request = new Request("POST", "/", headers, memory, "http"); // Then ((IEnumerable<string>)request.Form.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit); } [Fact] public void Should_limit_the_amount_of_querystring_fields_parsed() { // Given var sb = new StringBuilder(); for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++) { if (i > 0) { sb.Append('&'); } sb.AppendFormat("Field{0}=Value{0}", i); } var memory = CreateRequestStream(); // When var request = new Request("GET", "/", new Dictionary<string, IEnumerable<string>>(), memory, "http", sb.ToString()); // Then ((IEnumerable<string>)request.Query.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit); } [Fact] public void Should_change_empty_path_to_root() { var request = new Request("GET", "", "http"); request.Path.ShouldEqual("/"); } private static RequestStream CreateRequestStream() { return CreateRequestStream(new MemoryStream()); } private static RequestStream CreateRequestStream(Stream stream) { return RequestStream.FromStream(stream); } private static byte[] BuildMultipartFormValues(params KeyValuePair<string, string>[] values) { var boundaryBuilder = new StringBuilder(); foreach (var pair in values) { boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("--"); boundaryBuilder.Append("----NancyFormBoundary"); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", pair.Key); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append(pair.Value); } boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("------NancyFormBoundary--"); var bytes = Encoding.ASCII.GetBytes(boundaryBuilder.ToString()); return bytes; } private static byte[] BuildMultipartFormValues(Dictionary<string, string> formValues) { var pairs = formValues.Keys.Select(key => new KeyValuePair<string, string>(key, formValues[key])); return BuildMultipartFormValues(pairs.ToArray()); } private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues) { var boundaryBuilder = new StringBuilder(); foreach (var key in formValues.Keys) { boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("--"); boundaryBuilder.Append("----NancyFormBoundary"); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{1}\"; filename=\"{0}\"", key, formValues[key].Item3); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.AppendFormat("Content-Type: {0}", formValues[key].Item1); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append(formValues[key].Item2); } boundaryBuilder.Append('\r'); boundaryBuilder.Append('\n'); boundaryBuilder.Append("------NancyFormBoundary--"); var bytes = Encoding.ASCII.GetBytes(boundaryBuilder.ToString()); return bytes; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Ports.Tests { public class SerialStream_ReadTimeout_Property : PortsTest { // The default number of bytes to write with when testing timeout with Read(byte[], int, int) private const int DEFAULT_READ_BYTE_ARRAY_SIZE = 8; // The amount of time to wait when expecting an long timeout private const int DEFAULT_WAIT_LONG_TIMEOUT = 250; // The maximum acceptable time allowed when a read method should timeout immediately when it is called for the first time private const int MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT = 1000; // The maximum acceptable percentage difference allowed when a read method is called for the first time private const double MAX_ACCEPTABLE_WARMUP_PERCENTAGE_DIFFERENCE = .5; // The maximum acceptable percentage difference allowed private const double MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE = .15; private const int SUCCESSIVE_READTIMEOUT_SOMEDATA = 950; private const int NUM_TRYS = 5; private delegate void ReadMethodDelegate(Stream stream); #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_DefaultValue() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; Debug.WriteLine("Verifying the default value of ReadTimeout"); Assert.Equal(-1, stream.ReadTimeout); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_AfterClose() { Debug.WriteLine("Verifying setting ReadTimeout after the SerialPort was closed"); VerifyException(2048, null, typeof(ObjectDisposedException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_Int32MinValue() { Debug.WriteLine("Verifying Int32.MinValue ReadTimeout"); VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_NEG2() { Debug.WriteLine("Verifying -2 ReadTimeout"); VerifyException(-2, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Default_Read_byte_int_int() { Debug.WriteLine("Verifying default ReadTimeout with Read(byte[] buffer, int offset, int count)"); VerifyDefaultTimeout(Read_byte_int_int); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Default_ReadByte() { Debug.WriteLine("Verifying default ReadTimeout with ReadByte()"); VerifyDefaultTimeout(ReadByte); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Infinite_Read_byte_int_int() { Debug.WriteLine("Verifying infinite ReadTimeout with Read(byte[] buffer, int offset, int count)"); VerifyLongTimeout(Read_byte_int_int, -1); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Infinite_ReadByte() { Debug.WriteLine("Verifying infinite ReadTimeout with ReadByte()"); VerifyLongTimeout(ReadByte, -1); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Int32MaxValue_Read_byte_int_int() { Debug.WriteLine("Verifying Int32.MaxValue ReadTimeout with Read(byte[] buffer, int offset, int count)"); VerifyLongTimeout(Read_byte_int_int, int.MaxValue - 1); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadTimeout_Int32MaxValue_ReadByte() { Debug.WriteLine("Verifying Int32.MaxValue ReadTimeout with ReadByte()"); VerifyLongTimeout(ReadByte, int.MaxValue - 1); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_750_Read_byte_int_int() { Debug.WriteLine("Verifying 750 ReadTimeout with Read(byte[] buffer, int offset, int count)"); VerifyTimeout(Read_byte_int_int, 750); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_750_ReadByte() { Debug.WriteLine("Verifying 750 ReadTimeout with ReadByte()"); VerifyTimeout(ReadByte, 750); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData_Read_byte_int_int() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; stream.ReadTimeout = 850; Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to Read(byte[], int, int) and no data", stream.ReadTimeout); try { stream.Read(new byte[DEFAULT_READ_BYTE_ARRAY_SIZE], 0, DEFAULT_READ_BYTE_ARRAY_SIZE); Assert.True(false, "Err_1707ahbap!!!: Read did not throw TimeouException when it timed out"); } catch (TimeoutException) { } VerifyTimeout(Read_byte_int_int, stream); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData_Read_byte_int_int() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var t = new Task(WriteToCom1); com1.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = SUCCESSIVE_READTIMEOUT_SOMEDATA; Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to Read(byte[], int, int) and some data being received in the first call", stream.ReadTimeout); // Call WriteToCom1 asynchronously this will write to com1 some time before the following call // to a read method times out t.Start(); try { stream.Read(new byte[DEFAULT_READ_BYTE_ARRAY_SIZE], 0, DEFAULT_READ_BYTE_ARRAY_SIZE); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); // Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(Read_byte_int_int, stream); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData_ReadByte() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; stream.ReadTimeout = 850; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to ReadByte() and no data", stream.ReadTimeout); Assert.Throws<TimeoutException>(() => stream.ReadByte()); VerifyTimeout(ReadByte, stream); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData_ReadByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var t = new Task(WriteToCom1); com1.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = SUCCESSIVE_READTIMEOUT_SOMEDATA; Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to ReadByte() and some data being received in the first call", stream.ReadTimeout); // Call WriteToCom1 asynchronously this will write to com1 some time before the following call // to a read method times out t.Start(); try { stream.ReadByte(); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); // Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(ReadByte, stream); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_0_Read_byte_int_int() { Debug.WriteLine("Verifying 0 ReadTimeout with Read(byte[] buffer, int offset, int count)"); Verify0Timeout(Read_byte_int_int); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void ReadTimeout_0_ReadByte() { Debug.WriteLine("Verifying 0 ReadTimeout with ReadByte()"); Verify0Timeout(ReadByte); } [ConditionalFact(nameof(HasNullModem))] public void ReadTimeout_0_1ByteAvailable_Read_byte_int_int() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rcvBytes = new byte[128]; int bytesRead; Debug.WriteLine( "Verifying 0 ReadTimeout with Read(byte[] buffer, int offset, int count) and one byte available"); com1.Open(); com2.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = 0; com2.Write(new byte[] { 50 }, 0, 1); TCSupport.WaitForReadBufferToLoad(com1, 1); Assert.True(1 == (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length)), string.Format("Err_31597ahpba, Expected to Read to return 1 actual={0}", bytesRead)); Assert.True(50 == rcvBytes[0], string.Format("Err_778946ahba, Expected to read 50 actual={0}", rcvBytes[0])); } } [ConditionalFact(nameof(HasNullModem))] public void ReadTimeout_0_1ByteAvailable_ReadByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { int byteRead; Debug.WriteLine("Verifying 0 ReadTimeout with ReadByte() and one byte available"); com1.Open(); com2.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = 0; com2.Write(new byte[] { 50 }, 0, 1); TCSupport.WaitForReadBufferToLoad(com1, 1); Assert.True(50 == (byteRead = com1.ReadByte()), string.Format("Err_05949aypa, Expected to Read to return 50 actual={0}", byteRead)); } } private void WriteToCom1() { using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var xmitBuffer = new byte[1]; int sleepPeriod = SUCCESSIVE_READTIMEOUT_SOMEDATA / 2; // Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } #endregion #region Verification for Test Cases private void VerifyDefaultTimeout(ReadMethodDelegate readMethod) { using (var com1 = TCSupport.InitFirstSerialPort()) using (var com2 = TCSupport.InitSecondSerialPort(com1)) { com1.Open(); if (!com2.IsOpen) com2.Open(); com1.BaseStream.WriteTimeout = 1; Assert.Equal(-1, com1.BaseStream.ReadTimeout); VerifyLongTimeout(readMethod, com1, com2); } } private void VerifyLongTimeout(ReadMethodDelegate readMethod, int readTimeout) { using (var com1 = TCSupport.InitFirstSerialPort()) using (var com2 = TCSupport.InitSecondSerialPort(com1)) { com1.Open(); if (!com2.IsOpen) com2.Open(); com1.BaseStream.WriteTimeout = 1; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.ReadTimeout = readTimeout; Assert.True(readTimeout == com1.BaseStream.ReadTimeout, string.Format("Err_7071ahpsb!!! Expected ReadTimeout to be {0} actual {1}", readTimeout, com1.BaseStream.ReadTimeout)); VerifyLongTimeout(readMethod, com1, com2); } } private void VerifyLongTimeout(ReadMethodDelegate readMethod, SerialPort com1, SerialPort com2) { var readThread = new ReadDelegateThread(com1.BaseStream, readMethod); var t = new Task(readThread.CallRead); t.Start(); Thread.Sleep(DEFAULT_WAIT_LONG_TIMEOUT); Assert.False(t.IsCompleted, string.Format("Err_17071ahpa!!! {0} terminated with a long timeout of {1}ms", readMethod.Method.Name, com1.BaseStream.ReadTimeout)); com2.Write(new byte[8], 0, 8); TCSupport.WaitForTaskCompletion(t); } private void VerifyTimeout(ReadMethodDelegate readMethod, int readTimeout) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com1.Open(); com1.BaseStream.WriteTimeout = 1; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.ReadTimeout = readTimeout; Assert.True(readTimeout == com1.BaseStream.ReadTimeout, string.Format("Err_236897ahpbm!!! Expected ReadTimeout to be {0} actual {1}", readTimeout, com1.BaseStream.ReadTimeout)); VerifyTimeout(readMethod, com1.BaseStream); } } private void VerifyTimeout(ReadMethodDelegate readMethod, Stream stream) { var timer = new Stopwatch(); int expectedTime = stream.ReadTimeout; int actualTime; double percentageDifference; // Warmup the read method. When called for the first time the read method seems to take much longer then subsequent calls timer.Start(); try { readMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime = (int)timer.ElapsedMilliseconds; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference Assert.True(percentageDifference <= MAX_ACCEPTABLE_WARMUP_PERCENTAGE_DIFFERENCE, string.Format("Err_88558amuph!!!: The read method timedout in {0} expected {1} percentage difference: {2} when called for the first time", actualTime, expectedTime, percentageDifference)); actualTime = 0; timer.Reset(); // Perform the actual test verifying that the read method times out in approximately ReadTime milliseconds Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { readMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference Assert.True(percentageDifference <= MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE, string.Format("Err_56485ahpbz!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference)); } private void Verify0Timeout(ReadMethodDelegate readMethod) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com1.Open(); com1.BaseStream.WriteTimeout = 1; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.ReadTimeout = 0; Assert.True(0 == com1.BaseStream.ReadTimeout, string.Format("Err_72072ahps!!! Expected ReadTimeout to be {0} actual {1}", 0, com1.BaseStream.ReadTimeout)); Verify0Timeout(readMethod, com1.BaseStream); } } private void Verify0Timeout(ReadMethodDelegate readMethod, Stream stream) { var timer = new Stopwatch(); int actualTime; // Warmup the read method. When called for the first time the read method seems to take much longer then subsequent calls timer.Start(); try { readMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime = (int)timer.ElapsedMilliseconds; // Verify that the time the method took to timeout is less then the maximum acceptable time Assert.True(actualTime <= MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT, string.Format("Err_277a0ahpsb!!!: With a timeout of 0 the read method timedout in {0} expected something less then {1} when called for the first time", actualTime, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT)); actualTime = 0; timer.Reset(); // Perform the actual test verifying that the read method times out in approximately ReadTime milliseconds Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { readMethod(stream); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; // Verify that the time the method took to timeout is less then the maximum acceptable time Assert.True(actualTime <= MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT, string.Format("Err_112389ahbp!!!: With a timeout of 0 the read method timedout in {0} expected something less then {1}", actualTime, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT)); } private void VerifyException(int readTimeout, Type expectedException) { VerifyException(readTimeout, expectedException, expectedException); } private void VerifyException(int readTimeout, Type expectedExceptionAfterOpen, Type expectedExceptionAfterClose) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { com.Open(); Stream stream = com.BaseStream; VerifyException(stream, readTimeout, expectedExceptionAfterOpen); com.Close(); VerifyException(stream, readTimeout, expectedExceptionAfterClose); } } private void VerifyException(Stream stream, int readTimeout, Type expectedException) { int origReadTimeout = stream.ReadTimeout; if (expectedException != null) { Assert.Throws(expectedException, () => stream.ReadTimeout = readTimeout); Assert.Equal(origReadTimeout, stream.ReadTimeout); } else { stream.ReadTimeout = readTimeout; Assert.Equal(readTimeout, stream.ReadTimeout); } } private void Read_byte_int_int(Stream stream) { stream.Read(new byte[DEFAULT_READ_BYTE_ARRAY_SIZE], 0, DEFAULT_READ_BYTE_ARRAY_SIZE); } private void ReadByte(Stream stream) { stream.ReadByte(); } private class ReadDelegateThread { public ReadDelegateThread(Stream stream, ReadMethodDelegate readMethod) { _stream = stream; _readMethod = readMethod; } public void CallRead() { _readMethod(_stream); } private readonly ReadMethodDelegate _readMethod; private readonly Stream _stream; } #endregion } }
using System.Collections.Generic; using EliteTrader.EliteOcr; using EliteTrader.EliteOcr.Enums; namespace ThruddClient { public class AdminSearchResultItem { public int StationId { get; set; } public string Station { get; set; } public string System { get; set; } public int SystemId { get; set; } } public class SystemData { public int Id { get; set; } public string Name { get; set; } public string Economy { get; set; } public int GovernmentId { get; set; } public string GovernmentName { get; set; } public int AllegianceId { get; set; } public string AllegianceName { get; set; } public decimal X { get; set; } public decimal Y { get; set; } public decimal Z { get; set; } } public class SystemStationsData { public int SystemId { get; set; } public int MarketStationId { get; set; } public List<StationData> Stations { get; set; } } public class StationData { public int Id { get; set; } public string Name { get; set; } public int SystemId { get; set; } public bool HasBlackMarket { get; set; } public bool HasMarket { get; set; } public bool HasOutfitting { get; set; } public bool HasShipyard { get; set; } public bool HasRepairs { get; set; } public int AllegianceId { get; set; } public string Allegiance { get; set; } public int EconomyId { get; set; } public int? SecondaryEconomyId { get; set; } public string Economy { get; set; } public string SecondaryEconomy { get; set; } public int GovernmentId { get; set; } public string Government { get; set; } public int DistanceFromJumpIn { get; set; } public int StationTypeId { get; set; } public string StationTypeName { get; set; } public int CopyMarketFromStationId { get; set; } public EnumAllegiance AllegianceEnum { get { return (EnumAllegiance) AllegianceId; } } public EnumStationEconomy EconomyEnum { get { return (EnumStationEconomy)EconomyId; } } public EnumStationEconomy? SecondaryEconomyEnum { get { return SecondaryEconomyId != null ? (EnumStationEconomy?)SecondaryEconomyId : null; } } public EnumGovernment GovernmentEnum { get { return (EnumGovernment)GovernmentId; } } public EnumStationType StationTypeEnum { get { return (EnumStationType)StationTypeId; } } } public class StationCommoditiesResult { public List<StationCommoditiesData> StationCommodities { get; set; } } public class StationCommoditiesData { public string TimeSince { get; set; } public string CommodityName { get; set; } public string StationName { get; set; } public int Id { get; set; } //Use this Id to update the commodity prices (StationCommodityId) public int StationId { get; set; } public string Station { get; set; } public int CommodityId { get; set; } public string Commodity { get; set; } public int Buy { get; set; } public int Sell { get; set; } public string LastUpdate { get; set; } public string UpdatedBy { get; set; } public int Version { get; set; } public EnumCommodityItemName CommodityEnum { get { return (EnumCommodityItemName)CommodityId; } } } public enum EnumCommodityAction { Sell = 1, Buy = 2 } public class UpdateCommodityResponse { public int StationCommodityId { get; set; } public string Action { get; set; } public int Value { get; set; } public string LastUpdate { get; set; } public string UpdatedBy { get; set; } public RepResultData RepResult { get; set; } } public class RepResultData { public string CommanderName { get; set; } public int Reputation { get; set; } public int ReputationNeeded { get; set; } public string Title { get; set; } public bool RankUp { get; set; } public string Badge { get; set; } } public enum EnumPadSize { Small, Medium, Large } public class FindTradesInfo { public string SearchRange { get; private set; } public string SystemName { get; private set; } public string MinProfitPerTon { get; private set; } public EnumPadSize PadSize { get; private set; } public FindTradesInfo(int searchRange, string systemName, int minProfitPerTon, EnumPadSize padSize) { SearchRange = searchRange.ToString(); SystemName = systemName; MinProfitPerTon = minProfitPerTon.ToString(); PadSize = padSize; } } public class GetSelectListsResult { public List<SelectedListItem> Allegiances { get; set; } public List<SelectedListItem> Economies { get; set; } public List<SelectedListItem> Governments { get; set; } //Systems public List<SelectedListItem> StationTypes { get; set; } public List<CommodityCategory> CommodityCategories { get; set; } } public class SelectedListItem { public bool Disables { get; set; } public string Group { get; set; } public bool Selected { get; set; } public string Text { get; set; } public string Value { get; set; } } public class CommodityCategory { public string Text { get; set; } public int Value { get; set; } public List<CommodityItem> Commodities { get; set; } } public class CommodityItem { public string Text { get; set; } public int Value { get; set; } } /* * POST http://www.elitetradingtool.co.uk/Admin/AddEditStationCommodity HTTP/1.1 Host: www.elitetradingtool.co.uk Connection: keep-alive Content-Length: 83 Origin: http://www.elitetradingtool.co.uk X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 Content-Type: application/json Referer: http://www.elitetradingtool.co.uk/Admin/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8,da;q=0.6,nb;q=0.4,sv;q=0.2 Cookie: __RequestVerificationToken=_PRcL13C7hVPAT0CWWimiF6EzWOo9BB_yhXcrOBvy0CU3gwcF7vAMs7YpvGqk-Dst3Us_G-5K7mLqxO5kkn-AlMNoZBoSvWYFzEj9u-l7y41; .AspNet.ApplicationCookie=F8isL-y4eArX8KXxWcFgt0nTJeBdRSAFctFiKYvfa2MMsz-5vzJp5I1k-LOtfFsE-pjX1nhT8yRNjBLNdh4R9EU0ZK0eNoEgK02j3gbMf_yT8NWDIyU0kXcz82-Bub88bJX0m3EO1hacwFX0vPH-RT1vWMarXHRmkxLiSnSIEWZ0t-nSrMsPb9de3_vd4NE1Gg-oZRRVL6Eu1VrvYA9SOMeEJ2YMRODSHKLxwEaGZx6BxS5EdIq1xcR9VxAwnNeOMmdKOTlBjRuZoeTFL8ACPOe0raBlhxLbBDYY2OcmVPR2hmFuj5SdNr0gxFWHrHAKlyanSK-W1RMyt8EDV80HOm6kP8E-vSztxt70IOqQ1JKz6GnjD0puTjkQdGh586TKkoFNYxAREjBmrsIXWrh8XMyC_dEpzhbtPifSGjnuNArf0kYPd7f7mrxQMmo4Wl07206lN-JODTpa3CstB9RCE8nmeZIzERrOvUHiKHETSZWZDGsSdg7cS9svAqYXs9U3UtKsWJxLjogWWsU856m214yn5FFbAnf4FfEUyebyhYhAy7TBL3rzIQfbiuj8CJAQuC19U2dSdFbLFlMslTrIFJpVHEYoilj_8vYmBh8Iawk; _gat=1; _ga=GA1.3.139030831.1419415951 {"Id":0,"StationId":1078,"CommodityId":"2","Buy":"0","Sell":"366","CategoryId":"1"} */ /* HTTP/1.1 302 Found Date: Fri, 09 Jan 2015 04:21:27 GMT Server: Microsoft-IIS/8.5 Cache-Control: private, s-maxage=0 Content-Type: text/html; charset=utf-8 Location: /Admin/StationCommodities/1078?categoryId=1 X-AspNetMvc-Version: 5.2 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 160 Connection: close <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="/Admin/StationCommodities/1078?categoryId=1">here</a>.</h2> </body></html> */ /* * POST http://www.elitetradingtool.co.uk/Admin/DeleteStationCommodity HTTP/1.1 Host: www.elitetradingtool.co.uk Connection: keep-alive Content-Length: 30 Origin: http://www.elitetradingtool.co.uk X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 Content-Type: application/json Referer: http://www.elitetradingtool.co.uk/Admin/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8,da;q=0.6,nb;q=0.4,sv;q=0.2 Cookie: __RequestVerificationToken=_PRcL13C7hVPAT0CWWimiF6EzWOo9BB_yhXcrOBvy0CU3gwcF7vAMs7YpvGqk-Dst3Us_G-5K7mLqxO5kkn-AlMNoZBoSvWYFzEj9u-l7y41; .AspNet.ApplicationCookie=F8isL-y4eArX8KXxWcFgt0nTJeBdRSAFctFiKYvfa2MMsz-5vzJp5I1k-LOtfFsE-pjX1nhT8yRNjBLNdh4R9EU0ZK0eNoEgK02j3gbMf_yT8NWDIyU0kXcz82-Bub88bJX0m3EO1hacwFX0vPH-RT1vWMarXHRmkxLiSnSIEWZ0t-nSrMsPb9de3_vd4NE1Gg-oZRRVL6Eu1VrvYA9SOMeEJ2YMRODSHKLxwEaGZx6BxS5EdIq1xcR9VxAwnNeOMmdKOTlBjRuZoeTFL8ACPOe0raBlhxLbBDYY2OcmVPR2hmFuj5SdNr0gxFWHrHAKlyanSK-W1RMyt8EDV80HOm6kP8E-vSztxt70IOqQ1JKz6GnjD0puTjkQdGh586TKkoFNYxAREjBmrsIXWrh8XMyC_dEpzhbtPifSGjnuNArf0kYPd7f7mrxQMmo4Wl07206lN-JODTpa3CstB9RCE8nmeZIzERrOvUHiKHETSZWZDGsSdg7cS9svAqYXs9U3UtKsWJxLjogWWsU856m214yn5FFbAnf4FfEUyebyhYhAy7TBL3rzIQfbiuj8CJAQuC19U2dSdFbLFlMslTrIFJpVHEYoilj_8vYmBh8Iawk; _gat=1; _ga=GA1.3.139030831.1419415951 {"id":364616,"categoryId":"1"} */ /* * HTTP/1.1 302 Found Date: Fri, 09 Jan 2015 04:23:00 GMT Server: Microsoft-IIS/8.5 Cache-Control: private, s-maxage=0 Content-Type: text/html; charset=utf-8 Location: /Admin/StationCommodities/1078?categoryId=1 X-AspNetMvc-Version: 5.2 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 160 Connection: close <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="/Admin/StationCommodities/1078?categoryId=1">here</a>.</h2> </body></html> */ }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A secret /// First published in XenServer 5.6. /// </summary> public partial class Secret : XenObject<Secret> { #region Constructors public Secret() { } public Secret(string uuid, string value, Dictionary<string, string> other_config) { this.uuid = uuid; this.value = value; this.other_config = other_config; } /// <summary> /// Creates a new Secret from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Secret(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Secret from a Proxy_Secret. /// </summary> /// <param name="proxy"></param> public Secret(Proxy_Secret proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Secret. /// </summary> public override void UpdateFrom(Secret record) { uuid = record.uuid; value = record.value; other_config = record.other_config; } internal void UpdateFrom(Proxy_Secret proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; value = proxy.value == null ? null : proxy.value; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Secret /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("value")) value = Marshalling.ParseString(table, "value"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public Proxy_Secret ToProxy() { Proxy_Secret result_ = new Proxy_Secret(); result_.uuid = uuid ?? ""; result_.value = value ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } public bool DeepEquals(Secret other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._value, other._value) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Secret server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { if (!Helper.AreEqual2(_value, server._value)) { Secret.set_value(session, opaqueRef, _value); } if (!Helper.AreEqual2(_other_config, server._other_config)) { Secret.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Secret get_record(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_record(session.opaque_ref, _secret); else return new Secret(session.XmlRpcProxy.secret_get_record(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Get a reference to the secret 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<Secret> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Secret>.Create(session.XmlRpcProxy.secret_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Secret> create(Session session, Secret _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_create(session.opaque_ref, _record); else return XenRef<Secret>.Create(session.XmlRpcProxy.secret_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Secret _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_secret_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.XmlRpcProxy.async_secret_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static void destroy(Session session, string _secret) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_destroy(session.opaque_ref, _secret); else session.XmlRpcProxy.secret_destroy(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static XenRef<Task> async_destroy(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_secret_destroy(session.opaque_ref, _secret); else return XenRef<Task>.Create(session.XmlRpcProxy.async_secret_destroy(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Get the uuid field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_uuid(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_uuid(session.opaque_ref, _secret); else return session.XmlRpcProxy.secret_get_uuid(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Get the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_value(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_value(session.opaque_ref, _secret); else return session.XmlRpcProxy.secret_get_value(session.opaque_ref, _secret ?? "").parse(); } /// <summary> /// Get the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Dictionary<string, string> get_other_config(Session session, string _secret) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_other_config(session.opaque_ref, _secret); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.secret_get_other_config(session.opaque_ref, _secret ?? "").parse()); } /// <summary> /// Set the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_value">New value to set</param> public static void set_value(Session session, string _secret, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_set_value(session.opaque_ref, _secret, _value); else session.XmlRpcProxy.secret_set_value(session.opaque_ref, _secret ?? "", _value ?? "").parse(); } /// <summary> /// Set the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _secret, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_set_other_config(session.opaque_ref, _secret, _other_config); else session.XmlRpcProxy.secret_set_other_config(session.opaque_ref, _secret ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _secret, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_add_to_other_config(session.opaque_ref, _secret, _key, _value); else session.XmlRpcProxy.secret_add_to_other_config(session.opaque_ref, _secret ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given secret. If the key is not in that Map, then do nothing. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _secret, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.secret_remove_from_other_config(session.opaque_ref, _secret, _key); else session.XmlRpcProxy.secret_remove_from_other_config(session.opaque_ref, _secret ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the secrets known to the system. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Secret>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_all(session.opaque_ref); else return XenRef<Secret>.Create(session.XmlRpcProxy.secret_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the secret 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<Secret>, Secret> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.secret_get_all_records(session.opaque_ref); else return XenRef<Secret>.Create<Proxy_Secret>(session.XmlRpcProxy.secret_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the secret /// </summary> public virtual string value { get { return _value; } set { if (!Helper.AreEqual(value, _value)) { _value = value; NotifyPropertyChanged("value"); } } } private string _value = ""; /// <summary> /// other_config /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Runtime.ExceptionServices; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using MICore; using System.Globalization; using Microsoft.Win32; namespace Microsoft.MIDebugEngine { // AD7Engine is the primary entrypoint object for the sample engine. // // It implements: // // IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session, // from creating breakpoints to setting and clearing exceptions. // // IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs. // // IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each // process only contains one program, it is implemented on the engine. // // IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee. [ComVisible(true)] [Guid("0fc2f352-2fc1-4f80-8736-51cd1ab28f16")] sealed public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2, IDebugMemoryBytes2, IDebugEngine110 { // used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load. private EngineCallback _engineCallback; // The sample debug engine is split into two parts: a managed front-end and a mixed-mode back end. DebuggedProcess is the primary // object in the back-end. AD7Engine holds a reference to it. private DebuggedProcess _debuggedProcess; // This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging // api requires thread affinity to several operations. private WorkerThread _pollThread; // This object manages breakpoints in the sample engine. private BreakpointManager _breakpointManager; // A unique identifier for the program being debugged. private Guid _ad7ProgramId; private string _registryRoot; private IDebugSettingsCallback110 _settingsCallback; public AD7Engine() { //This call is to initialize the global service provider while we are still on the main thread. //Do not remove this this, even though the return value goes unused. var globalProvider = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider; _breakpointManager = new BreakpointManager(this); } ~AD7Engine() { if (_pollThread != null) { _pollThread.Close(); } } internal EngineCallback Callback { get { return _engineCallback; } } internal DebuggedProcess DebuggedProcess { get { return _debuggedProcess; } } internal uint CurrentRadix() { uint radix; if (_settingsCallback != null && _settingsCallback.GetDisplayRadix(out radix) == Constants.S_OK) { if (radix != _debuggedProcess.MICommandFactory.Radix) { _debuggedProcess.WorkerThread.RunOperation(async () => { await _debuggedProcess.MICommandFactory.SetRadix(radix); }); } } return _debuggedProcess.MICommandFactory.Radix; } internal bool ProgramCreateEventSent { get; private set; } public string GetAddressDescription(ulong ip) { return EngineUtils.GetAddressDescription(_debuggedProcess, ip); } public object GetMetric(string metric) { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(_registryRoot + @"\AD7Metrics\Engine\" + EngineConstants.EngineId.ToUpper(CultureInfo.InvariantCulture))) { if (key == null) { return null; } return key.GetValue(metric); } } #region IDebugEngine2 Members // Attach the debug engine to a program. int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) { Debug.Assert(_ad7ProgramId == Guid.Empty); if (celtPrograms != 1) { Debug.Fail("SampleEngine only expects to see one program in a process"); throw new ArgumentException(); } try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(rgpPrograms[0]); EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out _ad7ProgramId)); // Attach can either be called to attach to a new process, or to complete an attach // to a launched process if (_pollThread == null) { // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); _engineCallback = new EngineCallback(this, ad7Callback); // Complete the win32 attach on the poll thread _pollThread.RunOperation(new Operation(delegate { throw new NotImplementedException(); })); _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; } else { if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { Debug.Fail("Asked to attach to a process while we are debugging"); return Constants.E_FAIL; } } AD7EngineCreateEvent.Send(this); AD7ProgramCreateEvent.Send(this); this.ProgramCreateEventSent = true; return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run. // This is normally called in response to the user clicking on the pause button in the debugger. // When the break is complete, an AsyncBreakComplete event will be sent back to the debugger. int IDebugEngine2.CauseBreak() { return ((IDebugProgram2)this).CauseBreak(); } // Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM, // was received and processed. The only event the sample engine sends in this fashion is Program Destroy. // It responds to that event by shutting down the engine. int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject) { try { if (eventObject is AD7ProgramCreateEvent) { Exception exception = null; try { // At this point breakpoints and exception settings have been sent down, so we can resume the target _pollThread.RunOperation(() => { return _debuggedProcess.ResumeFromLaunch(); }); } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } if (exception != null) { // If something goes wrong, report the error and then stop debugging. The SDM will drop errors // from ContinueFromSynchronousEvent, so we want to deal with them ourself. SendStartDebuggingError(exception); _debuggedProcess.Terminate(); } return Constants.S_OK; } else if (eventObject is AD7ProgramDestroyEvent) { Dispose(); } else { Debug.Fail("Unknown syncronious event"); } } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } private void Dispose() { WorkerThread pollThread = _pollThread; DebuggedProcess debuggedProcess = _debuggedProcess; _engineCallback = null; _debuggedProcess = null; _pollThread = null; _ad7ProgramId = Guid.Empty; debuggedProcess?.Close(); pollThread?.Close(); } // Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to // a location in the debuggee. int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) { Debug.Assert(_breakpointManager != null); ppPendingBP = null; try { _breakpointManager.CreatePendingBreakpoint(pBPRequest, out ppPendingBP); } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } // Informs a DE that the program specified has been atypically terminated and that the DE should // clean up all references to the program and send a program destroy event. int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) { // Tell the SDM that the engine knows that the program is exiting, and that the // engine will send a program destroy. We do this because the Win32 debug api will always // tell us that the process exited, and otherwise we have a race condition. return (AD7_HRESULT.E_PROGRAM_DESTROY_PENDING); } // Gets the GUID of the DE. int IDebugEngine2.GetEngineId(out Guid guidEngine) { guidEngine = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // Removes the list of exceptions the IDE has set for a particular run-time architecture or language. int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) { return Constants.S_OK; } // Removes the specified exception so it is no longer handled by the debug engine. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) { return Constants.S_OK; } // Specifies how the DE should handle a given exception. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) { return Constants.S_OK; } // Sets the locale of the DE. // This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that // strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented. int IDebugEngine2.SetLocale(ushort wLangID) { return Constants.S_OK; } // A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality. // This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric. int IDebugEngine2.SetMetric(string pszMetric, object varValue) { // The sample engine does not need to understand any metric settings. return Constants.S_OK; } // Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored // This allows the debugger to tell the engine where that location is. int IDebugEngine2.SetRegistryRoot(string registryRoot) { _registryRoot = registryRoot; Logger.EnsureInitialized(registryRoot); return Constants.S_OK; } #endregion #region IDebugEngineLaunch2 Members // Determines if a process can be terminated. int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_OK; } else { return Constants.S_FALSE; } } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Launches a process by means of the debug engine. // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language), // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state. int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process) { Debug.Assert(_pollThread == null); Debug.Assert(_engineCallback == null); Debug.Assert(_debuggedProcess == null); Debug.Assert(_ad7ProgramId == Guid.Empty); process = null; _engineCallback = new EngineCallback(this, ad7Callback); Exception exception; try { // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop LaunchOptions launchOptions = LaunchOptions.GetInstance(_registryRoot, exe, args, dir, options, _engineCallback); // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); var cancellationTokenSource = new CancellationTokenSource(); using (cancellationTokenSource) { _pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (MICore.WaitLoop waitLoop) => { try { _debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this); } finally { // If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher, // otherwise the DebuggedProcess object takes ownership. if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null) { launchOptions.DeviceAppLauncher.Dispose(); } } _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; return _debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token); }); } EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process)); return Constants.S_OK; } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then // return E_ABORT. Logger.Flush(); SendStartDebuggingError(exception); Dispose(); return Constants.E_ABORT; } private void SendStartDebuggingError(Exception exception) { if (exception is OperationCanceledException) { return; // don't show a message in this case } string description = EngineUtils.GetExceptionDescription(exception); string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description); var initializationException = exception as MIDebuggerInitializeFailedException; if (initializationException != null) { string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n"; // NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event VsOutputWindow.WriteLaunchError(outputMessage); } _engineCallback.OnErrorImmediate(message); } // Resume a process launched by IDebugEngineLaunch2.LaunchSuspended int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); Debug.Assert(_ad7ProgramId == Guid.Empty); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } // Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach // which will complete the hookup with AD7 IDebugPort2 port; EngineUtils.RequireOk(process.GetPort(out port)); IDebugDefaultPort2 defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 portNotify; EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify)); EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_debuggedProcess.Id))); if (_ad7ProgramId == Guid.Empty) { Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called"); return Constants.E_FAIL; } // NOTE: We wait for the program create event to be continued before we really resume the process return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // This function is used to terminate a process that the SampleEngine launched // The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method. int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } _pollThread.RunOperation(() => _debuggedProcess.CmdTerminate()); _debuggedProcess.Terminate(); return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } #endregion #region IDebugProgram2 Members // Determines if a debug engine (DE) can detach from the program. public int CanDetach() { // The sample engine always supports detach return Constants.S_OK; } // The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering // breakmode. public int CauseBreak() { _pollThread.RunOperation(() => _debuggedProcess.CmdBreak()); return Constants.S_OK; } // Continue is called from the SDM when it wants execution to continue in the debugee // but have stepping state remain. An example is when a tracepoint is executed, // and the debugger does not want to actually enter break mode. public int Continue(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; _pollThread.RunOperation(new Operation(delegate { _debuggedProcess.Continue(thread.GetDebuggedThread()); })); return Constants.S_OK; } // Detach is called when debugging is stopped and the process was attached to (as opposed to launched) // or when one of the Detach commands are executed in the UI. public int Detach() { _breakpointManager.ClearBoundBreakpoints(); _pollThread.RunOperation(new Operation(delegate { _debuggedProcess.Detach(); })); return Constants.S_OK; } // Enumerates the code contexts for a given position in a source file. public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum) { string documentName; EngineUtils.CheckOk(docPosition.GetFileName(out documentName)); // Get the location in the document TEXT_POSITION[] startPosition = new TEXT_POSITION[1]; TEXT_POSITION[] endPosition = new TEXT_POSITION[1]; EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); List<IDebugCodeContext2> codeContexts = new List<IDebugCodeContext2>(); List<ulong> addresses = null; uint line = startPosition[0].dwLine + 1; _debuggedProcess.WorkerThread.RunOperation(async () => { addresses = await DebuggedProcess.StartAddressesForLine(documentName, line); }); if (addresses != null && addresses.Count > 0) { foreach (var a in addresses) { var codeCxt = new AD7MemoryAddress(this, a, null); TEXT_POSITION pos; pos.dwLine = line; pos.dwColumn = 0; MITextPosition textPosition = new MITextPosition(documentName, pos, pos); codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt)); codeContexts.Add(codeCxt); } if (codeContexts.Count > 0) { ppEnum = new AD7CodeContextEnum(codeContexts.ToArray()); return Constants.S_OK; } } ppEnum = null; return Constants.E_FAIL; } // EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which // function to step into. This is not something that the SampleEngine supports. public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) { pathEnum = null; safetyContext = null; return Constants.E_NOTIMPL; } // EnumModules is called by the debugger when it needs to enumerate the modules in the program. public int EnumModules(out IEnumDebugModules2 ppEnum) { DebuggedModule[] modules = _debuggedProcess.GetModules(); AD7Module[] moduleObjects = new AD7Module[modules.Length]; for (int i = 0; i < modules.Length; i++) { moduleObjects[i] = new AD7Module(modules[i], _debuggedProcess); } ppEnum = new Microsoft.MIDebugEngine.AD7ModuleEnum(moduleObjects); return Constants.S_OK; } // EnumThreads is called by the debugger when it needs to enumerate the threads in the program. public int EnumThreads(out IEnumDebugThreads2 ppEnum) { DebuggedThread[] threads = null; DebuggedProcess.WorkerThread.RunOperation(async () => threads = await DebuggedProcess.ThreadCache.GetThreads()); AD7Thread[] threadObjects = new AD7Thread[threads.Length]; for (int i = 0; i < threads.Length; i++) { Debug.Assert(threads[i].Client != null); threadObjects[i] = (AD7Thread)threads[i].Client; } ppEnum = new Microsoft.MIDebugEngine.AD7ThreadEnum(threadObjects); return Constants.S_OK; } // The properties returned by this method are specific to the program. If the program needs to return more than one property, // then the IDebugProperty2 object returned by this method is a container of additional properties and calling the // IDebugProperty2::EnumChildren method returns a list of all properties. // A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface. // An IDE might display the additional program properties through a generic property browser user interface. // The sample engine does not support this public int GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } // The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context. // The sample engine does not support dissassembly so it returns E_NOTIMPL // In order for this to be called, the Disassembly capability must be set in the registry for this Engine public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) { disassemblyStream = new AD7DisassemblyStream(dwScope, codeContext); return Constants.S_OK; } // This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL public int GetENCUpdate(out object update) { // The sample engine does not participate in managed edit & continue. update = null; return Constants.S_OK; } // Gets the name and identifier of the debug engine (DE) running this program. public int GetEngineInfo(out string engineName, out Guid engineGuid) { engineName = ResourceStrings.EngineName; engineGuid = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory // that was allocated when the program was executed. public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { ppMemoryBytes = this; return Constants.S_OK; } // Gets the name of the program. // The name returned by this method is always a friendly, user-displayable name that describes the program. public int GetName(out string programName) { // The Sample engine uses default transport and doesn't need to customize the name of the program, // so return NULL. programName = null; return Constants.S_OK; } // Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach // or IDebugEngine2::Attach methods. This allows identification of the program across debugger components. public int GetProgramId(out Guid guidProgramId) { Debug.Assert(_ad7ProgramId != Guid.Empty); guidProgramId = _ad7ProgramId; return Constants.S_OK; } public int Step(IDebugThread2 pThread, enum_STEPKIND kind, enum_STEPUNIT unit) { AD7Thread thread = (AD7Thread)pThread; _debuggedProcess.WorkerThread.RunOperation(() => _debuggedProcess.Step(thread.GetDebuggedThread().Id, kind, unit)); return Constants.S_OK; } // Terminates the program. public int Terminate() { // Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate // the process in IDebugEngineLaunch2.TerminateProcess return Constants.S_OK; } // Writes a dump to a file. public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { // The sample debugger does not support creating or reading mini-dumps. return Constants.E_NOTIMPL; } #endregion #region IDebugProgram3 Members // ExecuteOnThread is called when the SDM wants execution to continue and have // stepping state cleared. public int ExecuteOnThread(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; _pollThread.RunOperation(new Operation(delegate { _debuggedProcess.Execute(thread.GetDebuggedThread()); })); return Constants.S_OK; } #endregion #region IDebugEngineProgram2 Members // Stops all threads running in this program. // This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program // is received, this method is called on this program. The implementation of this method should be asynchronous; // that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be // as simple as calling the IDebugProgram2::CauseBreak method on this program. // // The sample engine only supports debugging native applications and therefore only has one program per-process public int Stop() { throw new NotImplementedException(); } // WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging // the same process. The sample engine doesn't cooperate with other engines, so it has nothing // to do here. public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch) { return Constants.S_OK; } // WatchForThreadStep is used to cooperate between two different engines debugging the same process. // The sample engine doesn't cooperate with other engines, so it has nothing to do here. public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame) { return Constants.S_OK; } #endregion #region IDebugMemoryBytes2 Members public int GetSize(out ulong pqwSize) { throw new NotImplementedException(); } public int ReadAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory, out uint pdwRead, ref uint pdwUnreadable) { pdwUnreadable = 0; AD7MemoryAddress addr = (AD7MemoryAddress)pStartContext; uint bytesRead = 0; int hr = Constants.S_OK; DebuggedProcess.WorkerThread.RunOperation(async () => { bytesRead = await DebuggedProcess.ReadProcessMemory(addr.Address, dwCount, rgbMemory); }); if (bytesRead == uint.MaxValue) { bytesRead = 0; } if (bytesRead < dwCount) // copied from Concord { // assume 4096 sized pages: ARM has 4K or 64K pages uint pageSize = 4096; ulong readEnd = addr.Address + bytesRead; ulong nextPageStart = (readEnd + pageSize - 1) / pageSize * pageSize; if (nextPageStart == readEnd) { nextPageStart = readEnd + pageSize; } // if we have crossed a page boundry - Unreadable = bytes till end of page uint maxUnreadable = dwCount - bytesRead; if (addr.Address + dwCount > nextPageStart) { pdwUnreadable = (uint)Math.Min(maxUnreadable, nextPageStart - readEnd); } else { pdwUnreadable = (uint)Math.Min(maxUnreadable, pageSize); } } pdwRead = bytesRead; return hr; } public int WriteAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory) { throw new NotImplementedException(); } #endregion #region IDebugEngine110 public int SetMainThreadSettingsCallback110(IDebugSettingsCallback110 pCallback) { _settingsCallback = pCallback; return Constants.S_OK; } #endregion #region Deprecated interface methods // These methods are not called by the Visual Studio debugger, so they don't need to be implemented int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) { Debug.Fail("This function is not called by the debugger"); programs = null; return Constants.E_NOTIMPL; } public int Attach(IDebugEventCallback2 pCallback) { Debug.Fail("This function is not called by the debugger"); return Constants.E_NOTIMPL; } public int GetProcess(out IDebugProcess2 process) { Debug.Fail("This function is not called by the debugger"); process = null; return Constants.E_NOTIMPL; } public int Execute() { Debug.Fail("This function is not called by the debugger."); return Constants.E_NOTIMPL; } #endregion } }
using System; using System.Drawing; using System.ComponentModel; using System.Linq; using SharpGL.SceneGraph; using SharpGL.SceneGraph.Core; using SharpGL.OpenGLAttributes; using SharpGL.Enumerations; namespace SharpGL.SceneGraph.Effects { /// <summary> /// The OpenGLAttributes are an effect that can set /// any OpenGL attributes. /// </summary> public class OpenGLAttributesEffect : Effect { /// <summary> /// Initializes a new instance of the <see cref="OpenGLAttributesEffect"/> class. /// </summary> public OpenGLAttributesEffect() { Name = "OpenGL Attributes"; } /// <summary> /// Pushes the effect onto the specified parent element. /// </summary> /// <param name="gl">The OpenGL instance.</param> /// <param name="parentElement">The parent element.</param> public override void Push(OpenGL gl, SceneElement parentElement) { // Create a combined mask. AttributeMask attributeFlags = AttributeMask.None; attributeFlags &= accumBufferAttributes.AreAnyAttributesSet() ? accumBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= colorBufferAttributes.AreAnyAttributesSet() ? colorBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= currentAttributes.AreAnyAttributesSet() ? currentAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= depthBufferAttributes.AreAnyAttributesSet() ? depthBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= enableAttributes.AreAnyAttributesSet() ? enableAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= fogAttributes.AreAnyAttributesSet() ? fogAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= lightingAttributes.AreAnyAttributesSet() ? lightingAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= lineAttributes.AreAnyAttributesSet() ? lineAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= pointAttributes.AreAnyAttributesSet() ? pointAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= polygonAttributes.AreAnyAttributesSet() ? polygonAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= evalAttributes.AreAnyAttributesSet() ? evalAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= hintAttributes.AreAnyAttributesSet() ? hintAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= listAttributes.AreAnyAttributesSet() ? listAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= pixelModeAttributes.AreAnyAttributesSet() ? pixelModeAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= polygonStippleAttributes.AreAnyAttributesSet() ? polygonStippleAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= scissorAttributes.AreAnyAttributesSet() ? scissorAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= stencilBufferAttributes.AreAnyAttributesSet() ? stencilBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= textureAttributes.AreAnyAttributesSet() ? textureAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= transformAttributes.AreAnyAttributesSet() ? transformAttributes.AttributeFlags : AttributeMask.None; attributeFlags &= viewportAttributes.AreAnyAttributesSet() ? viewportAttributes.AttributeFlags : AttributeMask.None; // Push the attribute stack. gl.PushAttrib((uint)attributeFlags); // Set the attributes. accumBufferAttributes.SetAttributes(gl); colorBufferAttributes.SetAttributes(gl); currentAttributes.SetAttributes(gl); depthBufferAttributes.SetAttributes(gl); enableAttributes.SetAttributes(gl); fogAttributes.SetAttributes(gl); lightingAttributes.SetAttributes(gl); lineAttributes.SetAttributes(gl); pointAttributes.SetAttributes(gl); polygonAttributes.SetAttributes(gl); evalAttributes.SetAttributes(gl); hintAttributes.SetAttributes(gl); listAttributes.SetAttributes(gl); pixelModeAttributes.SetAttributes(gl); polygonStippleAttributes.SetAttributes(gl); scissorAttributes.SetAttributes(gl); stencilBufferAttributes.SetAttributes(gl); textureAttributes.SetAttributes(gl); transformAttributes.SetAttributes(gl); viewportAttributes.SetAttributes(gl); } /// <summary> /// Pops the effect off the specified parent element. /// </summary> /// <param name="gl">The OpenGL instance.</param> /// <param name="parentElement">The parent element.</param> public override void Pop(OpenGL gl, SceneElement parentElement) { // Pop the attribute stack. gl.PopAttrib(); } private AccumBufferAttributes accumBufferAttributes = new AccumBufferAttributes(); private ColorBufferAttributes colorBufferAttributes = new ColorBufferAttributes(); private CurrentAttributes currentAttributes = new CurrentAttributes(); private DepthBufferAttributes depthBufferAttributes = new DepthBufferAttributes(); private EnableAttributes enableAttributes = new EnableAttributes(); private EvalAttributes evalAttributes = new EvalAttributes(); private FogAttributes fogAttributes = new FogAttributes(); private HintAttributes hintAttributes = new HintAttributes(); private LightingAttributes lightingAttributes = new LightingAttributes(); private LineAttributes lineAttributes = new LineAttributes(); private ListAttributes listAttributes = new ListAttributes(); private PixelModeAttributes pixelModeAttributes = new PixelModeAttributes(); private PointAttributes pointAttributes = new PointAttributes(); private PolygonAttributes polygonAttributes = new PolygonAttributes(); private PolygonStippleAttributes polygonStippleAttributes = new PolygonStippleAttributes(); private ScissorAttributes scissorAttributes = new ScissorAttributes(); private StencilBufferAttributes stencilBufferAttributes = new StencilBufferAttributes(); private TextureAttributes textureAttributes = new TextureAttributes(); private TransformAttributes transformAttributes = new TransformAttributes(); private ViewportAttributes viewportAttributes = new ViewportAttributes(); /// <summary> /// Gets or sets the hint attributes. /// </summary> /// <value> /// The hint attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public HintAttributes HintAttributes { get { return hintAttributes; } set { hintAttributes = value; } } /// <summary> /// Gets or sets the list attributes. /// </summary> /// <value> /// The list attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ListAttributes ListAttributes { get { return listAttributes; } set { listAttributes = value; } } /// <summary> /// Gets or sets the pixel mode attributes. /// </summary> /// <value> /// The pixel mode attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public PixelModeAttributes PixelModeAttributes { get { return pixelModeAttributes; } set { pixelModeAttributes = value; } } /// <summary> /// Gets or sets the polygon stipple attributes. /// </summary> /// <value> /// The polygon stipple attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public PolygonStippleAttributes PolygonStippleAttributes { get { return polygonStippleAttributes; } set { polygonStippleAttributes = value; } } /// <summary> /// Gets or sets the scissor attributes. /// </summary> /// <value> /// The scissor attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ScissorAttributes ScissorAttributes { get { return scissorAttributes; } set { scissorAttributes = value; } } /// <summary> /// Gets or sets the stencil buffer attributes. /// </summary> /// <value> /// The stencil buffer attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public StencilBufferAttributes StencilBufferAttributes { get { return stencilBufferAttributes; } set { stencilBufferAttributes = value; } } /// <summary> /// Gets or sets the texture attributes. /// </summary> /// <value> /// The texture attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public TextureAttributes TextureAttributes { get { return textureAttributes; } set { textureAttributes = value; } } /// <summary> /// Gets or sets the transform attributes. /// </summary> /// <value> /// The transform attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public TransformAttributes TransformAttributes { get { return transformAttributes; } set { transformAttributes = value; } } /// <summary> /// Gets or sets the viewport attributes. /// </summary> /// <value> /// The viewport attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ViewportAttributes ViewportAttributes { get { return viewportAttributes; } set { viewportAttributes = value; } } /// <summary> /// Gets or sets the eval attributes. /// </summary> /// <value> /// The eval attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public EvalAttributes EvalAttributes { get { return evalAttributes; } set { evalAttributes = value; } } /// <summary> /// Gets or sets the accum buffer attributes. /// </summary> /// <value> /// The accum buffer attributes. /// </value> [Description("AccumBuffer attributes"), Category("OpenGL Attributes")] public AccumBufferAttributes AccumBufferAttributes { get { return accumBufferAttributes; } set { accumBufferAttributes = value; } } /// <summary> /// Gets or sets the color buffer attributes. /// </summary> /// <value> /// The color buffer attributes. /// </value> [Description("ColorBuffer attributes"), Category("OpenGL Attributes")] public ColorBufferAttributes ColorBufferAttributes { get { return colorBufferAttributes; } set { colorBufferAttributes = value; } } /// <summary> /// Gets or sets the current attributes. /// </summary> /// <value> /// The current buffer. /// </value> [Description("Current attributes"), Category("OpenGL Attributes")] public CurrentAttributes CurrentAttributes { get { return currentAttributes; } set { currentAttributes = value; } } /// <summary> /// Gets or sets the depth buffer attributes. /// </summary> /// <value> /// The depth buffer attributes. /// </value> [Description("DepthBuffer attributes"), Category("OpenGL Attributes")] public DepthBufferAttributes DepthBufferAttributes { get { return depthBufferAttributes; } set { depthBufferAttributes = value; } } /// <summary> /// Gets or sets the enable attributes. /// </summary> /// <value> /// The enable attributes. /// </value> [Description("Enable attributes"), Category("OpenGL Attributes")] public EnableAttributes EnableAttributes { get { return enableAttributes; } set { enableAttributes = value; } } /// <summary> /// Gets the fog attributes. /// </summary> [Description("Fog attributes"), Category("OpenGL Attributes")] public FogAttributes FogAttributes { get { return fogAttributes; } set { fogAttributes = value; } } /// <summary> /// Gets the lighting attributes. /// </summary> [Description("Lighting attributes"), Category("OpenGL Attributes")] public LightingAttributes LightingAttributes { get { return lightingAttributes; } set { lightingAttributes = value; } } /// <summary> /// Gets the line attributes. /// </summary> [Description("Line attributes"), Category("OpenGL Attributes")] public LineAttributes LineAttributes { get { return lineAttributes; } set { lineAttributes = value; } } /// <summary> /// Gets the point attributes. /// </summary> [Description("Point attributes"), Category("OpenGL Attributes")] public PointAttributes PointAttributes { get { return pointAttributes; } set { pointAttributes = value; } } /// <summary> /// Gets the polygon attributes. /// </summary> [Description("Polygon attributes"), Category("OpenGL Attributes")] public PolygonAttributes PolygonAttributes { get { return polygonAttributes; } set { polygonAttributes = value; } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation.Language; using System.Security; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a bridge class between internal classes and a public interface. It requires this much coupling.")] internal sealed partial class SessionStateInternal { #region tracer /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "SessionState" as the category. /// </summary> [Dbg.TraceSourceAttribute( "SessionState", "SessionState Class")] private static Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("SessionState", "SessionState Class"); #endregion tracer #region Constructor /// <summary> /// Constructor for session state object /// </summary> /// /// <param name="context"> /// The context for the runspace to which this session state object belongs. /// </param> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="context"/> is null. /// </exception> /// internal SessionStateInternal(ExecutionContext context) : this(null, false, context) { } internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context) { if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } ExecutionContext = context; // Create the working directory stack. This // is used for the pushd and popd commands _workingLocationStack = new Dictionary<String, Stack<PathInfo>>(StringComparer.OrdinalIgnoreCase); GlobalScope = new SessionStateScope(null); ModuleScope = GlobalScope; _currentScope = GlobalScope; InitializeSessionStateInternalSpecialVariables(false); // Create the push the global scope on as // the starting script scope. That way, if you dot-source a script // that uses variables qualified by script: it works. GlobalScope.ScriptScope = GlobalScope; if (parent != null) { GlobalScope.Parent = parent.GlobalScope; // Copy the drives and providers from the parent... CopyProviders(parent); // During loading of core modules, providers are not populated. // We set the drive information later if (Providers != null && Providers.Count > 0) { CurrentDrive = parent.CurrentDrive; } // Link it to the global scope... if (linkToGlobal) { GlobalScope = parent.GlobalScope; } } else { _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); } } /// <summary> /// Add any special variables to the session state variable table. This routine /// must be called at construction time or if the variable table is reset. /// </summary> internal void InitializeSessionStateInternalSpecialVariables(bool clearVariablesTable) { if (clearVariablesTable) { // Clear the variable table GlobalScope.Variables.Clear(); // Add in the per-scope default variables. GlobalScope.AddSessionStateScopeDefaultVariables(); } // Set variable $Error PSVariable errorvariable = new PSVariable("Error", new ArrayList(), ScopedItemOptions.Constant); GlobalScope.SetVariable(errorvariable.Name, errorvariable, false, false, this, fastPath: true); // Set variable $PSDefaultParameterValues Collection<Attribute> attributes = new Collection<Attribute>(); attributes.Add(new ArgumentTypeConverterAttribute(typeof(System.Management.Automation.DefaultParameterDictionary))); PSVariable psDefaultParameterValuesVariable = new PSVariable(SpecialVariables.PSDefaultParameterValues, new DefaultParameterDictionary(), ScopedItemOptions.None, attributes, RunspaceInit.PSDefaultParameterValuesDescription); GlobalScope.SetVariable(psDefaultParameterValuesVariable.Name, psDefaultParameterValuesVariable, false, false, this, fastPath: true); } #endregion Constructor #region Private data /// <summary> /// Provides all the path manipulation and globbing for Monad paths. /// </summary> /// internal LocationGlobber Globber { get { return _globberPrivate ?? (_globberPrivate = ExecutionContext.LocationGlobber); } } private LocationGlobber _globberPrivate; /// <summary> /// The context of the runspace to which this session state object belongs. /// </summary> internal ExecutionContext ExecutionContext { get; } /// <summary> /// Returns the public session state facade object for this session state instance. /// </summary> internal SessionState PublicSessionState { get { return _publicSessionState ?? (_publicSessionState = new SessionState(this)); } set { _publicSessionState = value; } } private SessionState _publicSessionState; /// <summary> /// Gets the engine APIs to access providers /// </summary> internal ProviderIntrinsics InvokeProvider { get { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } // get } private ProviderIntrinsics _invokeProvider; /// <summary> /// The module info object associated with this session state /// </summary> internal PSModuleInfo Module { get; set; } = null; // This is used to maintain the order in which modules were imported. // This is used by Get-Command -All to order by last imported internal List<string> ModuleTableKeys = new List<string>(); /// <summary> /// The private module table for this session state object... /// </summary> internal Dictionary<string, PSModuleInfo> ModuleTable { get; } = new Dictionary<string, PSModuleInfo>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Get/set constraints for this execution environemnt /// </summary> internal PSLanguageMode LanguageMode { get { return ExecutionContext.LanguageMode; } set { ExecutionContext.LanguageMode = value; } } /// <summary> /// If true the PowerShell debugger will use FullLanguage mode, otherwise it will use the current language mode /// </summary> internal bool UseFullLanguageModeInDebugger { get { return ExecutionContext.UseFullLanguageModeInDebugger; } } /// <summary> /// The list of scripts that are allowed to be run. If the name "*" /// is in the list, then all scripts can be run. (This is the default.) /// </summary> public List<string> Scripts { get; } = new List<string>(new string[] { "*" }); /// <summary> /// See if a script is allowed to be run. /// </summary> /// <param name="scriptPath">Path to check</param> /// <returns>true if script is allowed</returns> internal SessionStateEntryVisibility CheckScriptVisibility(string scriptPath) { return checkPathVisibility(Scripts, scriptPath); } /// <summary> /// The list of appications that are allowed to be run. If the name "*" /// is in the list, then all applications can be run. (This is the default.) /// </summary> public List<string> Applications { get; } = new List<string>(new string[] { "*" }); /// <summary> /// List of functions/filters to export from this session state object... /// </summary> internal List<CmdletInfo> ExportedCmdlets { get; } = new List<CmdletInfo>(); /// <summary> /// Defines the default command visibility for this session state. Binding an InitialSessionState instance /// with private members will set this to Private. /// </summary> internal SessionStateEntryVisibility DefaultCommandVisibility = SessionStateEntryVisibility.Public; /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry) { AddSessionStateEntry(entry, /*local*/false); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> /// <param name="local">If local, add cmdlet to current scope. Else, add to module scope</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry, bool local) { ExecutionContext.CommandDiscovery.AddSessionStateCmdletEntryToCache(entry, local); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> internal void AddSessionStateEntry(SessionStateApplicationEntry entry) { this.Applications.Add(entry.Path); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> internal void AddSessionStateEntry(SessionStateScriptEntry entry) { this.Scripts.Add(entry.Path); } /// <summary> /// Add the variables that must always be present in a SessionState instance... /// </summary> internal void InitializeFixedVariables() { // // BUGBUG // // String resources for aliases are currently associated with Runspace init // // $Host PSVariable v = new PSVariable( SpecialVariables.Host, ExecutionContext.EngineHostInterface, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHostDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $HOME - indicate where a user's home directory is located in the file system. // -- %USERPROFILE% on windows // -- %HOME% on unix string home = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home) ?? string.Empty; v = new PSVariable(SpecialVariables.Home, home, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.HOMEDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $ExecutionContext v = new PSVariable(SpecialVariables.ExecutionContext, ExecutionContext.EngineIntrinsics, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.ExecutionContextDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PSVersionTable v = new PSVariable(SpecialVariables.PSVersionTable, PSVersionInfo.GetPSVersionTable(), ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSVersionTableDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PSEdition v = new PSVariable(SpecialVariables.PSEdition, PSVersionInfo.PSEditionValue, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSEditionDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PID Process currentProcess = Process.GetCurrentProcess(); v = new PSVariable( SpecialVariables.PID, currentProcess.Id, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PIDDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PSCulture v = new PSCultureVariable(); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PSUICulture v = new PSUICultureVariable(); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $ShellId - if there is no runspace config, use the default string string shellId = ExecutionContext.ShellID; v = new PSVariable(SpecialVariables.ShellId, shellId, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.MshShellIdDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $PSHOME // This depends on the shellId. If we cannot read the application base // registry key, set the variable to empty string string applicationBase = ""; try { applicationBase = Utils.GetApplicationBase(shellId); } catch (SecurityException) { } v = new PSVariable(SpecialVariables.PSHome, applicationBase, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHOMEDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); // $Console - set the console file for this shell, if there is one, "" otherwise... SetConsoleVariable(); } /// <summary> /// Set the $Console variable in this session state instance... /// </summary> internal void SetConsoleVariable() { // $Console - set the console file for this shell, if there is one, "" otherwise... string consoleFileName = string.Empty; RunspaceConfigForSingleShell rcss = ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; if (rcss != null && rcss.ConsoleInfo != null && !string.IsNullOrEmpty(rcss.ConsoleInfo.Filename)) { consoleFileName = rcss.ConsoleInfo.Filename; } PSVariable v = new PSVariable(SpecialVariables.ConsoleFileName, consoleFileName, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.ConsoleDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); } /// <summary> /// Add all of the default built-in functions to this session state instance... /// </summary> internal void AddBuiltInEntries(bool addSetStrictMode) { // Other built-in variables AddBuiltInVariables(); AddBuiltInFunctions(); AddBuiltInAliases(); if (addSetStrictMode) { SessionStateFunctionEntry f = new SessionStateFunctionEntry("Set-StrictMode", ""); this.AddSessionStateEntry(f); } } /// <summary> /// Add the built-in variables to this instance of session state... /// </summary> internal void AddBuiltInVariables() { foreach (SessionStateVariableEntry e in InitialSessionState.BuiltInVariables) { this.AddSessionStateEntry(e); } } /// <summary> /// Add the built-in functions to this instance of session state... /// </summary> internal void AddBuiltInFunctions() { foreach (SessionStateFunctionEntry f in InitialSessionState.BuiltInFunctions) { this.AddSessionStateEntry(f); } } /// <summary> /// Add the built-in aliases to this instance of session state... /// </summary> internal void AddBuiltInAliases() { foreach (SessionStateAliasEntry ae in InitialSessionState.BuiltInAliases) { this.AddSessionStateEntry(ae, StringLiterals.Global); } } /// <summary> /// Check to see if an application is allowed to be run. /// </summary> /// <param name="applicationPath">The path to the application to check</param> /// <returns>True if application is permitted.</returns> internal SessionStateEntryVisibility CheckApplicationVisibility(string applicationPath) { return checkPathVisibility(Applications, applicationPath); } private SessionStateEntryVisibility checkPathVisibility(List<string> list, string path) { if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (String.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; if (list.Contains("*")) return SessionStateEntryVisibility.Public; foreach (string p in list) { if (String.Equals(p, path, StringComparison.OrdinalIgnoreCase)) return SessionStateEntryVisibility.Public; if (WildcardPattern.ContainsWildcardCharacters(p)) { WildcardPattern pattern = WildcardPattern.Get(p, WildcardOptions.IgnoreCase); if (pattern.IsMatch(path)) { return SessionStateEntryVisibility.Public; } } } return SessionStateEntryVisibility.Private; } #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release /// <summary> /// Gets the collection of relationship providers /// </summary> /// internal RelationshipProviderCollection Relationships { get { return relationships; } } private RelationshipProviderCollection relationships = null; #endif #endregion Private data /// <summary> /// Notification for SessionState to do cleanup /// before runspace is closed. /// </summary> /// internal void RunspaceClosingNotification() { if (this != ExecutionContext.TopLevelSessionState && Providers.Count > 0) { // Remove all providers at the top level... CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); Collection<string> keys = new Collection<string>(); foreach (string key in Providers.Keys) { keys.Add(key); } foreach (string providerName in keys) { // All errors are ignored. RemoveProvider(providerName, true, context); } } } #region Errors /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data /// </summary> /// /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// /// <param name="resourceStr"> /// This is the message template string. /// </param> /// /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// /// <param name="path"> /// The path used when formatting the error message. /// </param> /// /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> /// internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e) { return NewProviderInvocationException(resourceId, resourceStr, provider, path, e, true); } /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data /// </summary> /// /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// /// <param name="resourceStr"> /// This is the message template string. /// </param> /// /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// /// <param name="path"> /// The path used when formatting the error message. /// </param> /// /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// /// <param name="useInnerExceptionErrorMessage"> /// If true, the error record from the inner exception will be used if it contains one. /// If false, the error message specified by the resourceId will be used. /// </param> /// /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> /// internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { // If the innerException was itself thrown by // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; if (null != pie) { pie._providerInfo = provider; return pie; } pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( ExecutionContext, provider.Name, pie, Severity.Warning); return pie; } #endregion Errors } // SessionStateInternal class }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using GitTfs.Commands; using GitTfs.Core.TfsInterop; using GitTfs.Util; namespace GitTfs.Core { public class GitTfsRemote : IGitTfsRemote { private static readonly Regex isInDotGit = new Regex("(?:^|/)\\.git(?:/|$)", RegexOptions.Compiled); private readonly Globals _globals; private readonly RemoteOptions _remoteOptions; private readonly ConfigProperties _properties; private int? maxChangesetId; private string maxCommitHash; private bool isTfsAuthenticated; public RemoteInfo RemoteInfo { get; private set; } public GitTfsRemote(RemoteInfo info, IGitRepository repository, RemoteOptions remoteOptions, Globals globals, ITfsHelper tfsHelper, ConfigProperties properties) { _remoteOptions = remoteOptions; _globals = globals; _properties = properties; Tfs = tfsHelper; Repository = repository; RemoteInfo = info; Id = info.Id; TfsUrl = info.Url; TfsRepositoryPath = info.Repository; TfsUsername = info.Username; TfsPassword = info.Password; Aliases = (info.Aliases ?? Enumerable.Empty<string>()).ToArray(); IgnoreRegexExpression = info.IgnoreRegex; IgnoreExceptRegexExpression = info.IgnoreExceptRegex; Autotag = info.Autotag; IsSubtree = CheckSubtree(); } private bool CheckSubtree() { var m = GitTfsConstants.RemoteSubtreeRegex.Match(Id); if (m.Success) { OwningRemoteId = m.Groups["owner"].Value; Prefix = m.Groups["prefix"].Value; return true; } return false; } public void EnsureTfsAuthenticated() { if (isTfsAuthenticated) return; Tfs.EnsureAuthenticated(); isTfsAuthenticated = true; } public bool IsDerived { get { return false; } } public int? GetInitialChangeset() { return _properties.InitialChangeset; } public void SetInitialChangeset(int? changesetId) { _properties.InitialChangeset = changesetId; } public bool IsSubtree { get; private set; } public bool IsSubtreeOwner { get { return TfsRepositoryPath == null; } } public string Id { get; set; } public string TfsUrl { get { return Tfs.Url; } set { Tfs.Url = value; } } private string[] Aliases { get; set; } public bool Autotag { get; set; } public string TfsUsername { get { return Tfs.Username; } set { Tfs.Username = value; } } public string TfsPassword { get { return Tfs.Password; } set { Tfs.Password = value; } } public string TfsRepositoryPath { get; set; } /// <summary> /// Gets the TFS server-side paths of all subtrees of this remote. /// Valid if the remote has subtrees, which occurs when <see cref="TfsRepositoryPath"/> is null. /// </summary> public string[] TfsSubtreePaths { get { if (tfsSubtreePaths == null) tfsSubtreePaths = Repository.GetSubtrees(this).Select(x => x.TfsRepositoryPath).ToArray(); return tfsSubtreePaths; } } private string[] tfsSubtreePaths = null; public string IgnoreRegexExpression { get; set; } public string IgnoreExceptRegexExpression { get; set; } public IGitRepository Repository { get; set; } public ITfsHelper Tfs { get; set; } public string OwningRemoteId { get; private set; } public string Prefix { get; private set; } public bool ExportMetadatas { get; set; } public Dictionary<string, IExportWorkItem> ExportWorkitemsMapping { get; set; } public int MaxChangesetId { get { InitHistory(); return maxChangesetId.Value; } set { maxChangesetId = value; } } public string MaxCommitHash { get { InitHistory(); return maxCommitHash; } set { maxCommitHash = value; } } private TfsChangesetInfo GetTfsChangesetById(int id) { return Repository.GetTfsChangesetById(RemoteRef, id); } private void InitHistory() { if (maxChangesetId == null) { var mostRecentUpdate = Repository.GetLastParentTfsCommits(RemoteRef).FirstOrDefault(); if (mostRecentUpdate != null) { MaxCommitHash = mostRecentUpdate.GitCommit; MaxChangesetId = mostRecentUpdate.ChangesetId; } else { MaxChangesetId = 0; //Manage the special case where a .gitignore has been commited try { var gitCommit = Repository.GetCommit(RemoteRef); if (gitCommit != null) { MaxCommitHash = gitCommit.Sha; } } catch (Exception) { } } } } private const string WorkspaceDirectory = "~w"; private string WorkingDirectory { get { var dir = Repository.GetConfig(GitTfsConstants.WorkspaceConfigKey); if (IsSubtree) { if (dir != null) { return Path.Combine(dir, Prefix); } //find the relative path to the owning remote return Ext.CombinePaths(_globals.GitDir, WorkspaceDirectory, OwningRemoteId, Prefix); } return dir ?? DefaultWorkingDirectory; } } private string DefaultWorkingDirectory { get { return Path.Combine(_globals.GitDir, WorkspaceDirectory); } } public void CleanupWorkspace() { Tfs.CleanupWorkspaces(WorkingDirectory); } public void CleanupWorkspaceDirectory() { try { if (Directory.Exists(WorkingDirectory)) { var allFiles = Directory.EnumerateFiles(WorkingDirectory, "*", SearchOption.AllDirectories); foreach (var file in allFiles) File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); Directory.Delete(WorkingDirectory, true); } } catch (Exception ex) { Trace.WriteLine("CleanupWorkspaceDirectory: " + ex.Message); } } public bool ShouldSkip(string path) { return IsInDotGit(path) || IsIgnored(path); } private bool IsIgnored(string path) { return Ignorance.IsIncluded(path) || Repository.IsPathIgnored(path); } private Bouncer _ignorance; private Bouncer Ignorance { get { if (_ignorance == null) { _ignorance = new Bouncer(); _ignorance.Include(IgnoreRegexExpression); _ignorance.Include(_remoteOptions.IgnoreRegex); _ignorance.Exclude(IgnoreExceptRegexExpression); _ignorance.Exclude(_remoteOptions.ExceptRegex); } return _ignorance; } } private bool IsInDotGit(string path) { return isInDotGit.IsMatch(path); } public string GetPathInGitRepo(string tfsPath) { if (tfsPath == null) return null; if (!IsSubtreeOwner) { if (!tfsPath.StartsWith(TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)) return null; if (TfsRepositoryPath == GitTfsConstants.TfsRoot) { tfsPath = tfsPath.Substring(TfsRepositoryPath.Length); } else { if (tfsPath.Length > TfsRepositoryPath.Length && tfsPath[TfsRepositoryPath.Length] != '/') return null; tfsPath = tfsPath.Substring(TfsRepositoryPath.Length); } } else { //look through the subtrees var p = _globals.Repository.GetSubtrees(this) .Where(x => x.IsSubtree) .FirstOrDefault(x => tfsPath.StartsWith(x.TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) && (tfsPath.Length == x.TfsRepositoryPath.Length || tfsPath[x.TfsRepositoryPath.Length] == '/')); if (p == null) return null; tfsPath = p.GetPathInGitRepo(tfsPath); //we must prepend the prefix in order to get the correct directory if (tfsPath.StartsWith("/")) tfsPath = p.Prefix + tfsPath; else tfsPath = p.Prefix + "/" + tfsPath; } while (tfsPath.StartsWith("/")) tfsPath = tfsPath.Substring(1); return tfsPath; } public class FetchResult : IFetchResult { public bool IsSuccess { get; set; } public int LastFetchedChangesetId { get; set; } public int NewChangesetCount { get; set; } public string ParentBranchTfsPath { get; set; } public bool IsProcessingRenameChangeset { get; set; } public string LastParentCommitBeforeRename { get; set; } } public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null) { return FetchWithMerge(-1, stopOnFailMergeCommit, lastChangesetIdToFetch, renameResult); } public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes) { return FetchWithMerge(mergeChangesetId, stopOnFailMergeCommit, -1, renameResult, parentCommitsHashes); } public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes) { var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 }; var latestChangesetId = GetLatestChangesetId(); if (lastChangesetIdToFetch != -1) latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch); // TFS 2010 doesn't like when we ask for history past its last changeset. if (MaxChangesetId >= latestChangesetId) return fetchResult; bool fetchRetrievedChangesets; do { var fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch); var objects = BuildEntryDictionary(); fetchRetrievedChangesets = false; foreach (var changeset in fetchedChangesets) { fetchRetrievedChangesets = true; fetchResult.NewChangesetCount++; if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch) return fetchResult; string parentCommitSha = null; if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha)) { fetchResult.NewChangesetCount--; // Merge wasn't successful - so don't count the changeset we found fetchResult.IsSuccess = false; return fetchResult; } var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash; var isFirstCommitInRepository = (parentSha == null); var log = Apply(parentSha, changeset, objects); if (changeset.IsRenameChangeset && !isFirstCommitInRepository) { if (renameResult == null || !renameResult.IsProcessingRenameChangeset) { fetchResult.IsProcessingRenameChangeset = true; fetchResult.LastParentCommitBeforeRename = MaxCommitHash; return fetchResult; } renameResult.IsProcessingRenameChangeset = false; renameResult.LastParentCommitBeforeRename = null; } if (parentCommitSha != null) log.CommitParents.Add(parentCommitSha); if (changeset.Summary.ChangesetId == mergeChangesetId) { foreach (var parent in parentCommitsHashes) log.CommitParents.Add(parent); } var commitSha = ProcessChangeset(changeset, log); fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId; // set commit sha for added git objects foreach (var commit in objects) { if (commit.Value.Commit == null) commit.Value.Commit = commitSha; } DoGcIfNeeded(); } } while (fetchRetrievedChangesets && latestChangesetId > fetchResult.LastFetchedChangesetId); return fetchResult; } private Dictionary<string, GitObject> BuildEntryDictionary() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } private bool ProcessMergeChangeset(ITfsChangeset changeset, bool stopOnFailMergeCommit, ref string parentCommit) { if (!Tfs.CanGetBranchInformation) { Trace.TraceInformation("info: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But was not treated as is because this version of TFS can't manage branches..."); } else if (!IsIgnoringBranches()) { var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this); if (parentChangesetId < 1) // Handle missing merge parent info { if (stopOnFailMergeCommit) { return false; } Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But git-tfs is unable to determine the parent changeset."); return true; } var shaParent = Repository.FindCommitHashByChangesetId(parentChangesetId); if (shaParent == null) { string omittedParentBranch; shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit, out omittedParentBranch); changeset.OmittedParentBranch = omittedParentBranch; } if (shaParent != null) { parentCommit = shaParent; } else { if (stopOnFailMergeCommit) return false; Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But git-tfs failed to find and fetch the parent changeset " + parentChangesetId + ". Parent changeset will be ignored..."); } } else { Trace.TraceInformation("info: this changeset " + changeset.Summary.ChangesetId + " is a merge changeset. But was not treated as is because of your git setting..."); changeset.OmittedParentBranch = ";C" + changeset.Summary.ChangesetId; } return true; } public bool IsIgnoringBranches() { var value = Repository.GetConfig<string>(GitTfsConstants.IgnoreBranches, null); bool isIgnoringBranches; if (value != null && bool.TryParse(value, out isIgnoringBranches)) return isIgnoringBranches; Trace.TraceInformation("warning: no value found for branch management setting '" + GitTfsConstants.IgnoreBranches + "'..."); var isIgnoringBranchesDetected = Repository.ReadAllTfsRemotes().Count() < 2; Trace.TraceInformation("=> Branch support " + (isIgnoringBranchesDetected ? "disabled!" : "enabled!")); if (isIgnoringBranchesDetected) Trace.TraceInformation(" if you want to enable branch support, use the command:" + Environment.NewLine + " git config --local " + GitTfsConstants.IgnoreBranches + " false"); _globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, isIgnoringBranchesDetected.ToString()); return isIgnoringBranchesDetected; } private string ProcessChangeset(ITfsChangeset changeset, LogEntry log) { if (ExportMetadatas) { if (changeset.Summary.Workitems.Any()) { var workItems = TranslateWorkItems(changeset.Summary.Workitems.Select(wi => new ExportWorkItem(wi))); if (workItems != null) { log.Log += "\nWorkitems:"; foreach (var workItem in workItems) { log.Log += "\n#" + workItem.Id + " " + workItem.Title; } } } if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment)) log.Log += "\n" + GitTfsConstants.GitTfsPolicyOverrideCommentPrefix + " " + changeset.Summary.PolicyOverrideComment; foreach (var checkinNote in changeset.Summary.CheckinNotes) { if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value)) log.Log += "\n" + GitTfsConstants.GitTfsPrefix + "-" + CamelCaseToDelimitedStringConverter.Convert(checkinNote.Name, "-") + ": " + checkinNote.Value; } } var commitSha = Commit(log); UpdateTfsHead(commitSha, changeset.Summary.ChangesetId); StringBuilder metadatas = new StringBuilder(); if (changeset.Summary.Workitems.Any()) { string workitemNote = "Workitems:\n"; foreach (var workitem in changeset.Summary.Workitems) { var workitemId = workitem.Id.ToString(); var workitemUrl = workitem.Url; if (ExportMetadatas && ExportWorkitemsMapping.Count != 0) { if (ExportWorkitemsMapping.ContainsKey(workitemId)) { var oldWorkitemId = workitemId; workitemId = ExportWorkitemsMapping[workitemId].Id; workitemUrl = workitemUrl.Replace(oldWorkitemId, workitemId); } } workitemNote += string.Format("[{0}] {1}\n {2}\n", workitemId, workitem.Title, workitemUrl); } metadatas.Append(workitemNote); } if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment)) metadatas.Append("\nPolicy Override Comment: " + changeset.Summary.PolicyOverrideComment); foreach (var checkinNote in changeset.Summary.CheckinNotes) { if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value)) metadatas.Append("\n" + checkinNote.Name + ": " + checkinNote.Value); } if (!string.IsNullOrWhiteSpace(changeset.OmittedParentBranch)) metadatas.Append("\nOmitted parent branch: " + changeset.OmittedParentBranch); if (metadatas.Length != 0) Repository.CreateNote(commitSha, metadatas.ToString(), log.AuthorName, log.AuthorEmail, log.Date); return commitSha; } private IEnumerable<IExportWorkItem> TranslateWorkItems(IEnumerable<IExportWorkItem> workItemsOriginal) { if (ExportWorkitemsMapping.Count == 0) return workItemsOriginal; List<IExportWorkItem> workItemsTranslated = new List<IExportWorkItem>(); if (workItemsOriginal == null) return workItemsTranslated; foreach (var oldWorkItemId in workItemsOriginal) { IExportWorkItem translatedWorkItem = null; if (oldWorkItemId != null && !ExportWorkitemsMapping.TryGetValue(oldWorkItemId.Id, out translatedWorkItem)) translatedWorkItem = oldWorkItemId; if (translatedWorkItem != null) workItemsTranslated.Add(translatedWorkItem); } return workItemsTranslated; } private string FindRootRemoteAndFetch(int parentChangesetId, IRenameResult renameResult = null) { string omittedParentBranch; return FindRemoteAndFetch(parentChangesetId, false, false, renameResult, out omittedParentBranch); } private string FindMergedRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, out string omittedParentBranch) { return FindRemoteAndFetch(parentChangesetId, false, true, null, out omittedParentBranch); } private string FindRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch) { var tfsRemote = FindOrInitTfsRemoteOfChangeset(parentChangesetId, mergeChangeset, renameResult, out omittedParentBranch); if (tfsRemote != null && string.Compare(tfsRemote.TfsRepositoryPath, TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) != 0) { Trace.TraceInformation("\tFetching from dependent TFS remote '{0}'...", tfsRemote.Id); try { var fetchResult = ((GitTfsRemote)tfsRemote).FetchWithMerge(-1, stopOnFailMergeCommit, parentChangesetId, renameResult); } finally { Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); if (tfsRemote.Repository.IsBare) tfsRemote.Repository.UpdateRef(GitRepository.ShortToLocalName(tfsRemote.Id), tfsRemote.MaxCommitHash); } return Repository.FindCommitHashByChangesetId(parentChangesetId); } return null; } private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch) { omittedParentBranch = null; IGitTfsRemote tfsRemote; IChangeset parentChangeset = Tfs.GetChangeset(parentChangesetId); //I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply. //Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!! var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null)); if (remote != null) tfsRemote = remote; else { // If the changeset has created multiple folders, the expected branch folder will not always be the first // so we scan all the changes of type folder to try to detect the first one which is a branch. // In most cases it will change nothing: the first folder is the good one IBranchObject tfsBranch = null; string tfsPath = null; var allBranches = Tfs.GetBranches(true); foreach (var change in parentChangeset.Changes) { tfsPath = change.Item.ServerItem; tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/"; tfsBranch = allBranches.SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/")); if (tfsBranch != null) { // we found a branch, we stop here break; } } if (mergeChangeset && tfsBranch != null && Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches) == true.ToString()) { Trace.TraceInformation("warning: skip not initialized branch for path " + tfsBranch.Path); tfsRemote = null; omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId; } else if (tfsBranch == null) { Trace.TraceInformation("error: branch not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath); tfsRemote = null; omittedParentBranch = ";C" + parentChangesetId; } else { tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId, renameResult); if (tfsRemote == null) omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId; } } return tfsRemote; } private IGitTfsRemote InitTfsRemoteOfChangeset(IBranchObject tfsBranch, int parentChangesetId, IRenameResult renameResult = null) { if (tfsBranch.IsRoot) { return InitTfsBranch(_remoteOptions, tfsBranch.Path); } var branchesDatas = Tfs.GetRootChangesetForBranch(tfsBranch.Path, parentChangesetId); IGitTfsRemote remote = null; foreach (var branch in branchesDatas) { var rootChangesetId = branch.SourceBranchChangesetId; remote = InitBranch(_remoteOptions, tfsBranch.Path, rootChangesetId, true); if (remote == null) { Trace.TraceInformation("warning: root commit not found corresponding to changeset " + rootChangesetId); Trace.TraceInformation("=> continuing anyway by creating a branch without parent..."); return InitTfsBranch(_remoteOptions, tfsBranch.Path); } if (branch.IsRenamedBranch) { try { remote.Fetch(renameResult: renameResult); } finally { Trace.WriteLine("Cleaning..."); remote.CleanupWorkspaceDirectory(); if (remote.Repository.IsBare) remote.Repository.UpdateRef(GitRepository.ShortToLocalName(remote.Id), remote.MaxCommitHash); } } } return remote; } public void QuickFetch() { var changeset = GetLatestChangeset(); quickFetch(changeset); } public void QuickFetch(int changesetId) { var changeset = Tfs.GetChangeset(changesetId, this); quickFetch(changeset); } private void quickFetch(ITfsChangeset changeset) { var log = CopyTree(MaxCommitHash, changeset); UpdateTfsHead(Commit(log), changeset.Summary.ChangesetId); DoGcIfNeeded(); } private IEnumerable<ITfsChangeset> FetchChangesets(bool byLots, int lastVersion = -1) { int lowerBoundChangesetId; // If we're starting at the Root side of a branch commit (e.g. C1), but there ar // invalid commits between C1 and the actual branch side of the commit operation // (e.g. a Folder with the branch name was created [C2] and then deleted [C3], // then the root-side was branched [C4; C1 --branch--> C4]), this will detecte // only the folder creation and deletion operations due to the lowerBound being // detected as the root-side of the commit +1 (C1+1=C2) instead of referencing // the branch-side of the branching operation [C4]. if (_properties.InitialChangeset.HasValue) lowerBoundChangesetId = Math.Max(MaxChangesetId + 1, _properties.InitialChangeset.Value); else lowerBoundChangesetId = MaxChangesetId + 1; Trace.WriteLine(RemoteRef + ": Getting changesets from " + lowerBoundChangesetId + " to " + lastVersion + " ...", "info"); if (!IsSubtreeOwner) return Tfs.GetChangesets(TfsRepositoryPath, lowerBoundChangesetId, this, lastVersion, byLots); return _globals.Repository.GetSubtrees(this) .SelectMany(x => Tfs.GetChangesets(x.TfsRepositoryPath, lowerBoundChangesetId, x, lastVersion, byLots)) .OrderBy(x => x.Summary.ChangesetId); } public ITfsChangeset GetChangeset(int changesetId) { return Tfs.GetChangeset(changesetId, this); } private ITfsChangeset GetLatestChangeset() { if (!string.IsNullOrEmpty(TfsRepositoryPath)) return Tfs.GetLatestChangeset(this); var changesetId = _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangeset(x)).Max(x => x.Summary.ChangesetId); return GetChangeset(changesetId); } private int GetLatestChangesetId() { if (!string.IsNullOrEmpty(TfsRepositoryPath)) return Tfs.GetLatestChangesetId(this); return _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangesetId(x)).Max(); } public void UpdateTfsHead(string commitHash, int changesetId) { MaxCommitHash = commitHash; MaxChangesetId = changesetId; Repository.UpdateRef(RemoteRef, MaxCommitHash, "C" + MaxChangesetId); if (Autotag) Repository.UpdateRef(TagPrefix + "C" + MaxChangesetId, MaxCommitHash); LogCurrentMapping(); } private void LogCurrentMapping() { Trace.TraceInformation("C" + MaxChangesetId + " = " + MaxCommitHash); } private string TagPrefix { get { return "refs/tags/tfs/" + Id + "/"; } } public string RemoteRef { get { return "refs/remotes/tfs/" + Id; } } private void DoGcIfNeeded() { Trace.WriteLine("GC Countdown: " + _globals.GcCountdown); if (--_globals.GcCountdown < 0) { _globals.GcCountdown = _globals.GcPeriod; Repository.GarbageCollect(true, "Try running it after git-tfs is finished."); } } private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries) { return Apply(parent, changeset, entries, null); } private LogEntry Apply(string parent, ITfsChangeset changeset, Action<Exception> ignorableErrorHandler) { return Apply(parent, changeset, BuildEntryDictionary(), ignorableErrorHandler); } private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries, Action<Exception> ignorableErrorHandler) { LogEntry result = null; WithWorkspace(changeset.Summary, workspace => { var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(parent); result = changeset.Apply(parent, treeBuilder, workspace, entries, ignorableErrorHandler); result.Tree = treeBuilder.GetTree(); }); if (!string.IsNullOrEmpty(parent)) result.CommitParents.Add(parent); return result; } private LogEntry CopyTree(string lastCommit, ITfsChangeset changeset) { LogEntry result = null; WithWorkspace(changeset.Summary, workspace => { var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(null); result = changeset.CopyTree(treeBuilder, workspace); result.Tree = treeBuilder.GetTree(); }); if (!string.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit); return result; } private string Commit(LogEntry logEntry) { logEntry.Log = BuildCommitMessage(logEntry.Log, logEntry.ChangesetId); return Repository.Commit(logEntry).Sha; } private string BuildCommitMessage(string tfsCheckinComment, int changesetId) { var builder = new StringWriter(); builder.WriteLine(tfsCheckinComment); builder.WriteLine(GitTfsConstants.TfsCommitInfoFormat, TfsUrl, TfsRepositoryPath, changesetId); return builder.ToString(); } public void Unshelve(string shelvesetOwner, string shelvesetName, string destinationBranch, Action<Exception> ignorableErrorHandler, bool force) { var destinationRef = GitRepository.ShortToLocalName(destinationBranch); if (Repository.HasRef(destinationRef)) throw new GitTfsException("ERROR: Destination branch (" + destinationBranch + ") already exists!"); var shelvesetChangeset = Tfs.GetShelvesetData(this, shelvesetOwner, shelvesetName); var parentId = shelvesetChangeset.BaseChangesetId; var ch = GetTfsChangesetById(parentId); string rootCommit; if (ch == null) { if (!force) throw new GitTfsException("ERROR: Parent changeset C" + parentId + " not found.", new[] { "Try fetching the latest changes from TFS", "Try applying the shelveset on the currently checkouted commit using the '--force' option" } ); Trace.TraceInformation("warning: Parent changeset C" + parentId + " not found." + " Trying to apply the shelveset on the current commit..."); rootCommit = Repository.GetCurrentCommit(); } else { rootCommit = ch.GitCommit; } var log = Apply(rootCommit, shelvesetChangeset, ignorableErrorHandler); var commit = Commit(log); Repository.UpdateRef(destinationRef, commit, "Shelveset " + shelvesetName + " from " + shelvesetOwner); } public void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies) { WithWorkspace(parentChangeset, workspace => Shelve(shelvesetName, head, parentChangeset, options, evaluateCheckinPolicies, workspace)); } public bool HasShelveset(string shelvesetName) { return Tfs.HasShelveset(shelvesetName); } private void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); workspace.Shelve(shelvesetName, evaluateCheckinPolicies, options, () => Repository.GetCommitMessage(head, parentChangeset.GitCommit)); } public int CheckinTool(string head, TfsChangesetInfo parentChangeset) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = CheckinTool(head, parentChangeset, workspace)); return changeset; } private int CheckinTool(string head, TfsChangesetInfo parentChangeset, ITfsWorkspace workspace) { PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace); return workspace.CheckinTool(() => Repository.GetCommitMessage(head, parentChangeset.GitCommit)); } private void PendChangesToWorkspace(string head, string parent, ITfsWorkspaceModifier workspace) { using (var tidyWorkspace = new DirectoryTidier(workspace, () => GetLatestChangeset().GetFullTree())) { foreach (var change in Repository.GetChangedFiles(parent, head)) { change.Apply(tidyWorkspace); } } } public int Checkin(string head, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parentChangeset.GitCommit, workspace, options, sourceTfsPath)); return changeset; } public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { var changeset = 0; WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parent, workspace, options, sourceTfsPath)); return changeset; } private void WithWorkspace(TfsChangesetInfo parentChangeset, Action<ITfsWorkspace> action) { //are there any subtrees? var subtrees = _globals.Repository.GetSubtrees(this); if (subtrees.Any()) { Tfs.WithWorkspace(WorkingDirectory, this, subtrees.Select(x => new Tuple<string, string>(x.TfsRepositoryPath, x.Prefix)), parentChangeset, action); } else { Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, action); } } private int Checkin(string head, string parent, ITfsWorkspace workspace, CheckinOptions options, string sourceTfsPath) { PendChangesToWorkspace(head, parent, workspace); if (!string.IsNullOrWhiteSpace(sourceTfsPath)) workspace.Merge(sourceTfsPath, TfsRepositoryPath); return workspace.Checkin(options, () => Repository.GetCommitMessage(head, parent)); } public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath) { if (!MatchesTfsUrl(tfsUrl)) return false; if (TfsRepositoryPath == null) return tfsRepositoryPath == null; return TfsRepositoryPath.Equals(tfsRepositoryPath, StringComparison.OrdinalIgnoreCase); } public void DeleteShelveset(string shelvesetName) { WithWorkspace(null, workspace => workspace.DeleteShelveset(shelvesetName)); } private bool MatchesTfsUrl(string tfsUrl) { return TfsUrl.Equals(tfsUrl, StringComparison.OrdinalIgnoreCase) || Aliases.Contains(tfsUrl, StringComparison.OrdinalIgnoreCase); } private string ExtractGitBranchNameFromTfsRepositoryPath(string tfsRepositoryPath) { var includeTeamProjectName = !Repository.IsInSameTeamProjectAsDefaultRepository(tfsRepositoryPath); var gitBranchName = tfsRepositoryPath.ToGitBranchNameFromTfsRepositoryPath(includeTeamProjectName); gitBranchName = Repository.AssertValidBranchName(gitBranchName); Trace.TraceInformation("The name of the local branch will be : " + gitBranchName); return gitBranchName; } public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null, IRenameResult renameResult = null) { return InitTfsBranch(remoteOptions, tfsRepositoryPath, rootChangesetId, fetchParentBranch, gitBranchNameExpected, renameResult); } private IGitTfsRemote InitTfsBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId = -1, bool fetchParentBranch = false, string gitBranchNameExpected = null, IRenameResult renameResult = null) { Trace.WriteLine("Begin process of creating branch for remote :" + tfsRepositoryPath); // TFS string representations of repository paths do not end in trailing slashes tfsRepositoryPath = (tfsRepositoryPath ?? string.Empty).TrimEnd('/'); string gitBranchName = ExtractGitBranchNameFromTfsRepositoryPath( string.IsNullOrWhiteSpace(gitBranchNameExpected) ? tfsRepositoryPath : gitBranchNameExpected); if (string.IsNullOrWhiteSpace(gitBranchName)) throw new GitTfsException("error: The Git branch name '" + gitBranchName + "' is not valid...\n"); Trace.WriteLine("Git local branch will be :" + gitBranchName); string sha1RootCommit = null; if (rootChangesetId != -1) { sha1RootCommit = Repository.FindCommitHashByChangesetId(rootChangesetId); if (fetchParentBranch && string.IsNullOrWhiteSpace(sha1RootCommit)) sha1RootCommit = FindRootRemoteAndFetch(rootChangesetId, renameResult); if (string.IsNullOrWhiteSpace(sha1RootCommit)) return null; Trace.WriteLine("Found commit " + sha1RootCommit + " for changeset :" + rootChangesetId); } IGitTfsRemote tfsRemote; if (Repository.HasRemote(gitBranchName)) { Trace.WriteLine("Remote already exist"); tfsRemote = Repository.ReadTfsRemote(gitBranchName); if (tfsRemote.TfsUrl != TfsUrl) Trace.WriteLine("warning: Url is different"); if (tfsRemote.TfsRepositoryPath != tfsRepositoryPath) Trace.WriteLine("warning: TFS repository path is different"); } else { Trace.WriteLine("Try creating remote..."); tfsRemote = Repository.CreateTfsRemote(new RemoteInfo { Id = gitBranchName, Url = TfsUrl, Repository = tfsRepositoryPath, RemoteOptions = remoteOptions }, string.Empty); tfsRemote.ExportMetadatas = ExportMetadatas; tfsRemote.ExportWorkitemsMapping = ExportWorkitemsMapping; } if (sha1RootCommit != null && !Repository.HasRef(tfsRemote.RemoteRef)) { if (!Repository.CreateBranch(tfsRemote.RemoteRef, sha1RootCommit)) throw new GitTfsException("error: Fail to create remote branch ref file!"); } Trace.WriteLine("Remote created!"); return tfsRemote; } } }
namespace AdMaiora.Bugghy { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using AdMaiora.AppKit.UI; using AdMaiora.Bugghy.Api; using AdMaiora.Bugghy.Model; #pragma warning disable CS4014 public class IssuesFragment : AdMaiora.AppKit.UI.App.Fragment { #region Inner Classes class IssueAdapter : ItemRecyclerAdapter<IssueAdapter.ChatViewHolder, Issue> { #region Inner Classes public class ChatViewHolder : ItemViewHolder { [Widget] public ImageView TypeImage; [Widget] public TextView CodeLabel; [Widget] public TextView TitleLabel; [Widget] public TextView SenderLabel; [Widget] public TextView DescriptionLabel; [Widget] public TextView CreatedDateLabel; [Widget] public TextView StatusDescriptionLabel; public ChatViewHolder(View itemView) : base(itemView) { } } #endregion #region Costants and Fields #endregion #region Constructors public IssueAdapter(AdMaiora.AppKit.UI.App.Fragment context, IEnumerable<Issue> source) : base(context, Resource.Layout.CellIssue, source) { } #endregion #region Public Methods public override void GetView(int postion, ChatViewHolder holder, View view, Issue item) { string[] typeImages = new[] { "image_gear", "image_issue_crash", "image_issue_blocking", "image_issue_nblocking" }; holder.TypeImage.SetImageResource(typeImages[(int)item.Type]); holder.CodeLabel.Text = String.Format("code: #{0}", item.Code); holder.TitleLabel.Text = item.Title; holder.SenderLabel.Text = item.Sender.Split('@')[0]; holder.DescriptionLabel.Text = item.Description; holder.CreatedDateLabel.Text = item.CreationDate?.ToString("d"); holder.StatusDescriptionLabel.Text = item.Status.ToString(); } public void Clear() { this.SourceItems.Clear(); } public void Refresh(IEnumerable<Issue> items) { this.SourceItems.Clear(); this.SourceItems.AddRange(items); } #endregion #region Methods #endregion } #endregion #region Constants and Fields private int _gimmickId; private int _filter; private bool _addNew; private IssueAdapter _adapter; // This flag check if we are already calling the login REST service private bool _isRefreshingIssues; // This cancellation token is used to cancel the rest send message request private CancellationTokenSource _cts0; #endregion #region Widgets private Button[] FilterButtons; [Widget] private Button FilterOpenedButton; [Widget] private Button FilterWorkingButton; [Widget] private Button FilterClosedButton; [Widget] private ItemRecyclerView IssueList; #endregion #region Constructors public IssuesFragment() { } #endregion #region Properties #endregion #region Fragment Methods public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _gimmickId = this.Arguments.GetInt("GimmickId"); _filter = this.Arguments.GetInt("Filter"); _addNew = this.Arguments.GetBoolean("AddNew"); } public override void OnCreateView(LayoutInflater inflater, ViewGroup container) { base.OnCreateView(inflater, container); #region Desinger Stuff SetContentView(Resource.Layout.FragmentIssues, inflater, container); this.FilterButtons = new[] { this.FilterOpenedButton, this.FilterWorkingButton, this.FilterClosedButton }; this.HasOptionsMenu = true; #endregion this.Title = "Issues"; this.FilterOpenedButton.Click += FilterButton_Click; this.FilterWorkingButton.Click += FilterButton_Click; this.FilterClosedButton.Click += FilterButton_Click; _adapter = new IssueAdapter(this, new Issue[0]); this.IssueList.SetAdapter(_adapter); this.IssueList.ItemSelected += IssueList_ItemSelected; if (_addNew) { _addNew = false; var f = new IssueFragment(); f.Arguments = new Bundle(); f.Arguments.PutInt("GimmickId", _gimmickId); this.FragmentManager.BeginTransaction() .AddToBackStack("BeforeIssueFragment") .Replace(Resource.Id.ContentLayout, f, "IssueFragment") .Commit(); } else { RefreshIssues(_filter); } } public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) { base.OnCreateOptionsMenu(menu, inflater); menu.Clear(); menu.Add(0, 1, 0, "Add New").SetShowAsAction(ShowAsAction.Always); } public override bool OnOptionsItemSelected(IMenuItem item) { switch(item.ItemId) { case 1: var f = new IssueFragment(); f.Arguments = new Bundle(); f.Arguments.PutInt("GimmickId", _gimmickId); this.FragmentManager.BeginTransaction() .AddToBackStack("BeforeIssueFragment") .Replace(Resource.Id.ContentLayout, f, "IssueFragment") .Commit(); return true; default: return base.OnOptionsItemSelected(item); } } public override void OnDestroyView() { base.OnDestroyView(); this.FilterOpenedButton.Click -= FilterButton_Click; this.FilterWorkingButton.Click -= FilterButton_Click; this.FilterClosedButton.Click -= FilterButton_Click; this.IssueList.ItemSelected -= IssueList_ItemSelected; } #endregion #region Public Methods #endregion #region Methods private void RefreshIssues(int filter) { if (_isRefreshingIssues) return; _filter = filter; HilightFilterButton(filter); this.IssueList.Visibility = ViewStates.Gone; _isRefreshingIssues = true; ((MainActivity)this.Activity).BlockUI(); Issue[] issues = null; _cts0 = new CancellationTokenSource(); AppController.RefreshIssues(_cts0, _gimmickId, (newIssues) => { issues = newIssues; }, (error) => { Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show(); }, () => { if (issues != null) { LoadIssues(issues, filter); if(_adapter?.ItemCount > 0) this.IssueList.Visibility = ViewStates.Visible; _isRefreshingIssues = false; ((MainActivity)this.Activity).UnblockUI(); } else { AppController.Utility.ExecuteOnAsyncTask(_cts0.Token, () => { issues = AppController.GetIssues(_gimmickId); }, () => { LoadIssues(issues, filter); if (_adapter?.ItemCount > 0) this.IssueList.Visibility = ViewStates.Visible; _isRefreshingIssues = false; ((MainActivity)this.Activity).UnblockUI(); }); } }); } private void LoadIssues(IEnumerable<Issue> issues, int filter = -1) { if (issues == null) return; if(filter != -1) { // Filter by tab selection switch(filter) { case 0: issues = issues.Where(x => x.Status == IssueStatus.Opened); break; case 1: issues = issues.Where(x => x.Status == IssueStatus.Evaluating || x.Status == IssueStatus.Working); break; case 2: issues = issues.Where(x => x.Status == IssueStatus.Resolved || x.Status == IssueStatus.Rejected || x.Status == IssueStatus.Closed); break; } } // Sort desc by creation date issues = issues.OrderByDescending(x => x.CreationDate); _adapter.Refresh(issues); this.IssueList.ReloadData(); } private void HilightFilterButton(int filter) { for(int i = 0; i < this.FilterButtons.Length; i++) { Button b = this.FilterButtons[i]; b.SetTextColor(ViewBuilder.ColorFromARGB(i == filter ? AppController.Colors.Jet : AppController.Colors.White)); b.SetBackgroundColor(ViewBuilder.ColorFromARGB(i == filter ? AppController.Colors.White : AppController.Colors.Jet)); } } #endregion #region Event Handlers private void FilterButton_Click(object sender, EventArgs e) { int filter = Array.IndexOf(this.FilterButtons, sender); if (filter == _filter) return; RefreshIssues(filter); } private void IssueList_ItemSelected(object sender, ItemListSelectEventArgs e) { Issue issue = e.Item as Issue; var f = new ChatFragment(); f.Arguments = new Bundle(); f.Arguments.PutInt("GimmickId", _gimmickId); f.Arguments.PutObject<Issue>("Issue", issue); this.FragmentManager.BeginTransaction() .AddToBackStack("BeforeChatFragment") .Replace(Resource.Id.ContentLayout, f, "ChatFragment") .Commit(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.IO.Tests { public class Directory_GetFileSystemEntries_str : FileSystemTest { #region Utilities public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" }; protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories public virtual string[] GetEntries(string dirName) { return Directory.GetFileSystemEntries(dirName); } #endregion #region UniversalTests [Fact] public void NullFileName() { Assert.Throws<ArgumentNullException>(() => GetEntries(null)); } [Fact] public void EmptyFileName() { Assert.Throws<ArgumentException>(() => GetEntries(string.Empty)); } [Fact] public void InvalidFileNames() { Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist")); Assert.Throws<ArgumentException>(() => GetEntries("\0")); } [Fact] public void EmptyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Empty(GetEntries(testDir.FullName)); } [Fact] public void GetEntriesThenDelete() { string testDirPath = GetTestFilePath(); DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath); testDirInfo.Create(); string testDir1 = GetTestFileName(); string testDir2 = GetTestFileName(); string testFile1 = GetTestFileName(); string testFile2 = GetTestFileName(); string testFile3 = GetTestFileName(); string testFile4 = GetTestFileName(); string testFile5 = GetTestFileName(); testDirInfo.CreateSubdirectory(testDir1); testDirInfo.CreateSubdirectory(testDir2); using (File.Create(Path.Combine(testDirPath, testFile1))) using (File.Create(Path.Combine(testDirPath, testFile2))) using (File.Create(Path.Combine(testDirPath, testFile3))) { string[] results; using (File.Create(Path.Combine(testDirPath, testFile4))) using (File.Create(Path.Combine(testDirPath, testFile5))) { results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); Assert.Contains(Path.Combine(testDirPath, testFile4), results); Assert.Contains(Path.Combine(testDirPath, testFile5), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir1), results); Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } File.Delete(Path.Combine(testDirPath, testFile4)); File.Delete(Path.Combine(testDirPath, testFile5)); FailSafeDirectoryOperations.DeleteDirectory(testDir1, true); results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } } [Fact] public virtual void IgnoreSubDirectoryFiles() { string subDir = GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, subDir)); string testFile = Path.Combine(TestDirectory, GetTestFileName()); string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); string testDir = Path.Combine(TestDirectory, GetTestFileName()); string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); Directory.CreateDirectory(testDir); Directory.CreateDirectory(testDirInSub); using (File.Create(testFile)) using (File.Create(testFileInSub)) { string[] results = GetEntries(TestDirectory); if (TestFiles) Assert.Contains(testFile, results); if (TestDirectories) Assert.Contains(testDir, results); Assert.DoesNotContain(testFileInSub, results); Assert.DoesNotContain(testDirInSub, results); } } [Fact] public void NonexistentPath() { Assert.Throws<DirectoryNotFoundException>(() => GetEntries(GetTestFilePath())); } [Fact] public void TrailingSlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName())); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5)); Assert.NotNull(strArr); Assert.NotEmpty(strArr); } } #endregion #region PlatformSpecific [Fact] public void InvalidPath() { foreach (char invalid in Path.GetInvalidFileNameChars()) { if (invalid == '/' || invalid == '\\') { Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else if (invalid == ':') { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else { Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsInvalidCharsPath() { Assert.All(WindowsInvalidUnixValid, invalid => Assert.Throws<ArgumentException>(() => GetEntries(invalid))); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixValidCharsFilePath() { if (TestFiles) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) File.Create(Path.Combine(testDir.FullName, valid)).Dispose(); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixValidCharsDirectoryPath() { if (TestDirectories) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) testDir.CreateSubdirectory(valid); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } #endregion } public sealed class Directory_GetEntries_CurrentDirectory : RemoteExecutorTestBase { [Fact] public void CurrentDirectory() { string testDir = GetTestFilePath(); Directory.CreateDirectory(testDir); File.WriteAllText(Path.Combine(testDir, GetTestFileName()), "cat"); Directory.CreateDirectory(Path.Combine(testDir, GetTestFileName())); RemoteInvoke((testDirectory) => { Directory.SetCurrentDirectory(testDirectory); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); return SuccessExitCode; }, testDir).Dispose(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Service { using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Text; using Apache.Ignite.Config; using Apache.Ignite.Core; using Apache.Ignite.Core.Common; /// <summary> /// Ignite windows service. /// </summary> internal class IgniteService : ServiceBase { /** Service name. */ internal static readonly string SvcName = "Apache Ignite"; /** Service display name. */ internal static readonly string SvcDisplayName = "Apache Ignite .NET " + Assembly.GetExecutingAssembly().GetName().Version.ToString(4); /** Service description. */ internal static readonly string SvcDesc = "Apache Ignite .Net Service."; /** Current executable name. */ internal static readonly string ExeName = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).FullName; /** Current executable fully qualified name. */ internal static readonly string FullExeName = Path.GetFileName(FullExeName); /** Ignite configuration to start with. */ private readonly IgniteConfiguration _cfg; /// <summary> /// Constructor. /// </summary> public IgniteService(IgniteConfiguration cfg) { AutoLog = true; CanStop = true; ServiceName = SvcName; _cfg = cfg; } /** <inheritDoc /> */ protected override void OnStart(string[] args) { Ignition.Start(_cfg); } /** <inheritDoc /> */ protected override void OnStop() { Ignition.StopAll(true); } /// <summary> /// Install service programmatically. /// </summary> /// <param name="cfg">Ignite configuration.</param> internal static void DoInstall(IgniteConfiguration cfg) { // 1. Check if already defined. if (ServiceController.GetServices().Any(svc => SvcName.Equals(svc.ServiceName))) { throw new IgniteException("Ignite service is already installed (uninstall it using \"" + ExeName + " " + IgniteRunner.SvcUninstall + "\" first)"); } // 2. Create startup arguments. var args = ArgsConfigurator.ToArgs(cfg); if (args.Length > 0) { Console.WriteLine("Installing \"" + SvcName + "\" service with the following startup " + "arguments:"); foreach (var arg in args) Console.WriteLine("\t" + arg); } else Console.WriteLine("Installing \"" + SvcName + "\" service ..."); // 3. Actual installation. Install0(args); Console.WriteLine("\"" + SvcName + "\" service installed successfully."); } /// <summary> /// Uninstall service programmatically. /// </summary> internal static void Uninstall() { var svc = ServiceController.GetServices().FirstOrDefault(x => SvcName == x.ServiceName); if (svc == null) { Console.WriteLine("\"" + SvcName + "\" service is not installed."); } else if (svc.Status != ServiceControllerStatus.Stopped) { throw new IgniteException("Ignite service is running, please stop it first."); } else { Console.WriteLine("Uninstalling \"" + SvcName + "\" service ..."); Uninstall0(); Console.WriteLine("\"" + SvcName + "\" service uninstalled successfully."); } } /// <summary> /// Native service installation. /// </summary> /// <param name="args">Arguments.</param> private static void Install0(string[] args) { // 1. Prepare arguments. var binPath = new StringBuilder(FullExeName).Append(" ").Append(IgniteRunner.Svc); foreach (var arg in args) binPath.Append(" ").Append(arg); // 2. Get SC manager. var scMgr = OpenServiceControlManager(); // 3. Create service. var svc = NativeMethods.CreateService( scMgr, SvcName, SvcDisplayName, 983551, // Access constant. 0x10, // Service type SERVICE_WIN32_OWN_PROCESS. 0x2, // Start type SERVICE_AUTO_START. 0x2, // Error control SERVICE_ERROR_SEVERE. binPath.ToString(), null, IntPtr.Zero, null, null, // Use priviliged LocalSystem account. null ); if (svc == IntPtr.Zero) throw new IgniteException("Failed to create the service.", new Win32Exception()); // 4. Set description. var desc = new ServiceDescription {desc = Marshal.StringToHGlobalUni(SvcDesc)}; try { if (!NativeMethods.ChangeServiceConfig2(svc, 1u, ref desc)) throw new IgniteException("Failed to set service description.", new Win32Exception()); } finally { Marshal.FreeHGlobal(desc.desc); } } /// <summary> /// Native service uninstallation. /// </summary> private static void Uninstall0() { var scMgr = OpenServiceControlManager(); var svc = NativeMethods.OpenService(scMgr, SvcName, 65536); if (svc == IntPtr.Zero) throw new IgniteException("Failed to uninstall the service.", new Win32Exception()); NativeMethods.DeleteService(svc); } /// <summary> /// Opens SC manager. /// </summary> /// <returns>SC manager pointer.</returns> private static IntPtr OpenServiceControlManager() { var ptr = NativeMethods.OpenSCManager(null, null, 983103); if (ptr == IntPtr.Zero) throw new IgniteException("Failed to initialize Service Control manager " + "(did you run the command as administrator?)", new Win32Exception()); return ptr; } } }
#region License /* * WebSocketServerBase.cs * * The MIT License * * Copyright (c) 2012-2013 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Threading; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides the basic functions of the server that receives the WebSocket connection requests. /// </summary> /// <remarks> /// The WebSocketServerBase class is an abstract class. /// </remarks> public abstract class WebSocketServerBase { #region Private Fields private IPAddress _address; private X509Certificate2 _cert; private bool _listening; private Logger _logger; private int _port; private Thread _receiveRequestThread; private bool _secure; private bool _selfHost; private TcpListener _listener; private Uri _uri; #endregion #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketServerBase"/> class. /// </summary> /// <remarks> /// This constructor initializes a new instance of this class as non self hosted server. /// </remarks> protected WebSocketServerBase () : this (new Logger ()) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServerBase"/> class /// with the specified <paramref name="logger"/>. /// </summary> /// <remarks> /// This constructor initializes a new instance of this class as non self hosted server. /// </remarks> /// <param name="logger"> /// A <see cref="Logger"/> that provides the logging functions. /// </param> protected WebSocketServerBase (Logger logger) { _logger = logger; _selfHost = false; } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServerBase"/> class /// that listens for incoming connection attempts on the specified WebSocket URL. /// </summary> /// <param name="url"> /// A <see cref="string"/> that contains a WebSocket URL. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="url"/> is invalid. /// </exception> protected WebSocketServerBase (string url) { if (url == null) throw new ArgumentNullException ("url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); init (uri); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServerBase"/> class /// that listens for incoming connection attempts on the specified <paramref name="address"/>, /// <paramref name="port"/>, <paramref name="servicePath"/> and <paramref name="secure"/>. /// </summary> /// <param name="address"> /// A <see cref="IPAddress"/> that contains a local IP address. /// </param> /// <param name="port"> /// An <see cref="int"/> that contains a port number. /// </param> /// <param name="servicePath"> /// A <see cref="string"/> that contains an absolute path. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentNullException"> /// Either <paramref name="address"/> or <paramref name="servicePath"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is 0 or less, or 65536 or greater. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="servicePath"/> is invalid. /// </para> /// <para> /// -or- /// </para> /// <para> /// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid. /// </para> /// </exception> protected WebSocketServerBase (IPAddress address, int port, string servicePath, bool secure) { if (address == null) throw new ArgumentNullException ("address"); if (servicePath == null) throw new ArgumentNullException ("servicePath"); if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ("port", "Invalid port number: " + port); var msg = servicePath.CheckIfValidServicePath (); if (msg != null) throw new ArgumentException (msg, "servicePath"); if ((port == 80 && secure) || (port == 443 && !secure)) throw new ArgumentException (String.Format ( "Invalid pair of 'port' and 'secure': {0}, {1}", port, secure)); _address = address; _port = port; _uri = servicePath.ToUri (); _secure = secure; init (); } #endregion #region Protected Properties /// <summary> /// Gets or sets the WebSocket URL on which to listen for incoming connection attempts. /// </summary> /// <value> /// A <see cref="Uri"/> that contains a WebSocket URL. /// </value> protected Uri BaseUri { get { return _uri; } set { _uri = value; } } #endregion #region Public Properties /// <summary> /// Gets the local IP address on which to listen for incoming connection attempts. /// </summary> /// <value> /// A <see cref="IPAddress"/> that contains a local IP address. /// </value> public IPAddress Address { get { return _address; } } /// <summary> /// Gets or sets the certificate used to authenticate the server on the secure connection. /// </summary> /// <value> /// A <see cref="X509Certificate2"/> used to authenticate the server. /// </value> public X509Certificate2 Certificate { get { return _cert; } set { if (_listening) return; _cert = value; } } /// <summary> /// Gets a value indicating whether the server has been started. /// </summary> /// <value> /// <c>true</c> if the server has been started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _listening; } } /// <summary> /// Gets a value indicating whether the server provides secure connection. /// </summary> /// <value> /// <c>true</c> if the server provides secure connection; otherwise, <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets a value indicating whether the server is self host. /// </summary> /// <value> /// <c>true</c> if the server is self host; otherwise, <c>false</c>. /// </value> public bool IsSelfHost { get { return _selfHost; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is the <see cref="LogLevel.ERROR"/>. /// If you want to change the current logging level, you set the <c>Log.Level</c> property /// to one of the <see cref="LogLevel"/> values which you want. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } internal set { if (value == null) return; _logger = value; } } /// <summary> /// Gets the port on which to listen for incoming connection attempts. /// </summary> /// <value> /// An <see cref="int"/> that contains a port number. /// </value> public int Port { get { return _port; } } #endregion #region Private Methods private void init () { _listening = false; _logger = new Logger (); _selfHost = true; _listener = new TcpListener (_address, _port); } private void init (Uri uri) { var scheme = uri.Scheme; var host = uri.DnsSafeHost; var port = uri.Port; var addrs = Dns.GetHostAddresses (host); _uri = uri; _address = addrs [0]; _port = port; _secure = scheme == "wss" ? true : false; init (); } private void processRequestAsync (TcpClient client) { WaitCallback callback = state => { try { AcceptWebSocket (client.GetWebSocketContext (_secure, _cert)); } catch (Exception ex) { client.Close (); _logger.Fatal (ex.Message); } }; ThreadPool.QueueUserWorkItem (callback); } private void receiveRequest () { while (true) { try { processRequestAsync (_listener.AcceptTcpClient ()); } catch (SocketException) { _logger.Info ("TcpListener has been stopped."); break; } catch (Exception ex) { _logger.Fatal (ex.Message); break; } } } private void startReceiveRequestThread () { _receiveRequestThread = new Thread (new ThreadStart (receiveRequest)); _receiveRequestThread.IsBackground = true; _receiveRequestThread.Start (); } private static bool tryCreateUri (string uriString, out Uri result, out string message) { if (!uriString.TryCreateWebSocketUri (out result, out message)) return false; if (!result.Query.IsNullOrEmpty ()) { result = null; message = "Must not contain the query component: " + uriString; return false; } return true; } #endregion #region Protected Methods /// <summary> /// Accepts a WebSocket connection request. /// </summary> /// <param name="context"> /// A <see cref="TcpListenerWebSocketContext"/> that contains the WebSocket connection request objects. /// </param> protected abstract void AcceptWebSocket (TcpListenerWebSocketContext context); #endregion #region Public Methods /// <summary> /// Starts to receive the WebSocket connection requests. /// </summary> public virtual void Start () { if (!_selfHost || _listening) return; if (_secure && _cert == null) { _logger.Error ("Secure connection requires a server certificate."); return; } _listener.Start (); startReceiveRequestThread (); _listening = true; } /// <summary> /// Stops receiving the WebSocket connection requests. /// </summary> public virtual void Stop () { if (!_selfHost || !_listening) return; _listener.Stop (); _receiveRequestThread.Join (5 * 1000); _listening = false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public partial class Int64Tests { [Fact] public static void Ctor_Empty() { var i = new long(); Assert.Equal(0, i); } [Fact] public static void Ctor_Value() { long i = 41; Assert.Equal(41, i); } [Fact] public static void MaxValue() { Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue); } [Theory] [InlineData((long)234, (long)234, 0)] [InlineData((long)234, long.MinValue, 1)] [InlineData((long)234, (long)-123, 1)] [InlineData((long)234, (long)0, 1)] [InlineData((long)234, (long)123, 1)] [InlineData((long)234, (long)456, -1)] [InlineData((long)234, long.MaxValue, -1)] [InlineData((long)-234, (long)-234, 0)] [InlineData((long)-234, (long)234, -1)] [InlineData((long)-234, (long)-432, 1)] [InlineData((long)234, null, 1)] public void CompareTo_Other_ReturnsExpected(long i, object value, int expected) { if (value is long longValue) { Assert.Equal(expected, Math.Sign(i.CompareTo(longValue))); } Assert.Equal(expected, Math.Sign(i.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotLong_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((long)123).CompareTo(value)); } [Theory] [InlineData((long)789, (long)789, true)] [InlineData((long)789, (long)-789, false)] [InlineData((long)789, (long)0, false)] [InlineData((long)0, (long)0, true)] [InlineData((long)-789, (long)-789, true)] [InlineData((long)-789, (long)789, false)] [InlineData((long)789, null, false)] [InlineData((long)789, "789", false)] [InlineData((long)789, 789, false)] public static void Equals(long i1, object obj, bool expected) { if (obj is long) { long i2 = (long)obj; Assert.Equal(expected, i1.Equals(i2)); Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode())); } Assert.Equal(expected, i1.Equals(obj)); } [Fact] public void GetTypeCode_Invoke_ReturnsInt64() { Assert.Equal(TypeCode.Int64, ((long)1).GetTypeCode()); } public static IEnumerable<object[]> ToString_TestData() { NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo; yield return new object[] { long.MinValue, "G", emptyFormat, "-9223372036854775808" }; yield return new object[] { (long)-4567, "G", emptyFormat, "-4567" }; yield return new object[] { (long)0, "G", emptyFormat, "0" }; yield return new object[] { (long)4567, "G", emptyFormat, "4567" }; yield return new object[] { long.MaxValue, "G", emptyFormat, "9223372036854775807" }; yield return new object[] { (long)0x2468, "x", emptyFormat, "2468" }; yield return new object[] { (long)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) }; NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.NegativeSign = "#"; customFormat.NumberDecimalSeparator = "~"; customFormat.NumberGroupSeparator = "*"; yield return new object[] { (long)-2468, "N", customFormat, "#2*468~00" }; yield return new object[] { (long)2468, "N", customFormat, "2*468~00" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(long i, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString()); Assert.Equal(upperExpected, i.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, i.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString(upperFormat)); Assert.Equal(lowerExpected, i.ToString(lowerFormat)); Assert.Equal(upperExpected, i.ToString(upperFormat, null)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, i.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { long i = 123; Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { NumberStyles defaultStyle = NumberStyles.Integer; NumberFormatInfo emptyFormat = new NumberFormatInfo(); NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.CurrencySymbol = "$"; yield return new object[] { "-9223372036854775808", defaultStyle, null, -9223372036854775808 }; yield return new object[] { "-123", defaultStyle, null, (long)-123 }; yield return new object[] { "0", defaultStyle, null, (long)0 }; yield return new object[] { "123", defaultStyle, null, (long)123 }; yield return new object[] { "+123", defaultStyle, null, (long)123 }; yield return new object[] { " 123 ", defaultStyle, null, (long)123 }; yield return new object[] { "9223372036854775807", defaultStyle, null, 9223372036854775807 }; yield return new object[] { "123", NumberStyles.HexNumber, null, (long)0x123 }; yield return new object[] { "abc", NumberStyles.HexNumber, null, (long)0xabc }; yield return new object[] { "ABC", NumberStyles.HexNumber, null, (long)0xabc }; yield return new object[] { "1000", NumberStyles.AllowThousands, null, (long)1000 }; yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (long)-123 }; // Parentheses = negative yield return new object[] { "123", defaultStyle, emptyFormat, (long)123 }; yield return new object[] { "123", NumberStyles.Any, emptyFormat, (long)123 }; yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (long)0x12 }; yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (long)1000 }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string value, NumberStyles style, IFormatProvider provider, long expected) { long result; // If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.True(long.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, long.Parse(value)); // If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (provider != null) { Assert.Equal(expected, long.Parse(value, provider)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.True(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result)); Assert.Equal(expected, result); // If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (provider == null) { Assert.Equal(expected, long.Parse(value, style)); } Assert.Equal(expected, long.Parse(value, style, provider ?? new NumberFormatInfo())); } public static IEnumerable<object[]> Parse_Invalid_TestData() { NumberStyles defaultStyle = NumberStyles.Integer; NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.CurrencySymbol = "$"; customFormat.NumberDecimalSeparator = "."; yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) }; yield return new object[] { "", defaultStyle, null, typeof(FormatException) }; yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) }; yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal yield return new object[] { "-9223372036854775809", defaultStyle, null, typeof(OverflowException) }; // < min value yield return new object[] { "9223372036854775808", defaultStyle, null, typeof(OverflowException) }; // > max value } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { long result; // If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.False(long.TryParse(value, out result)); Assert.Equal(default(long), result); Assert.Throws(exceptionType, () => long.Parse(value)); // If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (provider != null) { Assert.Throws(exceptionType, () => long.Parse(value, provider)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.False(long.TryParse(value, style, provider ?? new NumberFormatInfo(), out result)); Assert.Equal(default(long), result); // If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (provider == null) { Assert.Throws(exceptionType, () => long.Parse(value, style)); } Assert.Throws(exceptionType, () => long.Parse(value, style, provider ?? new NumberFormatInfo())); } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)] [InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName) { long result = 0; AssertExtensions.Throws<ArgumentException>(paramName, () => long.TryParse("1", style, null, out result)); Assert.Equal(default(long), result); AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style)); AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style, null)); } } }
// NoteDataXML_Panel.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using Layout; using System.Windows.Forms; using System.Drawing; using CoreUtilities; namespace LayoutPanels { public class NoteDataXML_Panel :NoteDataXML { #region constants public override int defaultHeight { get { return 400; } } public override int defaultWidth { get { return 500; } } #endregion #region gui protected LayoutPanelBase panelLayout; #endregion #region variable public override bool IsPanel { get { return true;} } #endregion #region testingstub public void Add10TestNotes () { for (int i=0; i <10; i++) { NoteDataXML note = new NoteDataXML(); note.Caption = "hello there " + i.ToString(); panelLayout.AddNote (note); } } #endregion // This is where it gets tricky. Need to modify the list of valid data types to store! public NoteDataXML_Panel () : base() { Caption = Loc.Instance.Cat.GetString("Panel"); } public override void Dispose () { lg.Instance.Line("NoteDataXML_Panel->Dispose", ProblemType.MESSAGE, String.Format ("Dispose called for Note Panel Caption/Guid {0}/{1}", Caption, this.GuidForNote),Loud.ACRITICAL); base.Dispose (); } /// <summary> /// Gets the panels layout. This is used when autobuilding a panel inside a panel inside DefaultLayouts.cs /// </summary> public LayoutPanelBase GetPanelsLayout () { return panelLayout; } public NoteDataXML_Panel(int height, int width) : base(height, width) { Caption = Loc.Instance.Cat.GetString("Panel"); } /// <summary> /// Gets the child notes. /// </summary> public override System.Collections.ArrayList GetChildNotes() { LayoutDatabase layout = new LayoutDatabase(this.GuidForNote); layout.LoadFrom(null); return layout.GetAllNotes(); } protected override string GetIcon () { return @"%*folder.png"; } // names of subnotes, if a panel or equivalent notes (used for accessiblity as NoteDataXML_Panel not alwasy available) /// <summary> /// Lists the of subnotes. JUST THE NAMES /// /// </summary> /// <returns> /// The of subnotes. /// </returns> public override System.Collections.Generic.List<string> ListOfSubnotes () { System.Collections.Generic.List<string> output = new System.Collections.Generic.List<string> (); LayoutDatabase layout = new LayoutDatabase(this.GuidForNote); layout.LoadFrom(null); foreach (NoteDataInterface note in layout.GetAllNotes()) { output.Add(note.Caption); } return output; } /// <summary> /// Lists the of subnotes as notes. For faster access to the subnotes of a subpanel. (September 16 2013) /// </summary> /// <returns> /// The of subnotes as notes. /// </returns> public override System.Collections.Generic.List<NoteDataInterface> ListOfSubnotesAsNotes () { System.Collections.Generic.List<NoteDataInterface> output = new System.Collections.Generic.List<NoteDataInterface> (); LayoutDatabase layout = new LayoutDatabase(this.GuidForNote); layout.LoadFrom(null); foreach (NoteDataInterface note in layout.GetAllNotes()) { output.Add(note); } return output; } /// <summary> /// Adds the note. (during a move operation. Called from LayoutPanel) /// </summary> /// <param name='note'> /// Note. /// </param> public void AddNote (NoteDataInterface note) { if (null == panelLayout) { throw new Exception("No layout defined for this Subpanel. Did you remember to add it to a Layout?"); } else panelLayout.AddNote (note); // jan 20 2013 - added this because i was doing an Update in LayoutPanel but that was causing // issues with destroying/disposing the original object //note.CreateParent(panelLayout); } public override void Save () { base.Save (); // February 2013 - Confusion arises because both LayoutPanel and Notes have ParentGUID // it is the notes ParentGUID that is blank, not the layoutpanel //NewMessage.Show(String.Format ("My {0} parent GUid is {1} ..", this.Caption, panelLayout.ParentGUID)); // need some kind of copy constructor to grab things like Notebook and Section from the parent to give to the child panels // if (panelLayout.ParentGUID == Constants.BLANK) { // panelLayout.ParentGUID = GetAbsoluteParent (); // } //panelLayout.ParentGUID = Layout.GetAbsoluteParent().GUID; if (Layout != null) { // if (Layout.GUID != panelLayout.ParentGUID) // { // string message = Loc.Instance.GetStringFmt ("Parent ID is: {0} but this panel parent's ID is set to: {0}", // this.Layout.GUID, this.panelLayout.ParentGUID); // NewMessage.Show (message); // } panelLayout.SetParentFields (Layout.Section, Layout.Keywords, Layout.Subtype, Layout.Notebook); panelLayout.SaveLayout (); } else { NewMessage.Show ("Could not save a subpanel. Import error. Layout was null on " + Caption + " from? " ); } } protected override void DoBuildChildren (LayoutPanelBase Layout) { base.DoBuildChildren (Layout); ParentNotePanel.BorderStyle = BorderStyle.Fixed3D; CaptionLabel.Dock = DockStyle.Top; ToolStripButton UpdateGuid = new ToolStripButton(); UpdateGuid.Text = Loc.Instance.GetString ("Verify Parent"); UpdateGuid.Click+= HandleVerifyParentClick; this.properties.DropDownItems.Add (UpdateGuid); panelLayout = new LayoutPanel(Layout.GUID, false); panelLayout.SetSubNoteSaveRequired = Layout.SetSaveRequired; // must set the Parent before loading panelLayout.Parent = ParentNotePanel; // load the layout based on the note panelLayout.LoadLayout(this.GuidForNote, true, Layout.GetLayoutTextEditContextStrip()); panelLayout.Visible = true; panelLayout.Dock = DockStyle.Fill; panelLayout.BringToFront(); panelLayout.SetParentLayoutCurrentNote = Layout.SetCurrentTextNote; /* I do not know why I duplicated this! ToolStripButton ShowTabs = new ToolStripButton(Loc.Instance.GetString("Show Tabs?")); ShowTabs.CheckOnClick = true; ShowTabs.Checked = panelLayout.ShowTabs; ShowTabs.CheckedChanged+= HandleCheckedChanged; properties.DropDownItems.Add (ShowTabs); */ } void HandleVerifyParentClick (object sender, EventArgs e) { string GUIDToSetTo = this.Layout.GUID; // here is where things get tricky // on a proper Layout ALL the subpanels inherit the ROOT ParentGUID // but the imported data messed this up // So if OUR PARENT has a PARENT then we use the PARENTGUID if (this.Layout.GetIsChild == true && this.Layout.ParentGuidFromNotes != Constants.BLANK) { GUIDToSetTo = this.Layout.ParentGuidFromNotes; } string message = Loc.Instance.GetStringFmt ("Parent ID is: {0}. Panel Parent ID says {1}. Panel Parent Notes ID says: {2}", GUIDToSetTo, this.panelLayout.ParentGUID, this.panelLayout.ParentGuidFromNotes); // issue I do not thik ParentGUID is the same as notes.ParentGuid and why not? if (NewMessage.Show (Loc.Instance.GetStringFmt ("Set Parent ID of this Panel to {0}?", GUIDToSetTo), Loc.Instance.GetString (message), MessageBoxButtons.YesNo, null) == DialogResult.Yes) { this.panelLayout.SetParentGuidForNotesFromExternal(GUIDToSetTo); } } /// <summary> /// Registers the type. /// </summary> public override string RegisterType() { return Loc.Instance.Cat.GetString("Panel"); } void HandleCheckedChanged (object sender, EventArgs e) { panelLayout.ShowTabs = !panelLayout.ShowTabs; panelLayout.RefreshTabs(); SetSaveRequired(true); } public NoteDataInterface FindSubpanelNote(NoteDataInterface note) { lg.Instance.Line("NoteDataXML_Panel->FindSubpanelNote", ProblemType.MESSAGE, String.Format ("Searching {0} for subnotes", this.Caption),Loud.CTRIVIAL); return panelLayout.FindSubpanelNote(note); } public void ClearDrag() { panelLayout.ClearDrag(); } protected override AppearanceClass UpdateAppearance () { AppearanceClass app = base.UpdateAppearance (); if (null != app) { ParentNotePanel.BackColor = app.captionBackground; panelLayout.ColorToolBars(app); } return app; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gcwcv = Google.Cloud.Workflows.Common.V1; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Workflows.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedWorkflowsClientTest { [xunit::FactAttribute] public void GetWorkflowRequestObject() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow response = client.GetWorkflow(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetWorkflowRequestObjectAsync() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow responseCallSettings = await client.GetWorkflowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Workflow responseCancellationToken = await client.GetWorkflowAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetWorkflow() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow response = client.GetWorkflow(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetWorkflowAsync() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow responseCallSettings = await client.GetWorkflowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Workflow responseCancellationToken = await client.GetWorkflowAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetWorkflowResourceNames() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow response = client.GetWorkflow(request.WorkflowName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetWorkflowResourceNamesAsync() { moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; Workflow expectedResponse = new Workflow { WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Description = "description2cf9da67", State = Workflow.Types.State.Unspecified, RevisionId = "revision_id8d9ae05d", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), RevisionCreateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, ServiceAccount = "service_accounta3c1b923", SourceContents = "source_contentscf4464d3", }; mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null)); WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null); Workflow responseCallSettings = await client.GetWorkflowAsync(request.WorkflowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Workflow responseCancellationToken = await client.GetWorkflowAsync(request.WorkflowName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Text.RegularExpressions { public partial class Capture { internal Capture() { } public int Index { get { throw null; } } public int Length { get { throw null; } } public string Value { get { throw null; } } public override string ToString() { throw null; } } public partial class CaptureCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Capture>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal CaptureCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Text.RegularExpressions.Capture this[int i] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Capture[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Capture> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.IndexOf(System.Text.RegularExpressions.Capture item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.Insert(int index, System.Text.RegularExpressions.Capture item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.RemoveAt(int index) { } System.Text.RegularExpressions.Capture System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.this[int index] { get { throw null; } set { } } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Add(System.Text.RegularExpressions.Capture item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Contains(System.Text.RegularExpressions.Capture item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Remove(System.Text.RegularExpressions.Capture item) { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } bool System.Collections.IList.IsFixedSize { get { throw null; } } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } object System.Collections.IList.this[int index] { get { throw null; } set { } } } public partial class Group : System.Text.RegularExpressions.Capture { internal Group() { } public System.Text.RegularExpressions.CaptureCollection Captures { get { throw null; } } public string Name { get { throw null; } } public bool Success { get { throw null; } } public static System.Text.RegularExpressions.Group Synchronized(System.Text.RegularExpressions.Group inner) { throw null; } } public partial class GroupCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>, System.Collections.Generic.IList<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Group>, System.Collections.IList, System.Collections.Generic.IReadOnlyDictionary<string, Group> { internal GroupCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Text.RegularExpressions.Group this[int groupnum] { get { throw null; } } public System.Text.RegularExpressions.Group this[string groupname] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Group[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Group> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.IndexOf(System.Text.RegularExpressions.Group item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.Insert(int index, System.Text.RegularExpressions.Group item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.RemoveAt(int index) { } System.Text.RegularExpressions.Group System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.this[int index] { get { throw null; } set { } } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Add(System.Text.RegularExpressions.Group item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Contains(System.Text.RegularExpressions.Group item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Remove(System.Text.RegularExpressions.Group item) { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } bool System.Collections.IList.IsFixedSize { get { throw null; } } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } public bool ContainsKey(string key) { throw null; } public bool TryGetValue(string key, out Group value) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Text.RegularExpressions.Group>>.GetEnumerator() { throw null; } public System.Collections.Generic.IEnumerable<string> Keys => throw null; public System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group> Values => throw null; object System.Collections.IList.this[int index] { get { throw null; } set { } } } public partial class Match : System.Text.RegularExpressions.Group { internal Match() { } public static System.Text.RegularExpressions.Match Empty { get { throw null; } } public virtual System.Text.RegularExpressions.GroupCollection Groups { get { throw null; } } public System.Text.RegularExpressions.Match NextMatch() { throw null; } public virtual string Result(string replacement) { throw null; } public static System.Text.RegularExpressions.Match Synchronized(System.Text.RegularExpressions.Match inner) { throw null; } } public partial class MatchCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>, System.Collections.Generic.IList<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Match>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal MatchCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public virtual System.Text.RegularExpressions.Match this[int i] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int arrayIndex) { } public void CopyTo(System.Text.RegularExpressions.Match[] array, int arrayIndex) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Match> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.IndexOf(System.Text.RegularExpressions.Match item) { throw null; } void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.Insert(int index, System.Text.RegularExpressions.Match item) { } void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.RemoveAt(int index) { } System.Text.RegularExpressions.Match System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.this[int index] { get { throw null; } set { } } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Add(System.Text.RegularExpressions.Match item) { } void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Clear() { } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Contains(System.Text.RegularExpressions.Match item) { throw null; } bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Remove(System.Text.RegularExpressions.Match item) { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } bool System.Collections.IList.IsFixedSize { get { throw null; } } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } object System.Collections.IList.this[int index] { get { throw null; } set { } } } public delegate string MatchEvaluator(System.Text.RegularExpressions.Match match); public partial class Regex : System.Runtime.Serialization.ISerializable { protected internal System.Collections.Hashtable caps; protected internal System.Collections.Hashtable capnames; protected internal int capsize; protected internal string[] capslist; protected internal System.Text.RegularExpressions.RegexRunnerFactory factory; public static readonly System.TimeSpan InfiniteMatchTimeout; protected internal System.TimeSpan internalMatchTimeout; protected internal string pattern; protected internal System.Text.RegularExpressions.RegexOptions roptions; protected Regex() { } protected Regex(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Regex(string pattern) { } public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options) { } public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { } public static int CacheSize { get { throw null; } set { } } [System.CLSCompliant(false)] protected System.Collections.IDictionary Caps { get { throw null; } set { } } [System.CLSCompliant(false)] protected System.Collections.IDictionary CapNames { get { throw null; } set { } } public System.TimeSpan MatchTimeout { get { throw null; } } public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } } public bool RightToLeft { get { throw null; } } public static string Escape(string str) { throw null; } public string[] GetGroupNames() { throw null; } public int[] GetGroupNumbers() { throw null; } public string GroupNameFromNumber(int i) { throw null; } public int GroupNumberFromName(string name) { throw null; } protected void InitializeReferences() { } public bool IsMatch(string input) { throw null; } public bool IsMatch(string input, int startat) { throw null; } public static bool IsMatch(string input, string pattern) { throw null; } public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public System.Text.RegularExpressions.Match Match(string input) { throw null; } public System.Text.RegularExpressions.Match Match(string input, int startat) { throw null; } public System.Text.RegularExpressions.Match Match(string input, int beginning, int length) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public System.Text.RegularExpressions.MatchCollection Matches(string input) { throw null; } public System.Text.RegularExpressions.MatchCollection Matches(string input, int startat) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public string Replace(string input, string replacement) { throw null; } public string Replace(string input, string replacement, int count) { throw null; } public string Replace(string input, string replacement, int count, int startat) { throw null; } public static string Replace(string input, string pattern, string replacement) { throw null; } public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count) { throw null; } public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat) { throw null; } public string[] Split(string input) { throw null; } public string[] Split(string input, int count) { throw null; } public string[] Split(string input, int count, int startat) { throw null; } public static string[] Split(string input, string pattern) { throw null; } public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; } public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } public static string Unescape(string str) { throw null; } protected bool UseOptionC() { throw null; } protected bool UseOptionR() { throw null; } protected internal static void ValidateMatchTimeout(System.TimeSpan matchTimeout) { } } public partial class RegexCompilationInfo { public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic) { } public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic, TimeSpan matchTimeout) { } public bool IsPublic { get; set; } public TimeSpan MatchTimeout { get; set; } public string Name { get; set; } public string Namespace { get; set; } public RegexOptions Options { get; set; } public string Pattern { get; set; } } public partial class RegexMatchTimeoutException : System.TimeoutException, System.Runtime.Serialization.ISerializable { public RegexMatchTimeoutException() { } protected RegexMatchTimeoutException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public RegexMatchTimeoutException(string message) { } public RegexMatchTimeoutException(string message, System.Exception inner) { } public RegexMatchTimeoutException(string regexInput, string regexPattern, System.TimeSpan matchTimeout) { } public string Input { get { throw null; } } public System.TimeSpan MatchTimeout { get { throw null; } } public string Pattern { get { throw null; } } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } } [System.FlagsAttribute] public enum RegexOptions { Compiled = 8, CultureInvariant = 512, ECMAScript = 256, ExplicitCapture = 4, IgnoreCase = 1, IgnorePatternWhitespace = 32, Multiline = 2, None = 0, RightToLeft = 64, Singleline = 16, } public abstract partial class RegexRunner { protected internal int[] runcrawl; protected internal int runcrawlpos; protected internal System.Text.RegularExpressions.Match runmatch; protected internal System.Text.RegularExpressions.Regex runregex; protected internal int[] runstack; protected internal int runstackpos; protected internal string runtext; protected internal int runtextbeg; protected internal int runtextend; protected internal int runtextpos; protected internal int runtextstart; protected internal int[] runtrack; protected internal int runtrackcount; protected internal int runtrackpos; protected internal RegexRunner() { } protected void Capture(int capnum, int start, int end) { } protected static bool CharInClass(char ch, string charClass) { throw null; } protected static bool CharInSet(char ch, string @set, string category) { throw null; } protected void CheckTimeout() { } protected void Crawl(int i) { } protected int Crawlpos() { throw null; } protected void DoubleCrawl() { } protected void DoubleStack() { } protected void DoubleTrack() { } protected void EnsureStorage() { } protected abstract bool FindFirstChar(); protected abstract void Go(); protected abstract void InitTrackCount(); protected bool IsBoundary(int index, int startpos, int endpos) { throw null; } protected bool IsECMABoundary(int index, int startpos, int endpos) { throw null; } protected bool IsMatched(int cap) { throw null; } protected int MatchIndex(int cap) { throw null; } protected int MatchLength(int cap) { throw null; } protected int Popcrawl() { throw null; } protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) { throw null; } protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, System.TimeSpan timeout) { throw null; } protected void TransferCapture(int capnum, int uncapnum, int start, int end) { } protected void Uncapture() { } } public abstract partial class RegexRunnerFactory { protected RegexRunnerFactory() { } protected internal abstract System.Text.RegularExpressions.RegexRunner CreateInstance(); } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace SmallSharpTools.VSX.Composite.VSPackage { // Last command type sent to the macro recorder. Note that there are more commands // recorded than is implied by this list. Commands in this list (other than // LastMacroNone) are coalesced when multiples of the same command are received // consecutively. // This enum should be extended or replaced with your own command identifiers to enable // Coalescing of commands. public enum LastMacro { None, Text, DownArrowLine, DownArrowLineSelection, DownArrowPara, DownArrowParaSelection, UpArrowLine, UpArrowLineSelection, UpArrowPara, UpArrowParaSelection, LeftArrowChar, LeftArrowCharSelection, LeftArrowWord, LeftArrowWordSelection, RightArrowChar, RightArrowCharSelection, RightArrowWord, RightArrowWordSelection, DeleteChar, DeleteWord, BackspaceChar, BackspaceWord } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum MoveScope { Character = tom.tomConstants.tomCharacter, Word = tom.tomConstants.tomWord, Line = tom.tomConstants.tomLine, Paragraph = tom.tomConstants.tomParagraph } /// <summary> /// The VSMacroRecorder class implementation and the IVsMacroRecorder Interface definition /// were included here in this seperate class because they were not included in the /// interop assemblies shipped with Visual Studio 2005. /// /// When implementing a macro recorder this class should be copied into your own name space /// and not shared between different 3rd party packages. /// </summary> public class VSMacroRecorder { private IVsMacroRecorder m_VsMacroRecorder; private LastMacro m_LastMacroRecorded; private uint m_TimesPreviouslyRecorded; Guid m_GuidEmitter; public VSMacroRecorder(Guid emitter) { this.m_LastMacroRecorded = LastMacro.None; this.m_GuidEmitter = emitter; } // Compiler generated destructor is fine public void Reset() { m_LastMacroRecorded = LastMacro.None; m_TimesPreviouslyRecorded = 0; } public void Stop() { Reset(); m_VsMacroRecorder = null; } public bool IsLastRecordedMacro(LastMacro macro) { return (macro == m_LastMacroRecorded && ObjectIsLastMacroEmitter()) ? true : false; } public bool IsRecording() { // If the property can not be retreived it is assumeed no macro is being recorded. VSRECORDSTATE recordState = VSRECORDSTATE.VSRECORDSTATE_OFF; // Retrieve the macro recording state. IVsShell vsShell = (IVsShell)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SVsShell)); if (vsShell != null) { object var; if (ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_RecordState, out var)) && null != var) { recordState = (VSRECORDSTATE)var; } } // If there is a change in the record state to OFF or ON we must either obtain // or release the macro recorder. if (recordState == VSRECORDSTATE.VSRECORDSTATE_ON && m_VsMacroRecorder == null) { // If this QueryService fails we no macro recording m_VsMacroRecorder = (IVsMacroRecorder)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsMacroRecorder)); } else if (recordState == VSRECORDSTATE.VSRECORDSTATE_OFF && m_VsMacroRecorder != null) { // If the macro recording state has been switched off then we can release // the service. Note that if the state has become paused we take no action. Stop(); } return (m_VsMacroRecorder != null); } public void RecordLine(string line) { m_VsMacroRecorder.RecordLine(line, ref m_GuidEmitter); Reset(); } public bool RecordBatchedLine(LastMacro macroRecorded, string line) { if (null == line) line = ""; return RecordBatchedLine(macroRecorded, line, 0); } public bool RecordBatchedLine(LastMacro macroRecorded, string line, int maxLineLength) { if (null == line) line = ""; if (maxLineLength > 0 && line.Length >= maxLineLength) { // Reset the state after recording the line, so it will not be appended to further RecordLine(line); // Notify the caller that the this line will not be appended to further return true; } if(IsLastRecordedMacro(macroRecorded)) { m_VsMacroRecorder.ReplaceLine(line, ref m_GuidEmitter); // m_LastMacroRecorded can stay the same ++m_TimesPreviouslyRecorded; } else { m_VsMacroRecorder.RecordLine(line, ref m_GuidEmitter); m_LastMacroRecorded = macroRecorded; m_TimesPreviouslyRecorded = 1; } return false; } public uint GetTimesPreviouslyRecorded(LastMacro macro) { return IsLastRecordedMacro(macro) ? m_TimesPreviouslyRecorded : 0; } // This function determines if the last line sent to the macro recorder was // sent from this emitter. Note it is not valid to call this function if // macro recording is switched off. private bool ObjectIsLastMacroEmitter() { Guid guid; m_VsMacroRecorder.GetLastEmitterId(out guid); return guid.Equals(m_GuidEmitter); } } #region "IVsMacro Interfaces" [StructLayout(LayoutKind.Sequential, Pack = 4), ComConversionLoss] internal struct _VSPROPSHEETPAGE { public uint dwSize; public uint dwFlags; [ComAliasName("vbapkg.ULONG_PTR")] public uint hInstance; public ushort wTemplateId; public uint dwTemplateSize; [ComConversionLoss] public IntPtr pTemplate; [ComAliasName("vbapkg.ULONG_PTR")] public uint pfnDlgProc; [ComAliasName("vbapkg.LONG_PTR")] public int lParam; [ComAliasName("vbapkg.ULONG_PTR")] public uint pfnCallback; [ComConversionLoss] public IntPtr pcRefParent; public uint dwReserved; [ComConversionLoss, ComAliasName("vbapkg.wireHWND")] public IntPtr hwndDlg; } internal enum _VSRECORDMODE { // Fields VSRECORDMODE_ABSOLUTE = 1, VSRECORDMODE_RELATIVE = 2 } [ComImport, ComConversionLoss, InterfaceType(1), Guid("55ED27C1-4CE7-11D2-890F-0060083196C6")] internal interface IVsMacros { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetMacroCommands([Out] IntPtr ppsaMacroCanonicalNames); } [ComImport, InterfaceType(1), Guid("04BBF6A5-4697-11D2-890E-0060083196C6")] internal interface IVsMacroRecorder { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordStart([In, MarshalAs(UnmanagedType.LPWStr)] string pszReserved); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordEnd(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine, [In] ref Guid rguidEmitter); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetLastEmitterId([Out] out Guid pguidEmitter); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ReplaceLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine, [In] ref Guid rguidEmitter); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordCancel(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordPause(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void RecordResume(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetCodeEmittedFlag([In] int fFlag); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCodeEmittedFlag([Out] out int pfFlag); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetKeyWord([In] uint uiKeyWordId, [Out, MarshalAs(UnmanagedType.BStr)] out string pbstrKeyWord); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void IsValidIdentifier([In, MarshalAs(UnmanagedType.LPWStr)] string pszIdentifier); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetRecordMode([Out] out _VSRECORDMODE peRecordMode); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetRecordMode([In] _VSRECORDMODE eRecordMode); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetStringLiteralExpression([In, MarshalAs(UnmanagedType.LPWStr)] string pszStringValue, [Out, MarshalAs(UnmanagedType.BStr)] out string pbstrLiteralExpression); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ExecuteLine([In, MarshalAs(UnmanagedType.LPWStr)] string pszLine); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void AddTypeLibRef([In] ref Guid guidTypeLib, [In] uint uVerMaj, [In] uint uVerMin); } #endregion }
using System; using UnityEngine; using System.Collections.Generic; using UnityEditor; namespace UEDS { public static class UEDSStyles { public const string kImagePath ="Assets/UEDS/Editor/images/"; static Dictionary<long,Texture2D>mTextures = new Dictionary<long, Texture2D>(); static Texture2D GetTexture(long pColorRGBA) { if(mTextures.ContainsKey(pColorRGBA) && mTextures[pColorRGBA] != null) return mTextures[pColorRGBA]; Color32 c = GetColor(pColorRGBA); var tmp = new Texture2D(4,4); for(int x = 0;x < 4;x++) for(int y = 0;y < 4;y++) tmp.SetPixel(x,y,c); tmp.Apply(); tmp.Compress(true); mTextures[pColorRGBA] = tmp; return tmp; } static Color32 GetColor(long pColorRGBA) { byte r =(byte)( (pColorRGBA & 0xff000000) >> 24 ); byte g =(byte)( (pColorRGBA & 0xff0000) >> 16 ); byte b =(byte)( (pColorRGBA & 0xff00) >> 8 ); byte a =(byte)( (pColorRGBA & 0xff) ); Color32 c = new Color32(r,g,b,a); return c; } static GUIStyle mList; public static GUIStyle list { get { if(mList == null) { mList = new GUIStyle(); mList.normal.background = GetTexture(0x424646ff); mList.alignment = TextAnchor.UpperLeft; mList.stretchWidth = true; mList.stretchHeight = true; } return mList; } } static GUIStyle mSelectableListEntry; public static GUIStyle selectableListEntry { get { if(mSelectableListEntry == null) { mSelectableListEntry = new GUIStyle(list); mSelectableListEntry.stretchHeight = false; mSelectableListEntry.normal.textColor = GetColor(0xb5b5b5ff); mSelectableListEntry.fontStyle = FontStyle.Bold; mSelectableListEntry.padding = new RectOffset(20,20,10,9); mSelectableListEntry.border = new RectOffset(0,0,0,1); } return mSelectableListEntry; } } static GUIStyle mSelectableListEntryOdd; public static GUIStyle selectableListEntryOdd { get { if(mSelectableListEntryOdd == null) { mSelectableListEntryOdd = new GUIStyle( selectableListEntry ); mSelectableListEntryOdd.normal.background = GetTexture(0x333535ff); } return mSelectableListEntryOdd; } } static GUIStyle mSelectedListEntry; public static GUIStyle selectedListEntry { get { if(mSelectedListEntry == null) { mSelectedListEntry = new GUIStyle(); mSelectedListEntry.normal.background = GetTexture(0x1b76d1ff); mSelectedListEntry.normal.textColor = GetColor(0xffffffff); mSelectedListEntry.fontStyle = FontStyle.Bold; mSelectedListEntry.padding = new RectOffset(20,20,10,9); mSelectedListEntry.border = new RectOffset(0,0,0,1); } return mSelectedListEntry; } } static GUIStyle mDirtySetting; public static GUIStyle dirtySetting { get { if(mDirtySetting == null) { mDirtySetting = new GUIStyle(); mDirtySetting.normal.background = GetTexture(0x1b76d1ff); } return mDirtySetting; } } static GUIStyle mBigHint; public static GUIStyle bigHint { get { if(mBigHint == null) { mBigHint = new GUIStyle(); mBigHint.alignment = TextAnchor.MiddleCenter; mBigHint.stretchWidth = true; mBigHint.stretchHeight = true; mBigHint.fontSize = 32; mBigHint.fontStyle = FontStyle.Bold; mBigHint.normal.textColor = GetColor(0x00000066); } return mBigHint; } } static GUIStyle mDetailsGroup; public static GUIStyle detailsGroup { get { if(mDetailsGroup == null) { mDetailsGroup = new GUIStyle(); mDetailsGroup.alignment = TextAnchor.UpperLeft; mDetailsGroup.margin = new RectOffset(2,2,2,2); } return mDetailsGroup; } } static GUIStyle mInfoGroup; public static GUIStyle infoGroup { get { if(mInfoGroup == null) { mInfoGroup = new GUIStyle(); mInfoGroup.alignment = TextAnchor.UpperLeft; mInfoGroup.margin = new RectOffset(20,20,2,10); mInfoGroup.padding = new RectOffset(10,10,5,5); mInfoGroup.normal.background = GetTexture(0x00000066); } return mInfoGroup; } } static GUIStyle mDetailsGizmo; public static GUIStyle detailsGizmo { get { if(mDetailsGizmo == null) { mDetailsGizmo = new GUIStyle(); mDetailsGizmo.alignment = TextAnchor.MiddleLeft; mDetailsGizmo.fixedWidth = 32; mDetailsGizmo.fixedHeight = 32; mDetailsGizmo.margin = new RectOffset(10,10,0,0); mDetailsGizmo.normal.textColor = Color.white; } return mDetailsGizmo; } } static GUIStyle mDetailsTitle; public static GUIStyle detailsTitle { get { if(mDetailsTitle == null) { mDetailsTitle = new GUIStyle(); mDetailsTitle.alignment = TextAnchor.MiddleLeft; mDetailsTitle.fontSize = 24; mDetailsTitle.normal.textColor = Color.white; } return mDetailsTitle; } } static GUIStyle mDetailsDescription; public static GUIStyle detailsDescription { get { if(mDetailsDescription == null) { mDetailsDescription = new GUIStyle(); mDetailsDescription.alignment = TextAnchor.UpperLeft; mDetailsDescription.margin = new RectOffset(65,10,10,15); mDetailsDescription.wordWrap = true; } return mDetailsDescription; } } static GUIStyle mStatusMessage; public static GUIStyle statusMessage { get { if(mStatusMessage == null) { mStatusMessage = new GUIStyle(); mStatusMessage.alignment = TextAnchor.MiddleCenter; mStatusMessage.stretchWidth = false; mStatusMessage.stretchHeight = false; mStatusMessage.fixedHeight = 20; mStatusMessage.fontSize = 12; mStatusMessage.margin = new RectOffset(10,10,2,2); mStatusMessage.normal.textColor = GetColor(0x00000066); } return mStatusMessage; } } static GUIStyle mSettingsDescription; public static GUIStyle settingDescription { get { if(mSettingsDescription == null) { mSettingsDescription = new GUIStyle(); mSettingsDescription.alignment = TextAnchor.MiddleRight; mSettingsDescription.imagePosition = ImagePosition.ImageOnly; mSettingsDescription.fixedWidth = 32; mSettingsDescription.fixedHeight = 20; mSettingsDescription.stretchHeight = false; mSettingsDescription.stretchWidth = false; mSettingsDescription.margin = new RectOffset(10,10,2,2); } return mSettingsDescription; } } static GUIStyle mHLine; public static GUIStyle hLine { get { if(mHLine == null) { mHLine = new GUIStyle(); mHLine.alignment = TextAnchor.MiddleCenter; mHLine.stretchWidth = true; mHLine.fixedHeight = 1; mHLine.normal.background = GetTexture(0x00000066); } return mHLine; } } static GUIStyle mVLine; public static GUIStyle vLine { get { if(mVLine == null) { mVLine = new GUIStyle(); mVLine.alignment = TextAnchor.MiddleCenter; mVLine.stretchHeight = true; mVLine.fixedHeight = 0; mVLine.fixedWidth = 1; mVLine.normal.background = GetTexture(0xffffff66); } return mVLine; } } public static void VerticalLine() { GUILayout.Label("",vLine); } public static void HorizontalLine() { GUILayout.Label("",hLine); } static GUIStyle mHSeparator; public static GUIStyle hSeparator { get { if(mHSeparator == null) { mHSeparator = new GUIStyle(); mHSeparator.alignment = TextAnchor.MiddleCenter; mHSeparator.stretchWidth = true; mHSeparator.fixedHeight = 1; mHSeparator.margin = new RectOffset(20,20,5,5); mHSeparator.normal.background = GetTexture(0x00000066); } return mHSeparator; } } public static void HorizontalSeparator() { GUILayout.Label("",hSeparator); } static GUIContent mOpenFileContent; public static GUIContent openFileContent { get { if(mOpenFileContent == null) { mOpenFileContent = new GUIContent(); mOpenFileContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath(UEDSStyles.kImagePath + "open.png", typeof(Texture2D)); mOpenFileContent.text = "Open"; } return mOpenFileContent; } } static GUIContent mSaveFileContent; public static GUIContent saveFileContent { get { if(mSaveFileContent == null) { mSaveFileContent = new GUIContent(); mSaveFileContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath(UEDSStyles.kImagePath + "save.png", typeof(Texture2D)); mSaveFileContent.text = "Save"; } return mSaveFileContent; } } static GUIContent mDupInstanceContent; public static GUIContent dupInstanceContent { get { if(mDupInstanceContent == null) { mDupInstanceContent = new GUIContent(); mDupInstanceContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath(UEDSStyles.kImagePath + "duplicate.png", typeof(Texture2D)); mDupInstanceContent.text = "Duplicate Instance"; } return mDupInstanceContent; } } static GUIContent mAddInstanceContent; public static GUIContent addInstanceContent { get { if(mAddInstanceContent == null) { mAddInstanceContent = new GUIContent(); mAddInstanceContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath( UEDSStyles.kImagePath + "add.png", typeof(Texture2D)); mAddInstanceContent.text = "Add Instance"; } return mAddInstanceContent; } } static GUIContent mDelInstanceContent; public static GUIContent delInstanceContent { get { if(mDelInstanceContent == null) { mDelInstanceContent = new GUIContent(); mDelInstanceContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath(UEDSStyles.kImagePath + "delete.png", typeof(Texture2D)); mDelInstanceContent.text = "Remove Instance"; } return mDelInstanceContent; } } static GUIContent mRenameInstanceContent; public static GUIContent renameInstanceContent { get { if(mRenameInstanceContent == null) { mRenameInstanceContent = new GUIContent(); mRenameInstanceContent.image = (Texture2D)AssetDatabase.LoadAssetAtPath(UEDSStyles.kImagePath + "rename.png", typeof(Texture2D)); mRenameInstanceContent.tooltip = "Rename Instance"; } return mRenameInstanceContent; } } } }
using System; using System.Text; using Server; using Server.Mobiles; using Server.Engines.CannedEvil; namespace Server.Misc { public class Titles { public const int MinFame = 0; public const int MaxFame = 15000; public static void AwardFame( Mobile m, int offset, bool message ) { if ( offset > 0 ) { if ( m.Fame >= MaxFame ) return; offset -= m.Fame / 100; if ( offset < 0 ) offset = 0; } else if ( offset < 0 ) { if ( m.Fame <= MinFame ) return; offset -= m.Fame / 100; if ( offset > 0 ) offset = 0; } if ( (m.Fame + offset) > MaxFame ) offset = MaxFame - m.Fame; else if ( (m.Fame + offset) < MinFame ) offset = MinFame - m.Fame; m.Fame += offset; if ( message ) { if ( offset > 40 ) m.SendLocalizedMessage( 1019054 ); // You have gained a lot of fame. else if ( offset > 20 ) m.SendLocalizedMessage( 1019053 ); // You have gained a good amount of fame. else if ( offset > 10 ) m.SendLocalizedMessage( 1019052 ); // You have gained some fame. else if ( offset > 0 ) m.SendLocalizedMessage( 1019051 ); // You have gained a little fame. else if ( offset < -40 ) m.SendLocalizedMessage( 1019058 ); // You have lost a lot of fame. else if ( offset < -20 ) m.SendLocalizedMessage( 1019057 ); // You have lost a good amount of fame. else if ( offset < -10 ) m.SendLocalizedMessage( 1019056 ); // You have lost some fame. else if ( offset < 0 ) m.SendLocalizedMessage( 1019055 ); // You have lost a little fame. } } public const int MinKarma = -15000; public const int MaxKarma = 15000; public static void AwardKarma( Mobile m, int offset, bool message ) { if ( offset > 0 ) { if ( m is PlayerMobile && ((PlayerMobile)m).KarmaLocked ) return; if ( m.Karma >= MaxKarma ) return; offset -= m.Karma / 100; if ( offset < 0 ) offset = 0; } else if ( offset < 0 ) { if ( m.Karma <= MinKarma ) return; offset -= m.Karma / 100; if ( offset > 0 ) offset = 0; } if ( (m.Karma + offset) > MaxKarma ) offset = MaxKarma - m.Karma; else if ( (m.Karma + offset) < MinKarma ) offset = MinKarma - m.Karma; bool wasPositiveKarma = ( m.Karma >= 0 ); m.Karma += offset; if ( message ) { if ( offset > 40 ) m.SendLocalizedMessage( 1019062 ); // You have gained a lot of karma. else if ( offset > 20 ) m.SendLocalizedMessage( 1019061 ); // You have gained a good amount of karma. else if ( offset > 10 ) m.SendLocalizedMessage( 1019060 ); // You have gained some karma. else if ( offset > 0 ) m.SendLocalizedMessage( 1019059 ); // You have gained a little karma. else if ( offset < -40 ) m.SendLocalizedMessage( 1019066 ); // You have lost a lot of karma. else if ( offset < -20 ) m.SendLocalizedMessage( 1019065 ); // You have lost a good amount of karma. else if ( offset < -10 ) m.SendLocalizedMessage( 1019064 ); // You have lost some karma. else if ( offset < 0 ) m.SendLocalizedMessage( 1019063 ); // You have lost a little karma. } if ( !Core.AOS && wasPositiveKarma && m.Karma < 0 && m is PlayerMobile && !((PlayerMobile)m).KarmaLocked ) { ((PlayerMobile)m).KarmaLocked = true; m.SendLocalizedMessage( 1042511, "", 0x22 ); // Karma is locked. A mantra spoken at a shrine will unlock it again. } } public static string[] HarrowerTitles = new string[] { "Spite", "Opponent", "Hunter", "Venom", "Executioner", "Annihilator", "Champion", "Assailant", "Purifier", "Nullifier" }; public static string ComputeTitle( Mobile beholder, Mobile beheld ) { StringBuilder title = new StringBuilder(); int fame = beheld.Fame; int karma = beheld.Karma; bool showSkillTitle = beheld.ShowFameTitle && ( (beholder == beheld) || (fame >= 5000) ); /*if ( beheld.Kills >= 5 ) { title.AppendFormat( beheld.Fame >= 10000 ? "The Murderer {1} {0}" : "The Murderer {0}", beheld.Name, beheld.Female ? "Lady" : "Lord" ); } else*/if ( beheld.ShowFameTitle || (beholder == beheld) ) { for ( int i = 0; i < m_FameEntries.Length; ++i ) { FameEntry fe = m_FameEntries[i]; if ( fame <= fe.m_Fame || i == (m_FameEntries.Length - 1) ) { KarmaEntry[] karmaEntries = fe.m_Karma; for ( int j = 0; j < karmaEntries.Length; ++j ) { KarmaEntry ke = karmaEntries[j]; if ( karma <= ke.m_Karma || j == (karmaEntries.Length - 1) ) { title.AppendFormat( beheld.Female? ke.m_FTitle : ke.m_Title, beheld.Name, beheld.Female ? "La Grande" : "Le Grand" ); break; } } break; } } } else { title.Append( beheld.Name ); } if( beheld is PlayerMobile && ((PlayerMobile)beheld).DisplayChampionTitle ) { PlayerMobile.ChampionTitleInfo info = ((PlayerMobile)beheld).ChampionTitles; if( info.Harrower > 0 ) title.AppendFormat( ": {0} of Evil", HarrowerTitles[Math.Min( HarrowerTitles.Length, info.Harrower )-1] ); else { int highestValue = 0, highestType = 0; for( int i = 0; i < ChampionSpawnInfo.Table.Length; i++ ) { int v = info.GetValue( i ); if( v > highestValue ) { highestValue = v; highestType = i; } } int offset = 0; if( highestValue > 800 ) offset = 3; else if( highestValue > 300 ) offset = (int)(highestValue/300); if( offset > 0 ) { ChampionSpawnInfo champInfo = ChampionSpawnInfo.GetInfo( (ChampionSpawnType)highestType ); title.AppendFormat( ": {0} of the {1}", champInfo.LevelNames[Math.Min( offset, champInfo.LevelNames.Length ) -1], champInfo.Name ); } } } string customTitle = beheld.Title; if ( customTitle != null && (customTitle = customTitle.Trim()).Length > 0 ) { title.AppendFormat( " {0}", customTitle ); } else if ( showSkillTitle && beheld.Player ) { string skillTitle = GetSkillTitle( beheld ); if ( skillTitle != null ) { title.Append( ", " ).Append( skillTitle ); } } return title.ToString(); } public static string GetSkillTitle( Mobile mob ) { Skill highest = GetHighestSkill( mob );// beheld.Skills.Highest; if (highest != null && highest.BaseFixedPoint >= 300) { //string skillLevel = GetSkillLevel(highest); string skillLevel = (mob.Female ? FGetSkillLevel(highest) : GetSkillLevel(highest)); string skillTitle = (mob.Female ? highest.Info.FTitle : highest.Info.Title); /*if ( mob.Female && skillTitle.EndsWith( "man" ) ) skillTitle = skillTitle.Substring( 0, skillTitle.Length - 3 ) + "woman";*/ if(skillLevel != null && skillTitle != null) return String.Concat(skillLevel, " ", skillTitle); } return null; } private static Skill GetHighestSkill( Mobile m ) { Skills skills = m.Skills; if ( !Core.AOS ) return skills.Highest; Skill highest = null; for ( int i = 0; i < m.Skills.Length; ++i ) { Skill check = m.Skills[i]; if ( highest == null || check.BaseFixedPoint > highest.BaseFixedPoint ) highest = check; else if ( highest != null && highest.Lock != SkillLock.Up && check.Lock == SkillLock.Up && check.BaseFixedPoint == highest.BaseFixedPoint ) highest = check; } return highest; } private static string[,] m_Levels = new string[,] { { "Neophite", "Neophite", "Neophite" }, { "Novice", "Novice", "Novice" }, { "Apprenti", "Apprenti", "Apprenti" }, { "Compagnon", "Compagnon", "Compagnon" }, { "Expert", "Expert", "Expert" }, { "Adepte", "Adepte", "Adepte" }, { "Maitre", "Maitre", "Maitre" }, { "Grand Maitre", "Grand Maitre", "Grand Maitre" }, { "Ancien", "Ancien", "Ancien" }, { "Legendaire", "Legendaire", "Legendaire" } }; private static string[,] m_FLevels = new string[,] { { "Neophite", "Neophite", "Neophite" }, { "Novice", "Novice", "Novice" }, { "Apprentie", "Apprentie", "Apprentie" }, { "Compagnon", "Compagnon", "Compagnon" }, { "Experte", "Experte", "Experte" }, { "Adepte", "Adepte", "Adepte" }, { "Maitre", "Maitre", "Maitre" }, { "Grande Maitre", "Grande Maitre", "Grande Maitre" }, { "Ancienne", "Ancienne", "Ancienne" }, { "Legendaire", "Legendaire", "Legendaire" } }; private static string GetSkillLevel( Skill skill ) { return m_Levels[GetTableIndex( skill ), GetTableType( skill )]; } private static string FGetSkillLevel(Skill skill) { return m_FLevels[GetTableIndex(skill), GetTableType(skill)]; } private static int GetTableType( Skill skill ) { switch ( skill.SkillName ) { default: return 0; case SkillName.Bushido: return 1; case SkillName.Ninjitsu: return 2; } } private static int GetTableIndex( Skill skill ) { int fp = Math.Min( skill.BaseFixedPoint, 1200 ); return (fp - 300) / 100; } private static FameEntry[] m_FameEntries = new FameEntry[] { new FameEntry( 1249, new KarmaEntry[] { new KarmaEntry( -10000, "{0} le Proscrit", "{0} la Proscrite" ), new KarmaEntry( -5000, "{0} le Meprisable", "{0} la Meprisable" ), new KarmaEntry( -2500, "{0} le Scelerat", "{0} la Scelerate" ), new KarmaEntry( -1250, "{0} le Repugnant", "{0} la Repugnante" ), new KarmaEntry( -625, "{0} le Rude", "{0} la Rude" ), new KarmaEntry( 624, "{0}", "{0}" ), new KarmaEntry( 1249, "{0} le Juste", "{0} la Juste" ), new KarmaEntry( 2499, "{0} l'Aimable", "{0} l'Aimable" ), new KarmaEntry( 4999, "{0} le Brave", "{0} la Brave"), new KarmaEntry( 9999, "{0} l'Honnete", "{0} l'Honnete" ), new KarmaEntry( 10000, "{0} le Fiable", "{0} la Fiable" ) } ), new FameEntry( 2499, new KarmaEntry[] { new KarmaEntry( -10000, "{0} le Miserable", "{0} la Miserable" ), new KarmaEntry( -5000, "{0} le Lache", "{0} la Lache" ), new KarmaEntry( -2500, "{0} le Malicieux", "{0} la Malicieuse" ), new KarmaEntry( -1250, "{0} le Deshonorable", "{0} la Deshonorable" ), new KarmaEntry( -625, "{0} le Minable", "{0} la Minable" ), new KarmaEntry( 624, "{0} le Notable", "{0} la Notable" ), new KarmaEntry( 1249, "{0} le Droit", "{0} la Droite" ), new KarmaEntry( 2499, "{0} le Respectable", "{0} la Respectable" ), new KarmaEntry( 4999, "{0} l'Honorable", "{0} l'Honorable" ), new KarmaEntry( 9999, "{0} le Louable", "{0} la Louable" ), new KarmaEntry( 10000, "{0} l'Estimable", "{0} l'Estimable" ) } ), new FameEntry( 4999, new KarmaEntry[] { new KarmaEntry( -10000, "{0} l'Infame", "{0} l'Infame" ), new KarmaEntry( -5000, "{0} le Cruel", "{0} la Cruelle" ), new KarmaEntry( -2500, "{0} le Vil", "{0} la Vile" ), new KarmaEntry( -1250, "{0} l'Ignoble", "{0} l'Ignoble" ), new KarmaEntry( -625, "{0} le Connu", "{0} la Connue" ), new KarmaEntry( 624, "{0} le Hautain", "{0} la Hautaine" ), new KarmaEntry( 1249, "{0} le Repute", "{0} la Reputee" ), new KarmaEntry( 2499, "{0} le Digne", "{0} la Digne" ), new KarmaEntry( 4999, "{0} l'Admirable", "{0} l'Admirable" ), new KarmaEntry( 9999, "{0} le Celebre", "{0} la Celebre" ), new KarmaEntry( 10000, "{0} le Grand", "{0} la Grande" ) } ), new FameEntry( 9999, new KarmaEntry[] { new KarmaEntry( -10000, "{0} le Terrible", "{0} la Terrible" ), new KarmaEntry( -5000, "{0} le Malfaisant", "{0} la Malfaisante" ), new KarmaEntry( -2500, "{0} le Sordide", "{0} la Sordide" ), new KarmaEntry( -1250, "{0} le Tenebreux", "{0} la Tenebreuse" ), new KarmaEntry( -625, "{0} le Sadique", "{0} la Sadique" ), new KarmaEntry( 624, "{0} le Fameux", "{0} la Fameuse" ), new KarmaEntry( 1249, "{0} le Distingue", "{0} la Distinguee" ), new KarmaEntry( 2499, "{0} l'Eminent", "{0} l'Eminente" ), new KarmaEntry( 4999, "{0} le Noble", "{0} la Noble" ), new KarmaEntry( 9999, "{0} l'Illustre", "{0} l'Illustre" ), new KarmaEntry( 10000, "{0} le Glorieux", "{0} la Glorieuse" ) } ), new FameEntry( 10000, new KarmaEntry[] { new KarmaEntry( -10000, "{1} {0} le Terrible", "{1} {0} la Terrible" ), new KarmaEntry( -5000, "{1} {0} le Malfaisant", "{1} {0} la Malfaisante" ), new KarmaEntry( -2500, "{1} {0} le Sombre", "{1} {0} la Sombre"), new KarmaEntry( -1250, "{1} {0} le Tenebreux", "{1} {0} la Tenebreuse"), new KarmaEntry( -625, "{1} {0} le Dechu", "{1} {0} la Dechue" ), new KarmaEntry( 624, "{1} {0}", "{1} {0}" ), new KarmaEntry( 1249, "{1} {0} le Distingue", "{1} {0} la Distinguee" ), new KarmaEntry( 2499, "{1} {0} l'Eminent", "{1} {0} l'Eminente" ), new KarmaEntry( 4999, "{1} {0} le Noble", "{1} {0} la Noble" ), new KarmaEntry( 9999, "{1} {0} l'Illustre", "{1} {0} l'Illustre" ), new KarmaEntry( 10000, "{1} {0} le Glorieux", "{1} {0} la Glorieuse" ) } ) }; } public class FameEntry { public int m_Fame; public KarmaEntry[] m_Karma; public FameEntry( int fame, KarmaEntry[] karma ) { m_Fame = fame; m_Karma = karma; } } public class KarmaEntry { public int m_Karma; public string m_Title; public string m_FTitle; public KarmaEntry( int karma, string title, string ftitle ) { m_Karma = karma; m_Title = title; m_FTitle = ftitle; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS namespace Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures { using System; using System.Collections.Generic; using System.Diagnostics; using Llvm.NET.Values; using Microsoft.Zelig.LLVM; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; public partial class LlvmForArmV7MCompilationState { private _BasicBlock m_basicBlock; private _BasicBlock GetOrInsertBasicBlock(IR.BasicBlock block) { _BasicBlock llvmBlock; if( m_blocks.TryGetValue( block, out llvmBlock ) ) { return llvmBlock; } llvmBlock = m_function.GetOrInsertBasicBlock( block.ToShortString( ) ); m_blocks.Add( block, llvmBlock ); return llvmBlock; } private _BasicBlock SplitCurrentBlock() { // REVIEW: This can result in chains of ".next.next.next...". In the future it may be // better to name these in a prettier fashion ".next1", ".next2", ... return m_function.GetOrInsertBasicBlock(m_basicBlock.Name + ".next"); } public override void EmitCodeForBasicBlock( IR.BasicBlock bb ) { #if GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS m_manager.TurnOffCompilationAndValidation( ); m_function.SetExternalLinkage( ); m_basicBlock = null; #else // GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS m_basicBlock = GetOrInsertBasicBlock( bb ); // If this is the entry block, set up local variable storage. if( bb == m_basicBlocks[ 0 ] ) { var defChains = m_cfg.DataFlow_DefinitionChains; var useChains = m_cfg.DataFlow_UseChains; foreach( IR.VariableExpression exp in m_variables ) { Debug.Assert( exp.SpanningTreeIndex >= 0, "Encountered unreachable expression; expected removal in prior phase: " + exp ); // Skip unused variables. These can exist when a value is aliased, but not otherwise referenced. if( ( defChains[exp.SpanningTreeIndex].Length == 0 ) && ( useChains[exp.SpanningTreeIndex].Length == 0 ) ) { continue; } Debug.Assert( !m_localValues.ContainsKey( exp ), "Found multiple definitions for expression: " + exp ); CreateValueCache( exp, defChains, useChains ); } } foreach( var op in bb.Operators ) { if ( EmitCodeForBasicBlock_ShouldSkip( op ) ) { continue; } TranslateOperator( op, bb ); } #endif // GENERATE_ONLY_TYPESYSTEM_AND_FUNCTION_DEFINITIONS } protected override bool EmitCodeForBasicBlock_ShouldSkip( IR.Operator op ) { return base.EmitCodeForBasicBlock_ShouldSkip( op ); } protected override uint EmitCodeForBasicBlock_EstimateMinimumSize( IR.Operator op ) { return sizeof(uint); } protected override void EmitCodeForBasicBlock_EmitOperator( IR.Operator op ) { throw new Exception( "EmitCodeForBasicBlock_EmitOperator not implemented." ); } protected override void EmitCodeForBasicBlock_FlushOperators( ) { } private void CreateValueCache(IR.VariableExpression expr, IR.Operator[][] defChains, IR.Operator[][] useChains) { Debug.Assert(expr.AliasedVariable == expr, "Aliased variables are currently unsupported."); // Get or create a slot for the backing variable. if (!m_localValues.ContainsKey(expr)) { ValueCache valueCache; if (RequiresAddress(expr, defChains, useChains)) { Value address = m_function.GetLocalStackValue(m_method, m_basicBlock, expr, m_manager); valueCache = new ValueCache(expr, address); } else { valueCache = new ValueCache(expr, m_manager.GetOrInsertType(expr.Type)); } m_localValues[expr] = valueCache; } } private bool RequiresAddress(IR.VariableExpression expr, IR.Operator[][] defChains, IR.Operator[][] useChains) { // LLVM needs an address to attach debug info, so give an address to all named variables. if (!string.IsNullOrWhiteSpace(expr.DebugName?.Name)) { return true; } // If the variable has more than one definition, give it an address instead of a phi node. if (defChains[expr.SpanningTreeIndex].Length > 1) { return true; } // If any operator takes the variable's address, it must be addressable. foreach (IR.Operator useOp in useChains[expr.SpanningTreeIndex]) { // Address assignment operators take their argument's address by definition. if (useOp is IR.AddressAssignmentOperator) { return true; } // Field accessors need the first argument to be an address, so value types need to stay indirected. if ((useOp is IR.StoreInstanceFieldOperator) || (useOp is IR.LoadInstanceFieldOperator) || (useOp is IR.LoadInstanceFieldAddressOperator)) { if ((expr == useOp.FirstArgument) && (expr.Type is TS.ValueTypeRepresentation)) { return true; } } } return false; } private Value GetImmediate(IR.BasicBlock block, IR.Expression expression) { return GetValue(block, expression, wantImmediate: true, allowLoad: true); } private Value GetAddress(IR.BasicBlock block, IR.Expression expression) { return GetValue(block, expression, wantImmediate: false, allowLoad: false); } private Value GetValue(IR.BasicBlock block, IR.Expression exp, bool wantImmediate, bool allowLoad) { if ( !IsSuitableForLLVMTranslation( exp ) ) { throw new System.InvalidOperationException( "Llilum output too low level." ); } if( exp is IR.VariableExpression ) { ValueCache valueCache = m_localValues[ exp ]; // If we don't need to load the value, just return the address. if( !wantImmediate ) { Debug.Assert( valueCache.IsAddressable ); return valueCache.Address; } // Never cache addressable values since we don't easily know when they'll be modified. // Instead, reload at each operator. Unnecessary loads will be optimized out by LLVM. if( valueCache.IsAddressable ) { return m_basicBlock.InsertLoad( valueCache.Address ); } // If we already have a cached value for this expression there's no need to load it again. Value value = valueCache.GetValueFromBlock(block); if (value != null) { return value; } // This value isn't addressable so it must have been set in a previous block. IR.BasicBlock idom = m_immediateDominators[ block.SpanningTreeIndex ]; if( idom == block ) { // This is the entry block so there's no predecessor to search. throw new InvalidOperationException( $"Encountered use of expression with no definition. Expression {exp} in {block.Owner.Method}" ); } value = GetValue(idom, exp, wantImmediate, allowLoad); valueCache.SetValueForBlock(block, value); return value; } if ( exp is IR.ConstantExpression ) { IR.ConstantExpression ce = ( IR.ConstantExpression )exp; if( ce.Value == null ) { Debug.Assert( wantImmediate, "Cannot take the address of a null constant." ); return m_manager.Module.GetNullValue( m_manager.GetOrInsertType( ce.Type ) ); } if( ce.Type.IsInteger || ce.Type.IsFloatingPoint ) { if( ce.SizeOfValue == 0 ) { throw new System.InvalidOperationException( "Scalar constant with 0 bits width." ); } Debug.Assert( wantImmediate, "Cannot take the address of a scalar constant." ); _Type scalarType = m_manager.GetOrInsertType( ce.Type ); object value = ce.Value; if( ce.Type.IsInteger ) { // Ensure integer types are converted to ulong. This will also catch enums and IntPtr/UIntPtr. ulong intValue; ce.GetAsRawUlong(out intValue); value = intValue; } return m_manager.Module.GetScalarConstant( scalarType, value ); } IR.DataManager.DataDescriptor dd = ce.Value as IR.DataManager.DataDescriptor; if( dd != null ) { Debug.Assert( wantImmediate || ( dd.Context is TS.ValueTypeRepresentation ), "Cannot take the address of a global object reference." ); // This call always returns a pointer to global storage, so value types may need to be loaded. Value value = m_manager.GlobalValueFromDataDescriptor(dd, true); if (wantImmediate && (dd.Context is TS.ValueTypeRepresentation)) { value = m_basicBlock.InsertLoad( value ); } return value; } throw new Exception( "Constant type not supported." ); } throw new Exception( "Expression type not supported." + exp ); } private void WarnUnimplemented( string msg ) { msg = "Unimplemented operator: " + msg; var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine( msg ); Console.ForegroundColor = color; //Trick to list in-code missing operators. //m_basicBlock.InsertASMString( "; " + msg ); } private void OutputStringInline( string str ) { m_basicBlock.InsertASMString( "####################################################" ); m_basicBlock.InsertASMString( "# " + str ); m_basicBlock.InsertASMString( "####################################################" ); } private void TranslateOperator( IR.Operator op, IR.BasicBlock bb ) { if( ShouldSkipOperator( op ) ) { return; } // Load Debug metadata // Miguel: (Hack to remove processor.cs epilogue/prologue debug data) if( op.DebugInfo != null && !op.DebugInfo.SrcFileName.EndsWith( "ProcessorARMv7M.cs" ) ) { m_basicBlock.SetDebugInfo( m_manager, m_method, op ); } OutputStringInline( op.ToString( ) ); //ALU if( op is IR.AbstractBinaryOperator ) { Translate_AbstractBinaryOperator( ( IR.AbstractBinaryOperator )op ); } else if( op is IR.AbstractUnaryOperator ) { //Todo: Add unary "Finite" operation, which in fact is "CKfinite" from the checks. Translate_AbstractUnaryOperator( ( IR.AbstractUnaryOperator )op ); } //Conversions else if( op is IR.ConversionOperator ) { Translate_ConversionOperator( ( IR.ConversionOperator )op ); } else if( op is IR.ConvertOperator ) { Translate_ConvertOperator( ( IR.ConvertOperator )op ); } //Store-Load operators else if( op is IR.SingleAssignmentOperator ) { Translate_SingleAssignmentOperator( ( IR.SingleAssignmentOperator )op ); } else if( op is IR.AddressAssignmentOperator ) { Translate_AddressAssignmentOperator( ( IR.AddressAssignmentOperator )op ); } else if( op is IR.InitialValueOperator ) { Translate_InitialValueOperator( ( IR.InitialValueOperator )op ); } else if( op is IR.CompareAndSetOperator ) { Translate_CompareAndSetOperator( ( IR.CompareAndSetOperator )op ); } else if( op is IR.LoadIndirectOperator ) { Translate_LoadIndirectOperator( ( IR.LoadIndirectOperator )op ); } else if( op is IR.StoreIndirectOperator ) { Translate_StoreIndirectOperator( ( IR.StoreIndirectOperator )op ); } else if( op is IR.StoreInstanceFieldOperator ) { Translate_StoreInstanceFieldOperator( ( IR.StoreInstanceFieldOperator )op ); } else if( op is IR.LoadInstanceFieldOperator ) { Translate_LoadInstanceFieldOperator( ( IR.LoadInstanceFieldOperator )op ); } else if( op is IR.LoadInstanceFieldAddressOperator ) { Translate_LoadInstanceFieldAddressOperator( ( IR.LoadInstanceFieldAddressOperator )op ); } else if( op is IR.StoreElementOperator ) { Translate_StoreElementOperator( ( IR.StoreElementOperator )op ); } else if( op is IR.LoadElementOperator ) { Translate_LoadElementOperator( ( IR.LoadElementOperator )op ); } else if( op is IR.LoadElementAddressOperator ) { Translate_LoadElementAddressOperator( ( IR.LoadElementAddressOperator )op ); } //Control flow operators else if( op is IR.UnconditionalControlOperator ) { Translate_UnconditionalControlOperator( ( IR.UnconditionalControlOperator )op ); } else if( op is IR.BinaryConditionalControlOperator ) { Translate_BinaryConditionalControlOperator( ( IR.BinaryConditionalControlOperator )op ); } else if( op is IR.CompareConditionalControlOperator ) { Translate_CompareConditionalControlOperator( ( IR.CompareConditionalControlOperator )op ); } else if( op is IR.MultiWayConditionalControlOperator ) { Translate_MultiWayConditionalControlOperator( ( IR.MultiWayConditionalControlOperator )op ); } else if( op is IR.ReturnControlOperator ) { Translate_ReturnControlOperator( ( IR.ReturnControlOperator )op ); } else if( op is IR.DeadControlOperator ) { Translate_DeadControlOperator( ( IR.DeadControlOperator )op ); } //Calls else if( op is IR.StaticCallOperator ) { Translate_StaticCallOperator( ( IR.StaticCallOperator )op ); } else if( op is IR.InstanceCallOperator ) { Translate_InstanceCallOperator( ( IR.InstanceCallOperator )op ); } else if( op is IR.IndirectCallOperator ) { Translate_IndirectCallOperator( ( IR.IndirectCallOperator )op ); } //Other else if (op is IR.LandingPadOperator) { Translate_LandingPadOperator((IR.LandingPadOperator)op); } else if (op is IR.ResumeUnwindOperator) { Translate_ResumeUnwindOperator((IR.ResumeUnwindOperator)op); } else { WarnUnimplemented( op.ToString( ) ); } } private static bool ShouldSkipOperator( IR.Operator op ) { if( ( op is IR.NullCheckOperator ) || ( op is IR.OutOfBoundCheckOperator ) || ( op is IR.CompilationConstraintsOperator ) || ( op is IR.NopOperator ) ) { return true; } return false; } private bool IsSuitableForLLVMTranslation( IR.Expression varExp ) { if( varExp is IR.PhysicalRegisterExpression || varExp is IR.StackLocationExpression ) { return false; } return true; } private void EnsureSameType(ref Value valA, ref Value valB) { _Type typeA = valA.GetDebugType(); _Type typeB = valB.GetDebugType(); if (typeA.IsPointer != typeB.IsPointer) { // Convert the pointer parameter to an integer to match the other. valA = ConvertValueToALUOperableType(valA); valB = ConvertValueToALUOperableType(valB); } else if (typeA.IsPointer) { // Ensure pointer types match. valB = m_basicBlock.InsertBitCast(valB, typeA); } if (typeA.IsInteger && typeB.IsInteger) { if (typeA.SizeInBits < typeB.SizeInBits) { if (typeA.IsSigned) { valA = m_basicBlock.InsertSExt(valA, typeB, typeA.SizeInBits); } else { valA = m_basicBlock.InsertZExt(valA, typeB, typeA.SizeInBits); } } else if (typeA.SizeInBits > typeB.SizeInBits) { if (typeA.IsSigned) { valB = m_basicBlock.InsertSExt(valB, typeA, typeB.SizeInBits); } else { valB = m_basicBlock.InsertZExt(valB, typeA, typeB.SizeInBits); } } } } private Value ConvertValueToALUOperableType(Value val) { // LLVM doesn't accept pointers as operands for arithmetic operations, so convert them to integers. if (val.NativeType.IsPointer) { _Type intPtrType = m_manager.GetOrInsertType(m_wkt.System_UInt32); return m_basicBlock.InsertPointerToInt(val, intPtrType); } return val; } private Value ConvertValueToStoreToTarget(Value val, _Type targetType) { // Trivial case: Value is already the desired type. We compare the inner types directly because the outer // types will be the same between pointer types for arrays and strings, while the inner types won't. if (val.NativeType == targetType.DebugType.NativeType) { return val; } _Type type = val.GetDebugType(); if (type.IsPointer && targetType.IsPointer) { return m_basicBlock.InsertBitCast(val, targetType); } if (type.IsInteger && targetType.IsInteger) { if (type.SizeInBits < targetType.SizeInBits) { if (type.IsSigned) { return m_basicBlock.InsertSExt(val, targetType, type.SizeInBits); } else { return m_basicBlock.InsertZExt(val, targetType, type.SizeInBits); } } if (type.SizeInBits > targetType.SizeInBits) { return m_basicBlock.InsertTrunc(val, targetType, type.SizeInBits); } return m_basicBlock.InsertBitCast(val, targetType); } if (type.IsInteger && targetType.IsPointer) { return m_basicBlock.InsertIntToPointer(val, targetType); } if (type.IsPointer && targetType.IsInteger) { return m_basicBlock.InsertPointerToInt(val, targetType); } if (type.IsFloatingPoint && targetType.IsFloatingPoint) { if (type.SizeInBits > targetType.SizeInBits) { return m_basicBlock.InsertFPTrunc(val, targetType); } else { return m_basicBlock.InsertFPExt(val, targetType); } } if (type.IsFloatingPoint && targetType.IsInteger) { return m_basicBlock.InsertFPToInt(val, targetType); } if (type.IsInteger && targetType.IsFloatingPoint) { return m_basicBlock.InsertIntToFP(val, targetType); } throw new InvalidOperationException("Invalid type cast."); } private void StoreValue(ValueCache dst, Value src, IR.BasicBlock block) { Value convertedSrc = ConvertValueToStoreToTarget(src, dst.Type); m_basicBlock.SetVariableName( convertedSrc, dst.Expression ); if( dst.IsAddressable ) { StoreValue( dst.Address, convertedSrc ); } else { dst.SetValueForBlock(block, convertedSrc); } } private void StoreValue(Value dst, Value src) { m_basicBlock.InsertStore(ConvertValueToStoreToTarget(src, dst.GetUnderlyingType()), dst); } private void Translate_AbstractBinaryOperator(IR.AbstractBinaryOperator op) { if (!(op is IR.BinaryOperator)) { throw new Exception("Unhandled Binary Op: " + op); } Value valA = GetImmediate(op.BasicBlock, op.FirstArgument); Value valB = GetImmediate(op.BasicBlock, op.SecondArgument); valA = ConvertValueToALUOperableType(valA); valB = ConvertValueToALUOperableType(valB); // TODO: Add support for overflow exceptions. EnsureSameType(ref valA, ref valB); Value result = m_basicBlock.InsertBinaryOp((int)op.Alu, valA, valB, op.Signed); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_AbstractUnaryOperator(IR.AbstractUnaryOperator op) { if (!(op is IR.UnaryOperator)) { throw new Exception("Unhandled Unary Op: " + op); } // TODO: Add support for overflow exceptions. Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = ConvertValueToALUOperableType(argument); Value result = m_basicBlock.InsertUnaryOp((int)op.Alu, value, op.Signed); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_ConversionOperator( IR.ConversionOperator op ) { // TODO: Add support for overflow exceptions Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = ConvertValueToALUOperableType(argument); _Type resultType = m_manager.GetOrInsertType( op.FirstResult.Type ); if( op.FirstResult.Type == m_wkt.System_IntPtr || op.FirstResult.Type == m_wkt.System_UIntPtr || op.FirstResult.Type is TS.PointerTypeRepresentation ) { resultType = m_manager.GetOrInsertType( m_wkt.System_UInt32 ); } if( op is IR.ZeroExtendOperator ) { value = m_basicBlock.InsertZExt( value, resultType, 8 * ( int )op.SignificantSize ); } else if( op is IR.SignExtendOperator ) { value = m_basicBlock.InsertSExt( value, resultType, 8 * ( int )op.SignificantSize ); } else if( op is IR.TruncateOperator ) { value = m_basicBlock.InsertTrunc( value, resultType, 8 * ( int )op.SignificantSize ); } else { throw new Exception( "Unimplemented Conversion Operator: " + op.ToString( ) ); } StoreValue(m_localValues[ op.FirstResult ], value, op.BasicBlock); } private void Translate_ConvertOperator(IR.ConvertOperator op) { // TODO: Add support for overflow exceptions Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], argument, op.BasicBlock); } private void Translate_SingleAssignmentOperator(IR.SingleAssignmentOperator op) { Value value = GetImmediate(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_AddressAssignmentOperator(IR.AddressAssignmentOperator op) { Value address = GetAddress(op.BasicBlock, op.FirstArgument); StoreValue(m_localValues[op.FirstResult], address, op.BasicBlock); } private void Translate_InitialValueOperator( IR.InitialValueOperator op ) { int index = op.FirstResult.Number; if (m_method is TS.StaticMethodRepresentation) { --index; } _Type type = m_manager.GetOrInsertType( op.FirstResult.Type ); Value argument = m_basicBlock.GetMethodArgument(index, type); StoreValue(m_localValues[ op.FirstResult ], argument, op.BasicBlock); } private void Translate_CompareAndSetOperator(IR.CompareAndSetOperator op) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value right = GetImmediate(op.BasicBlock, op.SecondArgument); EnsureSameType(ref left, ref right); Value value = m_basicBlock.InsertCmp((int)op.Condition, op.Signed, left, right); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadIndirectOperator(IR.LoadIndirectOperator op) { Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value address = m_basicBlock.LoadIndirect(argument, m_manager.GetOrInsertType(op.Type)); Value value = m_basicBlock.InsertLoad(address); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_StoreIndirectOperator(IR.StoreIndirectOperator op) { Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); Value value = GetImmediate(op.BasicBlock, op.SecondArgument); Value address = m_basicBlock.LoadIndirect(argument, m_manager.GetOrInsertType(op.Type)); StoreValue(address, value); } private Value GetInstanceAddress(IR.FieldOperator op) { IR.Expression instance = op.FirstArgument; if (instance.Type is TS.ValueTypeRepresentation) { return GetAddress( op.BasicBlock, instance ); } else { return GetImmediate( op.BasicBlock, instance ); } } private void Translate_StoreInstanceFieldOperator(IR.StoreInstanceFieldOperator op) { Value objAddress = GetInstanceAddress(op); Value value = GetImmediate(op.BasicBlock, op.SecondArgument); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); StoreValue(fieldAddress, value); } private void Translate_LoadInstanceFieldOperator(IR.LoadInstanceFieldOperator op) { Value objAddress = GetInstanceAddress(op); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); Value value = m_basicBlock.InsertLoad(fieldAddress); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadInstanceFieldAddressOperator(IR.LoadInstanceFieldAddressOperator op) { Value objAddress = GetInstanceAddress(op); _Type fieldType = m_manager.GetOrInsertType(op.Field.FieldType); Value fieldAddress = m_basicBlock.GetFieldAddress(objAddress, op.Field.Offset, fieldType); StoreValue(m_localValues[op.FirstResult], fieldAddress, op.BasicBlock); } private Value GetElementAddress(IR.ElementOperator op) { var arrayType = (TS.ArrayReferenceTypeRepresentation)op.FirstArgument.Type; _Type elementType = m_manager.GetOrInsertType(arrayType.ContainedType); Value array = GetImmediate(op.BasicBlock, op.FirstArgument); Value nativeArray = m_basicBlock.GetFieldAddress(array, (int)m_wkt.System_Array.Size, null); Value index = GetImmediate(op.BasicBlock, op.SecondArgument); Value aluIndex = ConvertValueToALUOperableType(index); return m_basicBlock.IndexLLVMArray(nativeArray, aluIndex, elementType); } private void Translate_LoadElementOperator(IR.LoadElementOperator op) { Value elementAddress = GetElementAddress(op); Value value = m_basicBlock.InsertLoad(elementAddress); StoreValue(m_localValues[op.FirstResult], value, op.BasicBlock); } private void Translate_LoadElementAddressOperator(IR.LoadElementAddressOperator op) { Value elementAddress = GetElementAddress(op); StoreValue(m_localValues[op.FirstResult], elementAddress, op.BasicBlock); } private void Translate_StoreElementOperator(IR.StoreElementOperator op) { Value elementAddress = GetElementAddress(op); Value value = GetImmediate(op.BasicBlock, op.ThirdArgument); StoreValue(elementAddress, value); } private void Translate_UnconditionalControlOperator( IR.UnconditionalControlOperator op ) { m_basicBlock.InsertUnconditionalBranch( GetOrInsertBasicBlock( op.TargetBranch ) ); } private void Translate_BinaryConditionalControlOperator( IR.BinaryConditionalControlOperator op ) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value zero = m_manager.Module.GetNullValue(left.GetDebugType()); Value condition = m_basicBlock.InsertCmp((int)IR.CompareAndSetOperator.ActionCondition.NE, false, left, zero); _BasicBlock taken = GetOrInsertBasicBlock( op.TargetBranchTaken ); _BasicBlock notTaken = GetOrInsertBasicBlock( op.TargetBranchNotTaken ); m_basicBlock.InsertConditionalBranch( condition, taken, notTaken ); } private void Translate_CompareConditionalControlOperator(IR.CompareConditionalControlOperator op) { Value left = GetImmediate(op.BasicBlock, op.FirstArgument); Value right = GetImmediate(op.BasicBlock, op.SecondArgument); EnsureSameType(ref left, ref right); Value condition = m_basicBlock.InsertCmp((int)op.Condition, op.Signed, left, right); _BasicBlock taken = GetOrInsertBasicBlock(op.TargetBranchTaken); _BasicBlock notTaken = GetOrInsertBasicBlock(op.TargetBranchNotTaken); m_basicBlock.InsertConditionalBranch(condition, taken, notTaken); } private void Translate_MultiWayConditionalControlOperator( IR.MultiWayConditionalControlOperator op ) { List<int> caseValues = new List<int>(); List<_BasicBlock> caseBBs = new List<_BasicBlock>(); for( int i = 0; i < op.Targets.Length; ++i ) { caseValues.Add( i ); caseBBs.Add( GetOrInsertBasicBlock( op.Targets[ i ] ) ); } Value argument = GetImmediate(op.BasicBlock, op.FirstArgument); _BasicBlock defaultBlock = GetOrInsertBasicBlock( op.TargetBranchNotTaken ); m_basicBlock.InsertSwitchAndCases( argument, defaultBlock, caseValues, caseBBs ); } private void Translate_ReturnControlOperator( IR.ReturnControlOperator op ) { switch( op.Arguments.Length ) { case 0: m_basicBlock.InsertRet( null ); break; case 1: Value result = GetImmediate(op.BasicBlock, op.FirstArgument); m_basicBlock.InsertRet( result ); break; default: throw new System.InvalidOperationException( "ReturnControlOperator with more than one arg not supported. " + op ); } } private void Translate_DeadControlOperator( IR.DeadControlOperator op ) { // Basic Block marked as dead code by Zelig. m_basicBlock.InsertUnreachable(); } private bool ReplaceMethodCallWithIntrinsic( TS.MethodRepresentation method, List<Value> convertedArgs, out Value result ) { TS.WellKnownMethods wkm = m_cfg.TypeSystem.WellKnownMethods; result = null; // System.Buffer.InternalMemoryCopy(byte*, byte*, int) => llvm.memcpy // System.Buffer.InternalBackwardMemoryCopy(byte*, byte*, int) => llvm.memmove if ( method == wkm.System_Buffer_InternalMemoryCopy //////|| method == wkm.System_Buffer_InternalBackwardMemoryCopy ) { bool overlapping = method != wkm.System_Buffer_InternalMemoryCopy; Value src = convertedArgs[0]; Value dst = convertedArgs[1]; Value size = convertedArgs[2]; m_basicBlock.InsertMemCpy(dst, src, size, overlapping); return true; } // Microsoft.Zelig.Runtime.Memory.Fill(byte*, int, byte) => llvm.memset if (method == wkm.Microsoft_Zelig_Runtime_Memory_Fill) { Value dst = convertedArgs[0]; Value size = convertedArgs[1]; Value value = convertedArgs[2]; m_basicBlock.InsertMemSet(dst, value, size); return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalAdd(ref int, int) => llvm.atomicrmw add // Note: there's no built-in support for 64bit interlocked methods at the moment. if (method == wkm.InterlockedImpl_InternalAdd_int) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; Value oldVal = m_basicBlock.InsertAtomicAdd(ptr, val); // Because LLVM atomicrmw returns the old value, in order to match the behavior of Interlocked.Add // We need to calculate the new value to return. result = m_basicBlock.InsertBinaryOp((int)IR.BinaryOperator.ALU.ADD, oldVal, val, true); return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref int, int) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref float, float) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref IntPtr, IntPtr) => llvm.atomicrmw xchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalExchange(ref T, T) => llvm.atomicrmw xchg // Note: there's no built-in support for 64bit interlocked methods at the moment. if ((method == wkm.InterlockedImpl_InternalExchange_int) || (method == wkm.InterlockedImpl_InternalExchange_float) || (method == wkm.InterlockedImpl_InternalExchange_IntPtr) || (method.IsGenericInstantiation && method.GenericTemplate == wkm.InterlockedImpl_InternalExchange_Template)) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; _Type type = val.GetDebugType(); // AtomicXchg only supports integer types, so need to convert them if necessary _Type intType = m_manager.GetOrInsertType( m_wkt.System_Int32 ); _Type intPtrType = m_manager.Module.GetOrInsertPointerType( intType ); if(!type.IsInteger) { ptr = m_basicBlock.InsertBitCast( ptr, intPtrType ); if(type.IsPointer) { val = m_basicBlock.InsertPointerToInt( val, intType ); } else { val = m_basicBlock.InsertBitCast( val, intType ); } } result = m_basicBlock.InsertAtomicXchg( ptr, val ); if (result.GetDebugType() != type) { if(type.IsPointer) { result = m_basicBlock.InsertIntToPointer( result, type ); } else { result = m_basicBlock.InsertBitCast( result, type ); } } return true; } // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref int, int, int) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref float, float, float) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref IntPtr, IntPtr, IntPtr) => llvm.compxchg // Microsoft.Zelig.Runtime.InterlockedImpl.InternalCompareExchange(ref T, T, T) => llvm.compxchg // Note: there's no built-in support for 64bit interlocked methods at the moment. if ((method == wkm.InterlockedImpl_InternalCompareExchange_int) || (method == wkm.InterlockedImpl_InternalCompareExchange_float) || (method == wkm.InterlockedImpl_InternalCompareExchange_IntPtr) || (method.IsGenericInstantiation && method.GenericTemplate == wkm.InterlockedImpl_InternalCompareExchange_Template)) { Value ptr = convertedArgs[0]; Value val = convertedArgs[1]; Value cmp = convertedArgs[2]; _Type type = val.GetDebugType(); // AtomicCmpXchg only supports integer types, so need to convert them if necessary _Type intType = m_manager.GetOrInsertType( m_wkt.System_Int32 ); _Type intPtrType = m_manager.Module.GetOrInsertPointerType( intType ); if(!type.IsInteger) { ptr = m_basicBlock.InsertBitCast( ptr, intPtrType ); if(type.IsPointer) { val = m_basicBlock.InsertPointerToInt( val, intType ); cmp = m_basicBlock.InsertPointerToInt( cmp, intType ); } else { val = m_basicBlock.InsertBitCast( val, intType ); cmp = m_basicBlock.InsertBitCast( cmp, intType ); } } result = m_basicBlock.InsertAtomicCmpXchg( ptr, cmp, val ); if (result.GetDebugType() != type) { if(type.IsPointer) { result = m_basicBlock.InsertIntToPointer( result, type ); } else { result = m_basicBlock.InsertBitCast( result, type ); } } return true; } return false; } private void BuildMethodCallInstructions(IR.CallOperator op) { List<Value> args = new List<Value>(); TS.MethodRepresentation method = op.TargetMethod; int firstArgument = (method is TS.StaticMethodRepresentation) ? 1 : 0; int indirectAdjust = 0; bool callIndirect = op is IR.IndirectCallOperator; if (callIndirect) { firstArgument = ((IR.IndirectCallOperator)op).IsInstanceCall ? 0 : 1; indirectAdjust = 1; } for (int i = firstArgument; i < method.ThisPlusArguments.Length; ++i) { TS.TypeRepresentation typeRep = method.ThisPlusArguments[i]; _Type type = m_manager.GetOrInsertType(typeRep); Value argument = GetImmediate(op.BasicBlock, op.Arguments[i + indirectAdjust]); Value convertedArg = ConvertValueToStoreToTarget(argument, type); args.Add(convertedArg); } Value result; if (!ReplaceMethodCallWithIntrinsic(method, args, out result)) { _Type returnType = m_manager.GetOrInsertType(method.ReturnType); Value callAddress; if (callIndirect) { callAddress = GetImmediate(op.BasicBlock, op.Arguments[0]); } else { _Function targetFunc = m_manager.GetOrInsertFunction(method); if (method.Flags.HasFlag(TS.MethodRepresentation.Attributes.PinvokeImpl)) { targetFunc.SetExternalLinkage(); } callAddress = targetFunc.LlvmFunction; } // If this call is protected by a landing pad, replace it with an invoke instruction. if ((op.BasicBlock.ProtectedBy.Length > 0) && op.MayThrow) { _BasicBlock nextBlock = SplitCurrentBlock(); _BasicBlock catchBlock = GetOrInsertBasicBlock(op.BasicBlock.ProtectedBy[0]); result = m_basicBlock.InsertInvoke(callAddress, returnType, args, callIndirect, nextBlock, catchBlock); m_basicBlock = nextBlock; EnsurePersonalityFunction(); } else { result = m_basicBlock.InsertCall(callAddress, returnType, args, callIndirect); } } if (op.Results.Length == 1) { StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } else if (op.Results.Length > 1) { throw new System.InvalidOperationException("More than one return values are not handled."); } } private void Translate_StaticCallOperator(IR.StaticCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_InstanceCallOperator(IR.InstanceCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_IndirectCallOperator(IR.IndirectCallOperator op) { BuildMethodCallInstructions(op); } private void Translate_LandingPadOperator(IR.LandingPadOperator op) { EnsurePersonalityFunction(); var vtables = new Value[op.Arguments.Length]; for (int i = 0; i < op.Arguments.Length; ++i) { var vtable = GetImmediate(op.BasicBlock, op.Arguments[i]); // BUGBUG: LLVM appears to have an issue with type-info pointers where GEP constant // expressions resolve to null. To work around this problem, we emit the "wrapped" // global with the object header and adjust to the real VTable pointer in the // personality routine. var vtableAsConst = (Constant)vtable; if (vtableAsConst.Operands.Count != 0) { vtable = vtableAsConst.Operands[0]; } vtables[i] = vtable; } _Type resultType = m_manager.GetOrInsertType(op.FirstResult.Type); Value result = m_basicBlock.InsertLandingPad(resultType, vtables, op.HasCleanupClause); StoreValue(m_localValues[op.FirstResult], result, op.BasicBlock); } private void Translate_ResumeUnwindOperator(IR.ResumeUnwindOperator op) { Value exception = GetImmediate(op.BasicBlock, op.FirstArgument); m_basicBlock.InsertResume(exception); } // Ensure that the currently emitting function has a personality function attached. private void EnsurePersonalityFunction() { m_function.LlvmFunction.PersonalityFunction = m_manager.Module.GetPersonalityFunction("LLOS_Personality"); } } }
// $Id$ // // 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 Org.Apache.Etch.Bindings.Csharp.Msg; using NUnit.Framework; namespace Org.Apache.Etch.Bindings.Csharp.Support { [TestFixture] public class TestValidator_string { private readonly ValueFactory vf = new DummyValueFactory(); [TestFixtureSetUp] public void First() { Console.WriteLine(); Console.Write( "TestValidator_string" ); } [Test] public void constructor1() { testconstructor( 0, "string[0]", typeof(string) ); testconstructor( 1, "string[1]", typeof(string[])); testconstructor( 2, "string[2]", typeof(string[][]) ); testconstructor( 3, "string[3]", typeof(string[][][]) ); testconstructor( 4, "string[4]", typeof(string[][][][])); testconstructor( 5, "string[5]", typeof(string[][][][][]) ); testconstructor( 6, "string[6]", typeof(string[][][][][][]) ); testconstructor( 7, "string[7]", typeof(string[][][][][][][]) ); testconstructor( 8, "string[8]", typeof(string[][][][][][][][]) ); testconstructor( 9, "string[9]", typeof(string[][][][][][][][][]) ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testconstructor( int n, string descr, Type expectedClass ) { TypeValidator v = Validator_string.Get( n ); Assert.AreEqual( n, v.GetNDims() ); Assert.AreSame( expectedClass, v.GetExpectedClass() ); Assert.AreEqual( descr, v.ToString() ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void constructor2() { Validator_string.Get( -1 ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void constructor3() { Validator_string.Get( Validator.MAX_NDIMS+1 ); } /** @ */ [Test] public void elementvalidator1() { testelementvalidator( 1, "string[0]", typeof(string) ); testelementvalidator( 2, "string[1]", typeof(string[]) ); testelementvalidator( 3, "string[2]", typeof(string[][]) ); testelementvalidator( 4, "string[3]", typeof(string[][][]) ); testelementvalidator( 5, "string[4]", typeof(string[][][][]) ); testelementvalidator( 6, "string[5]", typeof(string[][][][][]) ); testelementvalidator( 7, "string[6]", typeof(string[][][][][][]) ); testelementvalidator( 8, "string[7]", typeof(string[][][][][][][]) ); testelementvalidator(9, "string[8]", typeof(string[][][][][][][][])); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testelementvalidator( int n, string descr, Type expectedClass ) { TypeValidator v = (TypeValidator) Validator_string.Get( n ).ElementValidator(); Assert.AreEqual( n-1, v.GetNDims() ); Assert.AreSame( expectedClass, v.GetExpectedClass() ); Assert.AreEqual( descr, v.ToString() ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void elementvalidator2() { Validator_string.Get( 0 ).ElementValidator(); } /** @ */ [Test] public void good_scalar() { testgoodvalue( 0, "" ); testgoodvalue( 0, "abc" ); } /** @ */ [Test] public void good_array() { testgoodvalue( 1, new string[] {} ); testgoodvalue( 2, new string[][] {} ); testgoodvalue( 3, new string[][][] {} ); testgoodvalue( 4, new string[][][][] {} ); testgoodvalue( 5, new string[][][][][] {} ); testgoodvalue( 6, new string[][][][][][] {} ); testgoodvalue( 7, new string[][][][][][][] {} ); testgoodvalue( 8, new string[][][][][][][][] {} ); testgoodvalue( 9, new string[][][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testgoodvalue( int n, Object value ) { TypeValidator v = Validator_string.Get( n ); Assert.IsTrue( v.Validate( value ) ); Assert.IsTrue( validateValueOk( v, value ) ); } /** @ */ [Test] public void bad_scalar() { testbadvalue( 0, null ); testbadvalue( 0, false ); testbadvalue( 0, true ); testbadvalue( 0, (byte) 1 ); testbadvalue( 0, (short) 2222 ); testbadvalue( 0, 33333333 ); testbadvalue( 0, 4444444444444444L ); testbadvalue( 0, 5.5f ); testbadvalue( 0, 6.6 ); // testbadvalue( 0, "" ); // good! // testbadvalue( 0, "abc" ); // good! testbadvalue( 0, new Object() ); testbadvalue( 0, new StructValue( new XType( "abc" ), vf ) ); testbadvalue( 0, new DateTime() ); testbadvalue( 1, null ); testbadvalue( 1, false ); testbadvalue( 1, true ); testbadvalue( 1, (byte) 1 ); testbadvalue( 1, (short) 2222 ); testbadvalue( 1, 333333 ); testbadvalue( 1, 4444444444444444L ); testbadvalue( 1, 5.5f ); testbadvalue( 1, 6.6 ); testbadvalue( 1, "" ); testbadvalue( 1, "abc" ); testbadvalue( 1, new Object() ); testbadvalue(1, new StructValue(new XType("abc"), vf)); testbadvalue( 1, new DateTime() ); } /** @ */ [Test] public void bad_array() { testbadvalue( 0, new string[] {} ); testbadvalue( 1, new string[][] {} ); testbadvalue( 2, new string[][][] {} ); testbadvalue( 3, new string[][][][] {} ); testbadvalue( 4, new string[][][][][] {} ); testbadvalue( 5, new string[][][][][][] {} ); testbadvalue( 6, new string[][][][][][][] {} ); testbadvalue( 7, new string[][][][][][][][] {} ); testbadvalue( 8, new string[][][][][][][][][] {} ); testbadvalue( 9, new string[][][][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); testbadvalue( 2, new string[] {} ); testbadvalue( 3, new string[][] {} ); testbadvalue( 4, new string[][][] {} ); testbadvalue( 5, new string[][][][] {} ); testbadvalue( 6, new string[][][][][] {} ); testbadvalue( 7, new string[][][][][][] {} ); testbadvalue( 8, new string[][][][][][][] {} ); testbadvalue( 9, new string[][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testbadvalue( int n, Object value ) { TypeValidator v = Validator_string.Get( n ); Assert.IsFalse( v.Validate( value ) ); Assert.IsFalse( validateValueOk( v, value ) ); } private bool validateValueOk( Validator v, Object value ) { try { Object x = v.ValidateValue( value ); Assert.AreEqual( value, x ); return true; } catch ( Exception ) { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class CertificateValidationClientServer : IDisposable { private readonly X509Certificate2 _clientCertificate; private readonly X509Certificate2Collection _clientCertificateCollection; private readonly X509Certificate2 _serverCertificate; private readonly X509Certificate2Collection _serverCertificateCollection; private bool _clientCertificateRemovedByFilter; public CertificateValidationClientServer() { _serverCertificateCollection = Configuration.Certificates.GetServerCertificateCollection(); _serverCertificate = Configuration.Certificates.GetServerCertificate(); _clientCertificateCollection = Configuration.Certificates.GetClientCertificateCollection(); _clientCertificate = Configuration.Certificates.GetClientCertificate(); } public void Dispose() { _serverCertificate.Dispose(); _clientCertificate.Dispose(); foreach (X509Certificate2 cert in _serverCertificateCollection) cert.Dispose(); foreach (X509Certificate2 cert in _clientCertificateCollection) cert.Dispose(); } [Theory] [InlineData(false)] [InlineData(true)] public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback) { IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0); var server = new TcpListener(endPoint); server.Start(); _clientCertificateRemovedByFilter = false; if (PlatformDetection.IsWindows7 && !useClientSelectionCallback && !Capability.IsTrustedRootCertificateInstalled()) { // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2 // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed: // The behavior to send the Trusted Issuers List by default is off. // // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built // by the server using certificates from the Trusted Root Authorities certificate store. // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates. _clientCertificateRemovedByFilter = true; } using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6)) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); Assert.True( Task.WaitAll( new Task[] { clientConnect, serverAccept }, TestConfiguration.PassingTestTimeoutMilliseconds), "Client/Server TCP Connect timed out."); LocalCertificateSelectionCallback clientCertCallback = null; if (useClientSelectionCallback) { clientCertCallback = ClientCertSelectionCallback; } using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream( clientConnection.GetStream(), false, ClientSideRemoteServerCertificateValidation, clientCertCallback)) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, ServerSideRemoteClientCertificateValidation)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCerts = new X509CertificateCollection(); if (!useClientSelectionCallback) { clientCerts.Add(_clientCertificate); } Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, clientCerts, SslProtocolSupport.DefaultSslProtocols, false); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, SslProtocolSupport.DefaultSslProtocols, false); Assert.True( Task.WaitAll( new Task[] { clientAuthentication, serverAuthentication }, TestConfiguration.PassingTestTimeoutMilliseconds), "Client/Server Authentication timed out."); if (!_clientCertificateRemovedByFilter) { Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject); } else { Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Null(sslServerStream.RemoteCertificate); } Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject); } } } private X509Certificate ClientCertSelectionCallback( object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return _clientCertificate; } private bool ServerSideRemoteClientCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { if (!_clientCertificateRemovedByFilter) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } else { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateNotAvailable; } } else { // Validate only if we're able to build a trusted chain. CertificateChainValidation.Validate(_clientCertificateCollection, chain); } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (!_clientCertificateRemovedByFilter) { Assert.Equal(_clientCertificate, certificate); } return true; } private bool ClientSideRemoteServerCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } else { // Validate only if we're able to build a trusted chain. CertificateChainValidation.Validate(_serverCertificateCollection, chain); } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); Assert.Equal(_serverCertificate, certificate); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Extensions; using Castle.Core.Internal; namespace Abp.Notifications { /// <summary> /// Used to distribute notifications to users. /// </summary> public class DefaultNotificationDistributer : DomainService, INotificationDistributer { private readonly INotificationConfiguration _notificationConfiguration; private readonly INotificationDefinitionManager _notificationDefinitionManager; private readonly INotificationStore _notificationStore; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IGuidGenerator _guidGenerator; private readonly IIocResolver _iocResolver; /// <summary> /// Initializes a new instance of the <see cref="NotificationDistributionJob"/> class. /// </summary> public DefaultNotificationDistributer( INotificationConfiguration notificationConfiguration, INotificationDefinitionManager notificationDefinitionManager, INotificationStore notificationStore, IUnitOfWorkManager unitOfWorkManager, IGuidGenerator guidGenerator, IIocResolver iocResolver) { _notificationConfiguration = notificationConfiguration; _notificationDefinitionManager = notificationDefinitionManager; _notificationStore = notificationStore; _unitOfWorkManager = unitOfWorkManager; _guidGenerator = guidGenerator; _iocResolver = iocResolver; } public virtual async Task DistributeAsync(Guid notificationId) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var notificationInfo = await _notificationStore.GetNotificationOrNullAsync(notificationId); if (notificationInfo == null) { Logger.Warn( "NotificationDistributionJob can not continue since could not found notification by id: " + notificationId ); return; } var users = await GetUsersAsync(notificationInfo); var userNotifications = await SaveUserNotificationsAsync(users, notificationInfo); await _notificationStore.DeleteNotificationAsync(notificationInfo); await NotifyAsync(userNotifications.ToArray()); }); } protected virtual async Task<UserIdentifier[]> GetUsersAsync(NotificationInfo notificationInfo) { List<UserIdentifier> userIds; if (!notificationInfo.UserIds.IsNullOrEmpty()) { //Directly get from UserIds userIds = notificationInfo .UserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .Where(uid => SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, uid.TenantId, uid.UserId)) .ToList(); } else { //Get subscribed users var tenantIds = GetTenantIds(notificationInfo); List<NotificationSubscriptionInfo> subscriptions; if (tenantIds.IsNullOrEmpty() || (tenantIds.Length == 1 && tenantIds[0] == NotificationInfo.AllTenantIds.To<int>())) { //Get all subscribed users of all tenants subscriptions = await _notificationStore.GetSubscriptionsAsync( notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } else { //Get all subscribed users of specified tenant(s) subscriptions = await _notificationStore.GetSubscriptionsAsync( tenantIds, notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } //Remove invalid subscriptions var invalidSubscriptions = new Dictionary<Guid, NotificationSubscriptionInfo>(); //TODO: Group subscriptions per tenant for potential performance improvement foreach (var subscription in subscriptions) { using (CurrentUnitOfWork.SetTenantId(subscription.TenantId)) { if (!await _notificationDefinitionManager.IsAvailableAsync(notificationInfo.NotificationName, new UserIdentifier(subscription.TenantId, subscription.UserId)) || !SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, subscription.TenantId, subscription.UserId)) { invalidSubscriptions[subscription.Id] = subscription; } } } subscriptions.RemoveAll(s => invalidSubscriptions.ContainsKey(s.Id)); //Get user ids userIds = subscriptions .Select(s => new UserIdentifier(s.TenantId, s.UserId)) .ToList(); } if (!notificationInfo.ExcludedUserIds.IsNullOrEmpty()) { //Exclude specified users. var excludedUserIds = notificationInfo .ExcludedUserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .ToList(); userIds.RemoveAll(uid => excludedUserIds.Any(euid => euid.Equals(uid))); } return userIds.ToArray(); } protected virtual UserIdentifier[] GetUsers(NotificationInfo notificationInfo) { return _unitOfWorkManager.WithUnitOfWork(() => { List<UserIdentifier> userIds; if (!notificationInfo.UserIds.IsNullOrEmpty()) { //Directly get from UserIds userIds = notificationInfo .UserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .Where(uid => SettingManager.GetSettingValueForUser<bool>(NotificationSettingNames.ReceiveNotifications, uid.TenantId, uid.UserId)) .ToList(); } else { //Get subscribed users var tenantIds = GetTenantIds(notificationInfo); List<NotificationSubscriptionInfo> subscriptions; if (tenantIds.IsNullOrEmpty() || (tenantIds.Length == 1 && tenantIds[0] == NotificationInfo.AllTenantIds.To<int>())) { //Get all subscribed users of all tenants subscriptions = _notificationStore.GetSubscriptions( notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } else { //Get all subscribed users of specified tenant(s) subscriptions = _notificationStore.GetSubscriptions( tenantIds, notificationInfo.NotificationName, notificationInfo.EntityTypeName, notificationInfo.EntityId ); } //Remove invalid subscriptions var invalidSubscriptions = new Dictionary<Guid, NotificationSubscriptionInfo>(); //TODO: Group subscriptions per tenant for potential performance improvement foreach (var subscription in subscriptions) { using (CurrentUnitOfWork.SetTenantId(subscription.TenantId)) { if (!_notificationDefinitionManager.IsAvailable(notificationInfo.NotificationName, new UserIdentifier(subscription.TenantId, subscription.UserId)) || !SettingManager.GetSettingValueForUser<bool>( NotificationSettingNames.ReceiveNotifications, subscription.TenantId, subscription.UserId)) { invalidSubscriptions[subscription.Id] = subscription; } } } subscriptions.RemoveAll(s => invalidSubscriptions.ContainsKey(s.Id)); //Get user ids userIds = subscriptions .Select(s => new UserIdentifier(s.TenantId, s.UserId)) .ToList(); } if (!notificationInfo.ExcludedUserIds.IsNullOrEmpty()) { //Exclude specified users. var excludedUserIds = notificationInfo .ExcludedUserIds .Split(",") .Select(uidAsStr => UserIdentifier.Parse(uidAsStr)) .ToList(); userIds.RemoveAll(uid => excludedUserIds.Any(euid => euid.Equals(uid))); } return userIds.ToArray(); }); } private static int?[] GetTenantIds(NotificationInfo notificationInfo) { if (notificationInfo.TenantIds.IsNullOrEmpty()) { return null; } return notificationInfo .TenantIds .Split(",") .Select(tenantIdAsStr => tenantIdAsStr == "null" ? (int?) null : (int?) tenantIdAsStr.To<int>()) .ToArray(); } protected virtual async Task<List<UserNotification>> SaveUserNotificationsAsync(UserIdentifier[] users, NotificationInfo notificationInfo) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var userNotifications = new List<UserNotification>(); var tenantGroups = users.GroupBy(user => user.TenantId); foreach (var tenantGroup in tenantGroups) { using (_unitOfWorkManager.Current.SetTenantId(tenantGroup.Key)) { var tenantNotificationInfo = new TenantNotificationInfo(_guidGenerator.Create(), tenantGroup.Key, notificationInfo); await _notificationStore.InsertTenantNotificationAsync(tenantNotificationInfo); await _unitOfWorkManager.Current.SaveChangesAsync(); //To get tenantNotification.Id. var tenantNotification = tenantNotificationInfo.ToTenantNotification(); foreach (var user in tenantGroup) { var userNotification = new UserNotificationInfo(_guidGenerator.Create()) { TenantId = tenantGroup.Key, UserId = user.UserId, TenantNotificationId = tenantNotificationInfo.Id }; await _notificationStore.InsertUserNotificationAsync(userNotification); userNotifications.Add(userNotification.ToUserNotification(tenantNotification)); } await CurrentUnitOfWork.SaveChangesAsync(); //To get Ids of the notifications } } return userNotifications; }); } protected virtual List<UserNotification> SaveUserNotifications( UserIdentifier[] users, NotificationInfo notificationInfo) { return _unitOfWorkManager.WithUnitOfWork(() => { var userNotifications = new List<UserNotification>(); var tenantGroups = users.GroupBy(user => user.TenantId); foreach (var tenantGroup in tenantGroups) { using (_unitOfWorkManager.Current.SetTenantId(tenantGroup.Key)) { var tenantNotificationInfo = new TenantNotificationInfo(_guidGenerator.Create(), tenantGroup.Key, notificationInfo); _notificationStore.InsertTenantNotification(tenantNotificationInfo); _unitOfWorkManager.Current.SaveChanges(); //To get tenantNotification.Id. var tenantNotification = tenantNotificationInfo.ToTenantNotification(); foreach (var user in tenantGroup) { var userNotification = new UserNotificationInfo(_guidGenerator.Create()) { TenantId = tenantGroup.Key, UserId = user.UserId, TenantNotificationId = tenantNotificationInfo.Id }; _notificationStore.InsertUserNotification(userNotification); userNotifications.Add(userNotification.ToUserNotification(tenantNotification)); } CurrentUnitOfWork.SaveChanges(); //To get Ids of the notifications } } return userNotifications; }); } #region Protected methods protected virtual async Task NotifyAsync(UserNotification[] userNotifications) { foreach (var notifierType in _notificationConfiguration.Notifiers) { try { using (var notifier = _iocResolver.ResolveAsDisposable<IRealTimeNotifier>(notifierType)) { await notifier.Object.SendNotificationsAsync(userNotifications); } } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); } } } #endregion } }
/* * ApplicationId.cs - Implementation of the "System.ApplicationId" class. * * Copyright (C) 2003 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 { #if !ECMA_COMPAT && CONFIG_FRAMEWORK_2_0 using System.Text; public sealed class ApplicationId { // Internal state. private byte[] publicKeyToken; private String strName; private Version version; private String strProcessorArchitecture; private String strCulture; // Constructor. public ApplicationId(byte[] publicKeyToken, String strName, Version version, String strProcessorArchitecture, String strCulture) { if(strName == null) { throw new ArgumentNullException("strName"); } if(version == null) { throw new ArgumentNullException("version"); } if(publicKeyToken == null) { throw new ArgumentNullException("publicKeyToken"); } this.publicKeyToken = (Byte[])publicKeyToken.Clone(); this.strName = strName; this.version = version; this.strProcessorArchitecture = strProcessorArchitecture; this.strCulture = strCulture; } // Get this object's properties. public String Culture { get { return strCulture; } } public String Name { get { return strName; } } public String ProcessorArchitecture { get { return strProcessorArchitecture; } } public byte[] PublicKeyToken { get { return (Byte[])publicKeyToken.Clone(); } } public Version Version { get { return version; } } // Make a copy of this object. public ApplicationId Copy() { return (ApplicationId)(MemberwiseClone()); } // Determine if two objects are equal. public override bool Equals(Object o) { ApplicationId other = (o as ApplicationId); if(other != null) { if(strName != other.strName || strProcessorArchitecture != other.strProcessorArchitecture || strCulture != other.strCulture || version != other.version) { return false; } if(publicKeyToken == null) { return (other.publicKeyToken == null); } else if(other.publicKeyToken == null || publicKeyToken.Length != other.publicKeyToken.Length) { return false; } else { int posn; for(posn = 0; posn < publicKeyToken.Length; ++posn) { if(publicKeyToken[posn] != other.publicKeyToken[posn]) { return false; } } return true; } } else { return false; } } // Get a hash code for this object. public override int GetHashCode() { if(strName != null) { return strName.GetHashCode(); } else { return 0; } } // Convert this object into a string. public override String ToString() { StringBuilder builder = new StringBuilder(); if(strName != null) { builder.Append(strName); } if(strCulture != null) { builder.Append(", culture="); builder.Append('"'); builder.Append(strCulture); builder.Append('"'); } if(version != null) { builder.Append(", version="); builder.Append('"'); builder.Append(version.ToString()); builder.Append('"'); } if(publicKeyToken != null) { builder.Append(", publicKeyToken="); builder.Append('"'); foreach(byte value in publicKeyToken) { BitConverter.AppendHex(builder, value); } builder.Append('"'); } if(strProcessorArchitecture != null) { builder.Append(", processorArchitecture ="); builder.Append('"'); builder.Append(strProcessorArchitecture); builder.Append('"'); } return builder.ToString(); } }; // class ApplicationId #endif // !ECMA_COMPAT && CONFIG_FRAMEWORK_2_0 }; // namespace System
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; namespace System.Net.Http { internal static class WinHttpTraceHelper { private const string WinHtpTraceEnvironmentVariable = "WINHTTPHANDLER_TRACE"; private static bool s_TraceEnabled; static WinHttpTraceHelper() { string env; try { env = Environment.GetEnvironmentVariable(WinHtpTraceEnvironmentVariable); } catch (SecurityException) { env = null; } s_TraceEnabled = !string.IsNullOrEmpty(env); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsTraceEnabled() { return s_TraceEnabled; } public static void Trace(string message) { if (!IsTraceEnabled()) { return; } Debug.WriteLine(message); } public static void Trace(string format, object arg0, object arg1, object arg2) { if (!IsTraceEnabled()) { return; } Debug.WriteLine(format, arg0, arg1, arg2); } public static void TraceCallbackStatus(string message, IntPtr handle, IntPtr context, uint status) { if (!IsTraceEnabled()) { return; } Debug.WriteLine( "{0}: handle=0x{1:X}, context=0x{2:X}, {3}", message, handle, context, GetStringFromInternetStatus(status)); } public static void TraceAsyncError(string message, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { if (!IsTraceEnabled()) { return; } uint apiIndex = (uint)asyncResult.dwResult.ToInt32(); uint error = asyncResult.dwError; Debug.WriteLine( "{0}: api={1}, error={2}({3}) \"{4}\"", message, GetNameFromApiIndex(apiIndex), GetNameFromError(error), error, WinHttpException.GetErrorMessage((int)error)); } private static string GetNameFromApiIndex(uint index) { switch (index) { case Interop.WinHttp.API_RECEIVE_RESPONSE: return "API_RECEIVE_RESPONSE"; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: return "API_QUERY_DATA_AVAILABLE"; case Interop.WinHttp.API_READ_DATA: return "API_READ_DATA"; case Interop.WinHttp.API_WRITE_DATA: return "API_WRITE_DATA"; case Interop.WinHttp.API_SEND_REQUEST: return "API_SEND_REQUEST"; default: return index.ToString(); } } private static string GetNameFromError(uint error) { switch (error) { case Interop.WinHttp.ERROR_FILE_NOT_FOUND: return "ERROR_FILE_NOT_FOUND"; case Interop.WinHttp.ERROR_INVALID_HANDLE: return "ERROR_INVALID_HANDLE"; case Interop.WinHttp.ERROR_INVALID_PARAMETER: return "ERROR_INVALID_PARAMETER"; case Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER: return "ERROR_INSUFFICIENT_BUFFER"; case Interop.WinHttp.ERROR_NOT_FOUND: return "ERROR_NOT_FOUND"; case Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION: return "WINHTTP_INVALID_OPTION"; case Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE: return "WINHTTP_LOGIN_FAILURE"; case Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED: return "WINHTTP_OPERATION_CANCELLED"; case Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE: return "WINHTTP_INCORRECT_HANDLE_STATE"; case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR: return "WINHTTP_CONNECTION_ERROR"; case Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST: return "WINHTTP_RESEND_REQUEST"; case Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: return "WINHTTP_CLIENT_AUTH_CERT_NEEDED"; case Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND: return "WINHTTP_HEADER_NOT_FOUND"; case Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE: return "WINHTTP_SECURE_FAILURE"; case Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED: return "WINHTTP_AUTODETECTION_FAILED"; default: return error.ToString(); } } private static string GetStringFromInternetStatus(uint status) { switch (status) { case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: return "STATUS_RESOLVING_NAME"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: return "STATUS_NAME_RESOLVED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: return "STATUS_CONNECTING_TO_SERVER"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: return "STATUS_CONNECTED_TO_SERVER"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: return "STATUS_SENDING_REQUEST"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_SENT: return "STATUS_REQUEST_SENT"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: return "STATUS_RECEIVING_RESPONSE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: return "STATUS_RESPONSE_RECEIVED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: return "STATUS_CLOSING_CONNECTION"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: return "STATUS_CONNECTION_CLOSED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: return "STATUS_HANDLE_CREATED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: return "STATUS_HANDLE_CLOSING"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: return "STATUS_DETECTING_PROXY"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT: return "STATUS_REDIRECT"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: return "STATUS_INTERMEDIATE_RESPONSE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: return "STATUS_SECURE_FAILURE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: return "STATUS_HEADERS_AVAILABLE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: return "STATUS_DATA_AVAILABLE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE: return "STATUS_READ_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: return "STATUS_WRITE_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: return "STATUS_REQUEST_ERROR"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: return "STATUS_SENDREQUEST_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: return "STATUS_GETPROXYFORURL_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE: return "STATUS_CLOSE_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: return "STATUS_SHUTDOWN_COMPLETE"; default: return string.Format("0x{0:X}", status); } } } }
// Copyright 2018-2020 Andrew White // // 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 Finbuckle.MultiTenant; using Finbuckle.MultiTenant.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using MultiTenantIdentityDbContextShould; using Xunit; namespace EntityTypeBuilderExtensionsShould { public class TestDbContext : DbContext { private readonly Action<ModelBuilder> config; public TestDbContext(Action<ModelBuilder> config, DbContextOptions options) : base(options) { this.config = config; } DbSet<MyMultiTenantThing> MyMultiTenantThing { get; set; } DbSet<MyThingWithTenantId> MyThingWithTenantId { get; set; } DbSet<MyThingWithIntTenantId> MyThingWithIntTenantId { get; set; } protected override void OnModelCreating(ModelBuilder builder) { if (config != null) { config(builder); } else { builder.Entity<MyMultiTenantThing>().IsMultiTenant(); builder.Entity<MyThingWithTenantId>().IsMultiTenant(); } } } public class MyMultiTenantThing { public int Id { get; set; } } public class MyThingWithTenantId { public int Id { get; set; } public string TenantId { get; set; } } public class MyThingWithIntTenantId { public int Id { get; set; } public int TenantId { get; set; } } public class DynamicModelCacheKeyFactory : IModelCacheKeyFactory { public object Create(DbContext context) { return new Object(); // Never cache! } } public class EntityTypeBuilderExtensionsShould { private DbContext GetDbContext(Action<ModelBuilder> config = null) { var connection = new SqliteConnection("DataSource=:memory:"); var options = new DbContextOptionsBuilder() .UseSqlite(connection) .ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactory>() .Options; var db = new TestDbContext(config, options); return db; } private TestIdentityDbContext GetTestIdentityDbContext(TenantInfo tenant1) { var _connection = new SqliteConnection("DataSource=:memory:"); var options = new DbContextOptionsBuilder() .UseSqlite(_connection) .Options; return new TestIdentityDbContext(tenant1, options); } [Fact] public void SetMultiTenantAnnotation() { using (var db = GetDbContext()) { var annotation = db.Model.FindEntityType(typeof(MyMultiTenantThing)).FindAnnotation(Constants.MultiTenantAnnotationName); Assert.True((bool)annotation.Value); } } [Fact] public void AddTenantIdStringShadowProperty() { using (var db = GetDbContext()) { var prop = db.Model.FindEntityType(typeof(MyMultiTenantThing)).FindProperty("TenantId"); Assert.Equal(typeof(string), prop.ClrType); // IsShadowProperty doesn't work? // Assert.True(prop.IsShadowProperty()); Assert.Null(prop.FieldInfo); } } [Fact] public void RespectExistingTenantIdStringProperty() { using (var db = GetDbContext()) { var prop = db.Model.FindEntityType(typeof(MyThingWithTenantId)).FindProperty("TenantId"); Assert.Equal(typeof(string), prop.ClrType); // TODO: IsShadowProperty doesn't work? // Assert.False(prop.IsShadowProperty()); Assert.NotNull(prop.FieldInfo); } } [Fact] public void ThrowOnNonStringExistingTenantIdProperty() { using (var db = GetDbContext(b => b.Entity<MyThingWithIntTenantId>().IsMultiTenant())) { Assert.Throws<MultiTenantException>(() => db.Model); } } [Fact] public void SetsTenantIdStringMaxLength() { using (var db = GetDbContext()) { var prop = db.Model.FindEntityType(typeof(MyMultiTenantThing)).FindProperty("TenantId"); Assert.Equal(Finbuckle.MultiTenant.Internal.Constants.TenantIdMaxLength, prop.GetMaxLength()); } } [Fact] public void SetGlobalFilterQuery() { // Doesn't appear to be a way to test this except to try it out... var connection = new SqliteConnection("DataSource=:memory:"); try { connection.Open(); var options = new DbContextOptionsBuilder() .UseSqlite(connection) .Options; var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var db = new TestBlogDbContext(tenant1, options)) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); var blog1 = new Blog { Title = "abc" }; db.Blogs.Add(blog1); var post1 = new Post { Title = "post in abc", Blog = blog1 }; db.Posts.Add(post1); db.SaveChanges(); } var tenant2 = new TenantInfo { Id = "123", Identifier = "123", Name = "123", ConnectionString = "DataSource=testdb.db" }; using (var db = new TestBlogDbContext(tenant2, options)) { var blog1 = new Blog { Title = "123" }; db.Blogs.Add(blog1); var post1 = new Post { Title = "post in 123", Blog = blog1 }; db.Posts.Add(post1); db.SaveChanges(); } int postCount1 = 0; int postCount2 = 0; using (var db = new TestBlogDbContext(tenant1, options)) { postCount1 = db.Posts.Count(); postCount2 = db.Posts.IgnoreQueryFilters().Count(); } Assert.Equal(1, postCount1); Assert.Equal(2, postCount2); } finally { connection.Close(); } } [Fact] public void RespectExistingQueryFilter() { // Doesn't appear to be a way to test this except to try it out... var connection = new SqliteConnection("DataSource=:memory:"); var options = new DbContextOptionsBuilder() .UseSqlite(connection) .Options; try { connection.Open(); var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var db = new TestDbContextWithExistingGlobalFilter(tenant1, options)) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); var blog1 = new Blog { Title = "abc" }; db.Blogs.Add(blog1); var post1 = new Post { Title = "post in abc", Blog = blog1 }; db.Posts.Add(post1); var post2 = new Post { Title = "Filtered Title", Blog = blog1 }; db.Posts.Add(post2); db.SaveChanges(); } int postCount1 = 0; int postCount2 = 0; using (var db = new TestDbContextWithExistingGlobalFilter(tenant1, options)) { postCount1 = db.Posts.Count(); postCount2 = db.Posts.IgnoreQueryFilters().Count(); } Assert.Equal(1, postCount1); Assert.Equal(2, postCount2); } finally { connection.Close(); } } [Fact] public void AdjustRoleIndex() { var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var c = GetTestIdentityDbContext(tenant1)) { var props = new List<IProperty>(); props.Add(c.Model.FindEntityType(typeof(IdentityRole)).FindProperty("NormalizedName")); props.Add(c.Model.FindEntityType(typeof(IdentityRole)).FindProperty("TenantId")); var index = c.Model.FindEntityType(typeof(IdentityRole)).FindIndex(props); Assert.NotNull(index); Assert.True(index.IsUnique); } } [Fact] public void AdjustUserLoginKey() { var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var c = GetTestIdentityDbContext(tenant1)) { Assert.True(c.Model.FindEntityType(typeof(IdentityUserLogin<string>)).FindProperty("Id").IsPrimaryKey()); } } [Fact] public void AddUserLoginIndex() { var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var c = GetTestIdentityDbContext(tenant1)) { var props = new List<IProperty>(); props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin<string>)).FindProperty("LoginProvider")); props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin<string>)).FindProperty("ProviderKey")); props.Add(c.Model.FindEntityType(typeof(IdentityUserLogin<string>)).FindProperty("TenantId")); var index = c.Model.FindEntityType(typeof(IdentityUserLogin<string>)).FindIndex(props); Assert.NotNull(index); Assert.True(index.IsUnique); } } [Fact] public void AdjustUserIndex() { var tenant1 = new TenantInfo { Id = "abc", Identifier = "abc", Name = "abc", ConnectionString = "DataSource=testdb.db" }; using (var c = GetTestIdentityDbContext(tenant1)) { var props = new List<IProperty>(); props.Add(c.Model.FindEntityType(typeof(IdentityUser)).FindProperty("NormalizedUserName")); props.Add(c.Model.FindEntityType(typeof(IdentityUser)).FindProperty("TenantId")); var index = c.Model.FindEntityType(typeof(IdentityUser)).FindIndex(props); Assert.NotNull(index); Assert.True(index.IsUnique); } } } }
#undef DEBUG #region Foreign-License /* This class provides useful Tcl utility methods. Copyright (c) 1997 Cornell University. Copyright (c) 1997-1999 by Sun Microsystems, Inc. Copyright (c) 2012 Sky Morey See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #endregion using System; using System.Text; using Core; namespace Tcl.Lang { public class Util { public static int ActualPlatform { get { if (Util.Windows) { return JACL.PLATFORM_WINDOWS; } if (Util.Mac) { return JACL.PLATFORM_MAC; } return JACL.PLATFORM_UNIX; } } public static bool Unix { get { if (Mac || Windows) { return false; } return true; } } public static bool Mac { get { return false; } } public static bool Windows { get { // TODO .NET ist always Windows now return true; } } internal const int TCL_DONT_USE_BRACES = 1; internal const int USE_BRACES = 2; internal const int BRACES_UNMATCHED = 4; // Some error messages. internal const string intTooBigCode = "ARITH IOVERFLOW {integer value too large to represent}"; internal const string fpTooBigCode = "ARITH OVERFLOW {floating-point value too large to represent}"; // This table below is used to convert from ASCII digits to a // numerical equivalent. It maps from '0' through 'z' to integers // (100 for non-digit characters). internal static char[] cvtIn = new char[] { (char)(0), (char)(1), (char)(2), (char)(3), (char)(4), (char)(5), (char)(6), (char)(7), (char)(8), (char)(9), (char)(100), (char)(100), (char)(100), (char)(100), (char)(100), (char)(100), (char)(100), (char)(10), (char)(11), (char)(12), (char)(13), (char)(14), (char)(15), (char)(16), (char)(17), (char)(18), (char)(19), (char)(20), (char)(21), (char)(22), (char)(23), (char)(24), (char)(25), (char)(26), (char)(27), (char)(28), (char)(29), (char)(30), (char)(31), (char)(32), (char)(33), (char)(34), (char)(35), (char)(100), (char)(100), (char)(100), (char)(100), (char)(100), (char)(100), (char)(10), (char)(11), (char)(12), (char)(13), (char)(14), (char)(15), (char)(16), (char)(17), (char)(18), (char)(19), (char)(20), (char)(21), (char)(22), (char)(23), (char)(24), (char)(25), (char)(26), (char)(27), (char)(28), (char)(29), (char)(30), (char)(31), (char)(32), (char)(33), (char)(34), (char)(35) }; // Largest possible base 10 exponent. Any // exponent larger than this will already // produce underflow or overflow, so there's // no need to worry about additional digits. internal const int maxExponent = 511; // Table giving binary powers of 10. Entry // is 10^2^i. Used to convert decimal // exponents into floating-point numbers. internal static readonly double[] powersOf10 = new double[] { 10.0, 100.0, 1.0e4, 1.0e8, 1.0e16, 1.0e32, 1.0e64, 1.0e128, 1.0e256 }; // Default precision for converting floating-point values to strings. internal const int DEFAULT_PRECISION = 12; // The following variable determine the precision used when converting // floating-point values to strings. This information is linked to all // of the tcl_precision variables in all interpreters inside a JVM via // PrecTraceProc. // // Note: since multiple threads may change precision concurrently, race // conditions may occur. // // It should be modified only by the PrecTraceProc class. internal static int precision; private Util() { // Do nothing. This should never be called. } internal static StrtoulResult Strtoul(string s, int start, int base_) // Base for conversion. Must be less than 37. If 0, // then the base is chosen from the leading characters // of string: "0x" means hex, "0" means octal, // anything else means decimal. { long result = 0; int digit; bool anyDigits = false; int len = s.Length; int i = start; char c; // Skip any leading blanks. while (i < len && System.Char.IsWhiteSpace(s[i])) { i++; } if (i >= len) { return new StrtoulResult(0, 0, TCL.INVALID_INTEGER); } // If no base was provided, pick one from the leading characters // of the string. if (base_ == 0) { c = s[i]; if (c == '0') { if (i < len - 1) { i++; c = s[i]; if (c == 'x' || c == 'X') { i += 1; base_ = 16; } } if (base_ == 0) { // Must set anyDigits here, otherwise "0" produces a // "no digits" error. anyDigits = true; base_ = 8; } } else { base_ = 10; } } else if (base_ == 16) { if (i < len - 2) { // Skip a leading "0x" from hex numbers. if ((s[i] == '0') && (s[i + 1] == 'x')) { i += 2; } } } long max = (Int64.MaxValue / ((long)base_)); bool overflowed = false; for (; ; i += 1) { if (i >= len) { break; } digit = s[i] - '0'; if (digit < 0 || digit > ('z' - '0')) { break; } digit = cvtIn[digit]; if (digit >= base_) { break; } if (result > max) { overflowed = true; } result = result * base_ + digit; anyDigits = true; } // See if there were any digits at all. if (!anyDigits) { return new StrtoulResult(0, 0, TCL.INVALID_INTEGER); } else if (overflowed) { return new StrtoulResult(0, i, TCL.INTEGER_RANGE); } else { return new StrtoulResult(result, i, 0); } } internal static int getInt(Interp interp, string s) { int len = s.Length; bool sign; int i = 0; // Skip any leading blanks. while (i < len && System.Char.IsWhiteSpace(s[i])) { i++; } if (i >= len) { throw new TclException(interp, "expected integer but got \"" + s + "\""); } char c = s[i]; if (c == '-') { sign = true; i += 1; } else { if (c == '+') { i += 1; } sign = false; } StrtoulResult res = Strtoul(s, i, 0); if (res.errno < 0) { if (res.errno == TCL.INTEGER_RANGE) { if (interp != null) { interp.SetErrorCode(TclString.NewInstance(intTooBigCode)); } throw new TclException(interp, "integer value too large to represent"); } else { throw new TclException(interp, "expected integer but got \"" + s + "\"" + checkBadOctal(interp, s)); } } else if (res.Index < len) { for (i = res.Index; i < len; i++) { if (!System.Char.IsWhiteSpace(s[i])) { throw new TclException(interp, "expected integer but got \"" + s + "\"" + checkBadOctal(interp, s)); } } } if (sign) { return (int)(-res.value); } else { return (int)(res.value); } } internal static long getLong(Interp interp, string s) { int len = s.Length; bool sign; int i = 0; // Skip any leading blanks. while (i < len && System.Char.IsWhiteSpace(s[i])) { i++; } if (i >= len) { throw new TclException(interp, "expected integer but got \"" + s + "\""); } char c = s[i]; if (c == '-') { sign = true; i += 1; } else { if (c == '+') { i += 1; } sign = false; } StrtoulResult res = Strtoul(s, i, 0); if (res.errno < 0) { if (res.errno == TCL.INTEGER_RANGE) { if (interp != null) { interp.SetErrorCode(TclString.NewInstance(intTooBigCode)); } throw new TclException(interp, "integer value too large to represent"); } else { throw new TclException(interp, "expected integer but got \"" + s + "\"" + checkBadOctal(interp, s)); } } else if (res.Index < len) { for (i = res.Index; i < len; i++) { if (!System.Char.IsWhiteSpace(s[i])) { throw new TclException(interp, "expected integer but got \"" + s + "\"" + checkBadOctal(interp, s)); } } } if (sign) { return (long)(-res.value); } else { return (long)(res.value); } } internal static int getIntForIndex(Interp interp, TclObject tobj, int endValue) { int length, offset; if (tobj.InternalRep is TclInteger) { return TclInteger.Get(interp, tobj); } string bytes = tobj.ToString(); length = bytes.Length; string intforindex_error = "bad index \"" + bytes + "\": must be integer or end?-integer?" + checkBadOctal(interp, bytes); // FIXME : should we replace this call to regionMatches with a generic strncmp? if (!(String.Compare("end", 0, bytes, 0, (length > 3) ? 3 : length) == 0)) { try { offset = TclInteger.Get(null, tobj); } catch (TclException e) { throw new TclException(interp, "bad index \"" + bytes + "\": must be integer or end?-integer?" + checkBadOctal(interp, bytes)); } return offset; } if (length <= 3) { return endValue; } else if (bytes[3] == '-') { // This is our limited string expression evaluator offset = Util.getInt(interp, bytes.Substring(3)); return endValue + offset; } else { throw new TclException(interp, "bad index \"" + bytes + "\": must be integer or end?-integer?" + checkBadOctal(interp, bytes.Substring(3))); } } internal static string checkBadOctal(Interp interp, string value) { int p = 0; int len = value.Length; // A frequent mistake is invalid octal values due to an unwanted // leading zero. Try to generate a meaningful error message. while (p < len && System.Char.IsWhiteSpace(value[p])) { p++; } if ((p < len) && (value[p] == '+' || value[p] == '-')) { p++; } if ((p < len) && (value[p] == '0')) { while ((p < len) && System.Char.IsDigit(value[p])) { // INTL: digit. p++; } while ((p < len) && System.Char.IsWhiteSpace(value[p])) { // INTL: ISO space. p++; } if (p >= len) { // Reached end of string if (interp != null) { return " (looks like invalid octal number)"; } } } return ""; } internal static StrtodResult Strtod(string s, int start) // The index to the char where the number starts. { //bool sign; char c; int mantSize; // Number of digits in mantissa. int decPt; // Number of mantissa digits BEFORE decimal // point. int len = s.Length; int i = start; // Skip any leading blanks. while (i < len && System.Char.IsWhiteSpace(s[i])) { i++; } if (i >= len) { return new StrtodResult(0, 0, TCL.INVALID_DOUBLE); } c = s[i]; if (c == '-') { // sign = true; i += 1; } else { if (c == '+') { i += 1; } // sign = false; } // Count the number of digits in the mantissa (including the decimal // point), and also locate the decimal point. bool maybeZero = true; decPt = -1; for (mantSize = 0; ; mantSize += 1) { c = CharAt(s, i, len); if (!System.Char.IsDigit(c)) { if ((c != '.') || (decPt >= 0)) { break; } decPt = mantSize; } if (c != '0' && c != '.') { maybeZero = false; // non zero digit found... } i++; } // Skim off the exponent. if ((CharAt(s, i, len) == 'E') || (CharAt(s, i, len) == 'e')) { i += 1; if (CharAt(s, i, len) == '-') { i += 1; } else if (CharAt(s, i, len) == '+') { i += 1; } while (System.Char.IsDigit(CharAt(s, i, len))) { i += 1; } } s = s.Substring(start, (i) - (start)); double result = 0; try { result = System.Double.Parse(s, System.Globalization.NumberFormatInfo.InvariantInfo); } catch (System.OverflowException e) { return new StrtodResult(0, 0, TCL.DOUBLE_RANGE); } catch (System.FormatException e) { return new StrtodResult(0, 0, TCL.INVALID_DOUBLE); } if ((result == System.Double.NegativeInfinity) || (result == System.Double.PositiveInfinity) || (result == 0.0 && !maybeZero)) { return new StrtodResult(result, i, TCL.DOUBLE_RANGE); } if (result == System.Double.NaN) { return new StrtodResult(0, 0, TCL.INVALID_DOUBLE); } return new StrtodResult(result, i, 0); } internal static char CharAt(string s, int index, int len) { if (index >= 0 && index < len) { return s[index]; } else { return '\x0000'; } } internal static double getDouble(Interp interp, string s) { int len = s.Length; bool sign; int i = 0; // Skip any leading blanks. while (i < len && System.Char.IsWhiteSpace(s[i])) { i++; } if (i >= len) { throw new TclException(interp, "expected floating-point number but got \"" + s + "\""); } char c = s[i]; if (c == '-') { sign = true; i += 1; } else { if (c == '+') { i += 1; } sign = false; } StrtodResult res = Strtod(s, i); if (res.errno != 0) { if (res.errno == TCL.DOUBLE_RANGE) { if (interp != null) { interp.SetErrorCode(TclString.NewInstance(fpTooBigCode)); } throw new TclException(interp, "floating-point value too large to represent"); } else { throw new TclException(interp, "expected floating-point number but got \"" + s + "\""); } } else if (res.index < len) { for (i = res.index; i < len; i++) { if (!System.Char.IsWhiteSpace(s[i])) { throw new TclException(interp, "expected floating-point number but got \"" + s + "\""); } } } if (sign) { return (double)(-res.value); } else { return (double)(res.value); } } internal static string concat(int from, int to, TclObject[] argv) // The CmdArgs. { StringBuilder sbuf; if (from > argv.Length) { return ""; } if (to <= argv.Length) { to = argv.Length - 1; } sbuf = new StringBuilder(); for (int i = from; i <= to; i++) { string str = TrimLeft(argv[i].ToString()); str = TrimRight(str); if (str.Length == 0) { continue; } sbuf.Append(str); if (i < to) { sbuf.Append(" "); } } return sbuf.ToString().TrimEnd(); } public static bool StringMatch(string str, string pat) //Pattern which may contain special characters. { char[] strArr = str.ToCharArray(); char[] patArr = pat.ToCharArray(); int strLen = str.Length; // Cache the len of str. int patLen = pat.Length; // Cache the len of pat. int pIndex = 0; // Current index into patArr. int sIndex = 0; // Current index into patArr. char strch; // Stores current char in string. char ch1; // Stores char after '[' in pat. char ch2; // Stores look ahead 2 char in pat. bool incrIndex = false; // If true it will incr both p/sIndex. while (true) { if (incrIndex == true) { pIndex++; sIndex++; incrIndex = false; } // See if we're at the end of both the pattern and the string. // If so, we succeeded. If we're at the end of the pattern // but not at the end of the string, we failed. if (pIndex == patLen) { return sIndex == strLen; } if ((sIndex == strLen) && (patArr[pIndex] != '*')) { return false; } // Check for a "*" as the next pattern character. It matches // any substring. We handle this by calling ourselves // recursively for each postfix of string, until either we // match or we reach the end of the string. if (patArr[pIndex] == '*') { pIndex++; if (pIndex == patLen) { return true; } while (true) { if (StringMatch(str.Substring(sIndex), pat.Substring(pIndex))) { return true; } if (sIndex == strLen) { return false; } sIndex++; } } // Check for a "?" as the next pattern character. It matches // any single character. if (patArr[pIndex] == '?') { incrIndex = true; continue; } // Check for a "[" as the next pattern character. It is followed // by a list of characters that are acceptable, or by a range // (two characters separated by "-"). if (patArr[pIndex] == '[') { pIndex++; while (true) { if ((pIndex == patLen) || (patArr[pIndex] == ']')) { return false; } if (sIndex == strLen) { return false; } ch1 = patArr[pIndex]; strch = strArr[sIndex]; if (((pIndex + 1) != patLen) && (patArr[pIndex + 1] == '-')) { if ((pIndex += 2) == patLen) { return false; } ch2 = patArr[pIndex]; if (((ch1 <= strch) && (ch2 >= strch)) || ((ch1 >= strch) && (ch2 <= strch))) { break; } } else if (ch1 == strch) { break; } pIndex++; } for (pIndex++; ((pIndex != patLen) && (patArr[pIndex] != ']')); pIndex++) { } if (pIndex == patLen) { pIndex--; } incrIndex = true; continue; } // If the next pattern character is '\', just strip off the '\' // so we do exact matching on the character that follows. if (patArr[pIndex] == '\\') { pIndex++; if (pIndex == patLen) { return false; } } // There's no special character. Just make sure that the next // characters of each string match. if ((sIndex == strLen) || (patArr[pIndex] != strArr[sIndex])) { return false; } incrIndex = true; } } internal static string toTitle(string str) // String to convert in place. { // Capitalize the first character and then lowercase the rest of the // characters until we get to the end of string. int length = str.Length; if (length == 0) { return ""; } StringBuilder buf = new StringBuilder(length); buf.Append(System.Char.ToUpper(str[0])); buf.Append(str.Substring(1).ToLower()); return buf.ToString(); } internal static bool regExpMatch(Interp interp, string inString, TclObject pattern) { Regexp r = TclRegexp.compile(interp, pattern, false); return r.match(inString, (string[])null); } internal static void appendElement(Interp interp, StringBuilder sbuf, string s) { if (sbuf.Length > 0) { sbuf.Append(' '); } int flags = scanElement(interp, s); sbuf.Append(convertElement(s, flags)); } internal static FindElemResult findElement(Interp interp, string s, int i, int len) { int openBraces = 0; bool inQuotes = false; for (; i < len && System.Char.IsWhiteSpace(s[i]); i++) { ; } if (i >= len) { return null; } char c = s[i]; if (c == '{') { openBraces = 1; i++; } else if (c == '"') { inQuotes = true; i++; } StringBuilder sbuf = new StringBuilder(); while (true) { if (i >= len) { if (openBraces != 0) { throw new TclException(interp, "unmatched open brace in list"); } else if (inQuotes) { throw new TclException(interp, "unmatched open quote in list"); } return new FindElemResult(i, sbuf.ToString(), openBraces); } c = s[i]; switch (c) { // Open brace: don't treat specially unless the element is // in braces. In this case, keep a nesting count. case '{': if (openBraces != 0) { openBraces++; } sbuf.Append(c); i++; break; // Close brace: if element is in braces, keep nesting // count and quit when the last close brace is seen. case '}': if (openBraces == 1) { if (i == len - 1 || System.Char.IsWhiteSpace(s[i + 1])) { return new FindElemResult(i + 1, sbuf.ToString(), openBraces); } else { int errEnd; for (errEnd = i + 1; errEnd < len; errEnd++) { if (System.Char.IsWhiteSpace(s[errEnd])) { break; } } throw new TclException(interp, "list element in braces followed by \"" + s.Substring(i + 1, (errEnd) - (i + 1)) + "\" instead of space"); } } else if (openBraces != 0) { openBraces--; } sbuf.Append(c); i++; break; // Backslash: skip over everything up to the end of the // backslash sequence. case '\\': BackSlashResult bs = Interp.backslash(s, i, len); if (openBraces > 0) { // Quotes are ignored in brace-quoted stuff sbuf.Append(s.Substring(i, (bs.NextIndex) - (i))); } else { sbuf.Append(bs.C); } i = bs.NextIndex; break; // Space: ignore if element is in braces or quotes; otherwise // terminate element. case ' ': case '\f': case '\n': case '\r': case '\t': if ((openBraces == 0) && !inQuotes) { return new FindElemResult(i + 1, sbuf.ToString(), openBraces); } else { sbuf.Append(c); i++; } break; // Double-quote: if element is in quotes then terminate it. case '"': if (inQuotes) { if (i == len - 1 || System.Char.IsWhiteSpace(s[i + 1])) { return new FindElemResult(i + 1, sbuf.ToString(), openBraces); } else { int errEnd; for (errEnd = i + 1; errEnd < len; errEnd++) { if (System.Char.IsWhiteSpace(s[errEnd])) { break; } } throw new TclException(interp, "list element in quotes followed by \"" + s.Substring(i + 1, (errEnd) - (i + 1)) + "\" instead of space"); } } else { sbuf.Append(c); i++; } break; default: sbuf.Append(c); i++; break; } } } internal static int scanElement(Interp interp, string inString) { int flags, nestingLevel; char c; int len; int i; // This procedure and Tcl_ConvertElement together do two things: // // 1. They produce a proper list, one that will yield back the // argument strings when evaluated or when disassembled with // Tcl_SplitList. This is the most important thing. // // 2. They try to produce legible output, which means minimizing the // use of backslashes (using braces instead). However, there are // some situations where backslashes must be used (e.g. an element // like "{abc": the leading brace will have to be backslashed. For // each element, one of three things must be done: // // (a) Use the element as-is (it doesn't contain anything special // characters). This is the most desirable option. // // (b) Enclose the element in braces, but leave the contents alone. // This happens if the element contains embedded space, or if it // contains characters with special interpretation ($, [, ;, or \), // or if it starts with a brace or double-quote, or if there are // no characters in the element. // // (c) Don't enclose the element in braces, but add backslashes to // prevent special interpretation of special characters. This is a // last resort used when the argument would normally fall under case // (b) but contains unmatched braces. It also occurs if the last // character of the argument is a backslash or if the element contains // a backslash followed by newline. // // The procedure figures out how many bytes will be needed to store // the result (actually, it overestimates). It also collects // information about the element in the form of a flags word. nestingLevel = 0; flags = 0; i = 0; len = (inString != null ? inString.Length : 0); if (len == 0) { inString = '\x0000'.ToString(); // FIXME : pizza compiler workaround // We really should be able to use the "\0" form but there // is a nasty bug in the pizza compiler shipped with kaffe // that causes "\0" to be read as the empty string. //string = "\0"; } System.Diagnostics.Debug.WriteLine("scanElement string is \"" + inString + "\""); c = inString[i]; if ((c == '{') || (c == '"') || (c == '\x0000')) { flags |= USE_BRACES; } for (; i < len; i++) { System.Diagnostics.Debug.WriteLine("getting char at index " + i); System.Diagnostics.Debug.WriteLine("char is '" + inString[i] + "'"); c = inString[i]; switch (c) { case '{': nestingLevel++; break; case '}': nestingLevel--; if (nestingLevel < 0) { flags |= TCL_DONT_USE_BRACES | BRACES_UNMATCHED; } break; case '[': case '$': case ';': case ' ': case '\f': case '\n': case '\r': case '\t': case (char)(0x0b): flags |= USE_BRACES; break; case '\\': if ((i >= len - 1) || (inString[i + 1] == '\n')) { flags = TCL_DONT_USE_BRACES | BRACES_UNMATCHED; } else { BackSlashResult bs = Interp.backslash(inString, i, len); // Subtract 1 because the for loop will automatically // add one on the next iteration. i = (bs.NextIndex - 1); flags |= USE_BRACES; } break; } } if (nestingLevel != 0) { flags = TCL_DONT_USE_BRACES | BRACES_UNMATCHED; } return flags; } internal static string convertElement(string s, int flags) // Flags produced by ccanElement { int i = 0; char c; int len = (s != null ? s.Length : 0); // See the comment block at the beginning of the ScanElement // code for details of how this works. if (((System.Object)s == null) || (s.Length == 0) || (s[0] == '\x0000')) { return "{}"; } StringBuilder sbuf = new StringBuilder(); if (((flags & USE_BRACES) != 0) && ((flags & TCL_DONT_USE_BRACES) == 0)) { sbuf.Append('{'); for (i = 0; i < len; i++) { sbuf.Append(s[i]); } sbuf.Append('}'); } else { c = s[0]; if (c == '{') { // Can't have a leading brace unless the whole element is // enclosed in braces. Add a backslash before the brace. // Furthermore, this may destroy the balance between open // and close braces, so set BRACES_UNMATCHED. sbuf.Append('\\'); sbuf.Append('{'); i++; flags |= BRACES_UNMATCHED; } for (; i < len; i++) { c = s[i]; switch (c) { case ']': case '[': case '$': case ';': case ' ': case '\\': case '"': sbuf.Append('\\'); break; case '{': case '}': if ((flags & BRACES_UNMATCHED) != 0) { sbuf.Append('\\'); } break; case '\f': sbuf.Append('\\'); sbuf.Append('f'); continue; case '\n': sbuf.Append('\\'); sbuf.Append('n'); continue; case '\r': sbuf.Append('\\'); sbuf.Append('r'); continue; case '\t': sbuf.Append('\\'); sbuf.Append('t'); continue; case (char)(0x0b): sbuf.Append('\\'); sbuf.Append('v'); continue; } sbuf.Append(c); } } return sbuf.ToString(); } internal static string TrimLeft(string str, string pattern) { int i, j; char c; int strLen = str.Length; int patLen = pattern.Length; bool done = false; for (i = 0; i < strLen; i++) { c = str[i]; done = true; for (j = 0; j < patLen; j++) { if (c == pattern[j]) { done = false; break; } } if (done) { break; } } return str.Substring(i, (strLen) - (i)); } internal static string TrimLeft(string str) { return TrimLeft(str, " \n\t\r"); } internal static string TrimRight(string str, string pattern) { int last = str.Length - 1; char[] strArray = str.ToCharArray(); int c; // Remove trailing characters... while (last >= 0) { c = strArray[last]; if (pattern.IndexOf((System.Char)c) == -1) { break; } last--; } return str.Substring(0, (last + 1) - (0)); } internal static string TrimRight(string str) { return TrimRight(str, " \n\t\r"); } internal static bool GetBoolean(Interp interp, string inString) { string s = inString.ToLower(); // The length of 's' needs to be > 1 if it begins with 'o', // in order to compare between "on" and "off". if (s.Length > 0) { if ("yes".StartsWith(s)) { return true; } else if ("no".StartsWith(s)) { return false; } else if ("true".StartsWith(s)) { return true; } else if ("false".StartsWith(s)) { return false; } else if ("on".StartsWith(s) && s.Length > 1) { return true; } else if ("off".StartsWith(s) && s.Length > 1) { return false; } else if (s.Equals("0")) { return false; } else if (s.Equals("1")) { return true; } } throw new TclException(interp, "expected boolean value but got \"" + inString + "\""); } internal static void setupPrecisionTrace(Interp interp) // Current interpreter. { try { interp.TraceVar("tcl_precision", new PrecTraceProc(), TCL.VarFlag.GLOBAL_ONLY | TCL.VarFlag.TRACE_WRITES | TCL.VarFlag.TRACE_READS | TCL.VarFlag.TRACE_UNSETS); } catch (TclException e) { throw new TclRuntimeError("unexpected TclException: " + e.Message, e); } } internal static string printDouble(double number) // The number to format into a string. { string s = FormatCmd.toString(number, precision, 10).Replace("E", "e"); int length = s.Length; for (int i = 0; i < length; i++) { if ((s[i] == '.') || System.Char.IsLetter(s[i])) { return s; } } return string.Concat(s, ".0"); } internal static string tryGetSystemProperty(string propName, string defautlValue) // Default value. { try { // ATK return System_Renamed.getProperty(propName); return System.Environment.GetEnvironmentVariable("os.name"); } catch (System.Security.SecurityException e) { return defautlValue; } } static Util() { precision = DEFAULT_PRECISION; } } // end Util /* *---------------------------------------------------------------------- * * PrecTraceProc.java -- * * The PrecTraceProc class is used to implement variable traces for * the tcl_precision variable to control precision used when * converting floating-point values to strings. * *---------------------------------------------------------------------- */ sealed class PrecTraceProc : VarTrace { // Maximal precision supported by Tcl. internal const int TCL_MAX_PREC = 17; public void traceProc(Interp interp, string name1, string name2, TCL.VarFlag flags) { // If the variable is unset, then recreate the trace and restore // the default value of the format string. if ((flags & TCL.VarFlag.TRACE_UNSETS) != 0) { if (((flags & TCL.VarFlag.TRACE_DESTROYED) != 0) && ((flags & TCL.VarFlag.INTERP_DESTROYED) == 0)) { interp.TraceVar(name1, name2, new PrecTraceProc(), TCL.VarFlag.GLOBAL_ONLY | TCL.VarFlag.TRACE_WRITES | TCL.VarFlag.TRACE_READS | TCL.VarFlag.TRACE_UNSETS); Util.precision = Util.DEFAULT_PRECISION; } return; } // When the variable is read, reset its value from our shared // value. This is needed in case the variable was modified in // some other interpreter so that this interpreter's value is // out of date. if ((flags & TCL.VarFlag.TRACE_READS) != 0) { interp.SetVar(name1, name2, TclInteger.NewInstance(Util.precision), flags & TCL.VarFlag.GLOBAL_ONLY); return; } // The variable is being written. Check the new value and disallow // it if it isn't reasonable. // // (ToDo) Disallow it if this is a safe interpreter (we don't want // safe interpreters messing up the precision of other // interpreters). TclObject tobj = null; try { tobj = interp.GetVar(name1, name2, (flags & TCL.VarFlag.GLOBAL_ONLY)); } catch (TclException e) { // Do nothing when fixme does not exist. } string value; if (tobj != null) { value = tobj.ToString(); } else { value = ""; } StrtoulResult r = Util.Strtoul(value, 0, 10); if ((r == null) || (r.value <= 0) || (r.value > TCL_MAX_PREC) || (r.value > 100) || (r.Index == 0) || (r.Index != value.Length)) { interp.SetVar(name1, name2, TclInteger.NewInstance(Util.precision), TCL.VarFlag.GLOBAL_ONLY); throw new TclException(interp, "improper value for precision"); } Util.precision = (int)r.value; } } // end PrecTraceProc }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Subscriptions; using Microsoft.Azure.Subscriptions.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Subscriptions { /// <summary> /// Operations for managing subscriptions. /// </summary> internal partial class SubscriptionOperations : IServiceOperations<SubscriptionClient>, ISubscriptionOperations { /// <summary> /// Initializes a new instance of the SubscriptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionOperations(SubscriptionClient client) { this._client = client; } private SubscriptionClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Subscriptions.SubscriptionClient. /// </summary> public SubscriptionClient Client { get { return this._client; } } /// <summary> /// Gets details about particular subscription. /// </summary> /// <param name='subscriptionId'> /// Required. Id of the subscription. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription detailed information. /// </returns> public async Task<GetSubscriptionResult> GetAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate if (subscriptionId == null) { throw new ArgumentNullException("subscriptionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; url = url + Uri.EscapeDataString(subscriptionId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetSubscriptionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetSubscriptionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Subscription subscriptionInstance = new Subscription(); result.Subscription = subscriptionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); subscriptionInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of the subscriptionIds. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription list operation response. /// </returns> public async Task<SubscriptionListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Subscription subscriptionInstance = new Subscription(); result.Subscriptions.Add(subscriptionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); subscriptionInstance.State = stateInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of the subscription locations. /// </summary> /// <param name='subscriptionId'> /// Required. Id of the subscription /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Location list operation response. /// </returns> public async Task<LocationListResult> ListLocationsAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate if (subscriptionId == null) { throw new ArgumentNullException("subscriptionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); TracingAdapter.Enter(invocationId, this, "ListLocationsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; url = url + Uri.EscapeDataString(subscriptionId); url = url + "/locations"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LocationListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LocationListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Location locationInstance = new Location(); result.Locations.Add(locationInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); locationInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); locationInstance.SubscriptionId = subscriptionIdInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); locationInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); locationInstance.DisplayName = displayNameInstance; } JToken latitudeValue = valueValue["latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { string latitudeInstance = ((string)latitudeValue); locationInstance.Latitude = latitudeInstance; } JToken longitudeValue = valueValue["longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { string longitudeInstance = ((string)longitudeValue); locationInstance.Longitude = longitudeInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Services; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; //using OpenSim.Region.Communications.Hypergrid; using OpenSim.Region.Communications.Local; using OpenSim.Region.Communications.OGS1; namespace OpenSim.ApplicationPlugins.CreateCommsManager { public class CreateCommsManagerPlugin : IApplicationPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region IApplicationPlugin Members // TODO: required by IPlugin, but likely not at all right private string m_name = "CreateCommsManagerPlugin"; private string m_version = "0.0"; public string Version { get { return m_version; } } public string Name { get { return m_name; } } protected OpenSimBase m_openSim; protected BaseHttpServer m_httpServer; protected CommunicationsManager m_commsManager; protected GridInfoService m_gridInfoService; protected IHyperlink HGServices = null; protected IRegionCreator m_regionCreator; public void Initialise() { m_log.Info("[LOADREGIONS]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } public void Initialise(OpenSimBase openSim) { m_openSim = openSim; m_httpServer = openSim.HttpServer; InitialiseCommsManager(openSim); if (m_commsManager != null) { m_openSim.ApplicationRegistry.RegisterInterface<IUserService>(m_commsManager.UserService); } } public void PostInitialise() { if (m_openSim.ApplicationRegistry.TryGet<IRegionCreator>(out m_regionCreator)) { m_regionCreator.OnNewRegionCreated += RegionCreated; } } public void Dispose() { } #endregion private void RegionCreated(IScene scene) { if (m_commsManager != null) { scene.RegisterModuleInterface<IUserService>(m_commsManager.UserService); } } protected void InitialiseCommsManager(OpenSimBase openSim) { LibraryRootFolder libraryRootFolder = new LibraryRootFolder(m_openSim.ConfigurationSettings.LibrariesXMLFile); InitialiseStandardServices(libraryRootFolder); openSim.CommunicationsManager = m_commsManager; } /* protected void InitialiseHGServices(OpenSimBase openSim, LibraryRootFolder libraryRootFolder) { // Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false) if (m_openSim.ConfigurationSettings.Standalone) { InitialiseHGStandaloneServices(libraryRootFolder); } else { // We are in grid mode InitialiseHGGridServices(libraryRootFolder); } HGCommands.HGServices = HGServices; } */ protected void InitialiseStandardServices(LibraryRootFolder libraryRootFolder) { // Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false) if (m_openSim.ConfigurationSettings.Standalone) { InitialiseStandaloneServices(libraryRootFolder); } else { // We are in grid mode InitialiseGridServices(libraryRootFolder); } } /// <summary> /// Initialises the backend services for standalone mode, and registers some http handlers /// </summary> /// <param name="libraryRootFolder"></param> protected virtual void InitialiseStandaloneServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new CommunicationsLocal( m_openSim.ConfigurationSettings, m_openSim.NetServersInfo, m_httpServer, m_openSim.AssetCache, libraryRootFolder); CreateGridInfoService(); } protected virtual void InitialiseGridServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new CommunicationsOGS1(m_openSim.NetServersInfo, m_httpServer, m_openSim.AssetCache, libraryRootFolder, m_openSim.ConfigurationSettings); m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler()); m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim)); if (m_openSim.userStatsURI != String.Empty ) m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim)); } /* protected virtual void InitialiseHGStandaloneServices(LibraryRootFolder libraryRootFolder) { HGGridServicesStandalone gridService = new HGGridServicesStandalone( m_openSim.NetServersInfo, m_httpServer, m_openSim.AssetCache, m_openSim.SceneManager); m_commsManager = new HGCommunicationsStandalone( m_openSim.ConfigurationSettings, m_openSim.NetServersInfo, m_httpServer, m_openSim.AssetCache, gridService, libraryRootFolder, m_openSim.ConfigurationSettings.DumpAssetsToFile); HGServices = gridService; CreateGridInfoService(); } protected virtual void InitialiseHGGridServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new HGCommunicationsGridMode( m_openSim.NetServersInfo, m_httpServer, m_openSim.AssetCache, m_openSim.SceneManager, libraryRootFolder); HGServices = ((HGCommunicationsGridMode) m_commsManager).HGServices; m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler()); m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim)); if (m_openSim.userStatsURI != String.Empty ) m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim)); } */ private void CreateGridInfoService() { // provide grid info m_gridInfoService = new GridInfoService(m_openSim.ConfigSource.Source); // Old Style m_httpServer.AddXmlRPCHandler("get_grid_info", m_gridInfoService.XmlRpcGridInfoMethod); // New Style service interface m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("get_grid_info"), m_gridInfoService.XmlRpcGridInfoMethod)); // REST Handler m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/get_grid_info", m_gridInfoService.RestGetGridInfoMethod)); } } }
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Spines.Tools.AnalyzerBuilder.Classification; namespace Spines.Tools.AnalyzerBuilder.Precalculation { internal class ProgressiveHonorStateMachineBuilder : IStateMachineBuilder { /// <summary> /// The size of the alphabet. /// </summary> public int AlphabetSize => 15 + 1; /// <summary> /// The transitions for the specified language. /// </summary> public IReadOnlyList<int> Transitions => _transitions; /// <summary> /// The states at which the transitions can be entered. /// </summary> /// <returns>The ids of the states.</returns> public IReadOnlyList<int> EntryStates => new[] {0}; public void SetLanguage(IEnumerable<WordWithValue> language) { CreateLookupData(language); CreateTransitions(); } /// <summary> /// Is the transition one that describes can not be reached with a legal word? /// </summary> /// <param name="transition">The Id of the transtion.</param> /// <returns>True, if the transition can not be reached, false otherwise.</returns> public bool IsNull(int transition) { return _nullTransitionIds.Contains(transition); } /// <summary> /// Is the transition one that describes a result? /// </summary> /// <param name="transition">The Id of the transtion.</param> /// <returns>True, if the transition is a result, false otherwise.</returns> public bool IsResult(int transition) { return transition % AlphabetSize == 0; } private readonly Dictionary<int, int> _idToValue = new Dictionary<int, int>(); private readonly Dictionary<int, int> _idToStateColumn = new Dictionary<int, int>(); private readonly List<int> _stateColumnToId = new List<int>(); private ISet<int> _nullTransitionIds; private int[] _transitions; private void CreateTransitions() { var columnCount = _stateColumnToId.Count; _transitions = new int[AlphabetSize * columnCount]; _nullTransitionIds = new HashSet<int>(); for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) { var id = _stateColumnToId[columnIndex]; _transitions[AlphabetSize * columnIndex] = _idToValue[id]; // value in row 0 for (var c = 1; c < AlphabetSize; ++c) { var next = GetNext(id, c - 1); var transitionId = AlphabetSize * columnIndex + c; if (next.HasValue) { _transitions[transitionId] = AlphabetSize * _idToStateColumn[next.Value]; } else { _nullTransitionIds.Add(transitionId); } } } } private void CreateLookupData(IEnumerable<WordWithValue> language) { foreach (var word in language) { var id = GetId(word.Word); if (!_idToValue.ContainsKey(id)) { _idToValue.Add(id, word.Value); } } _stateColumnToId.AddRange(_idToValue.Keys.OrderBy(x => x)); for (var i = 0; i < _stateColumnToId.Count; ++i) { _idToStateColumn.Add(_stateColumnToId[i], i); } } private static int? GetNext(int s, int c) { var totalCount = 0; var word = new int[15]; for (var i = 0; i < 7; ++i) { var t = (s >> i * 3) & 7; if (t == 7) { word[i + 1] = 4; totalCount += 3; } else if (t > 4) { word[i + 1] = 3; totalCount += 3; word[i + 7 + 1] = t - 5; totalCount += t - 5; } else { word[i + 7 + 1] = t; totalCount += t; } } if (c <= 3) // draw without meld { if (totalCount == 14) // cant draw more { return null; } var existingCount = c; for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == existingCount && word[i + 1] == 0) { word[i + 7 + 1] += 1; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c == 4) // draw with meld { if (totalCount == 14) // cant draw more { return null; } for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == 0 && word[i + 1] == 3) { word[i + 7 + 1] = 1; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c <= 8) // discard without meld { var existingCount = c - 4; for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == existingCount && word[i + 1] == 0) { word[i + 7 + 1] -= 1; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c == 9) // discard with meld { for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == 1 && word[i + 1] == 3) { word[i + 7 + 1] = 0; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c <= 11) // pon { if (totalCount == 14) // cant pon here { return null; } var existingCount = c - 8; for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == existingCount && word[i + 1] == 0) { word[i + 7 + 1] -= 2; word[i + 1] = 3; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c == 12) // daiminkan { if (totalCount == 14) // cant daiminkan here { return null; } for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == 3 && word[i + 1] == 0) { word[i + 7 + 1] = 0; word[i + 1] = 4; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c == 13) // chakan { for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == 1 && word[i + 1] == 3) { word[i + 7 + 1] = 0; word[i + 1] = 4; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } else if (c == 14) // ankan { for (var i = 0; i < 7; ++i) { if (word[i + 7 + 1] == 4 && word[i + 1] == 0) { word[i + 7 + 1] = 0; word[i + 1] = 4; break; } if (i == 6) // hand does not match up with action requirements { return null; } } } return GetId(word); } private static int GetId(IReadOnlyList<int> word) { var c = Enumerable.Range(0, 7).Select(i => word[i + 7 + 1] + word[i + 1] * 2 - word[i + 1] / 3); return c.OrderByDescending(x => x).Select((a, i) => a << i * 3).Sum(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedFirewallsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) DeleteFirewallRequest request = new DeleteFirewallRequest { RequestId = "", Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteFirewallRequest, CallSettings) // Additional: DeleteAsync(DeleteFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) DeleteFirewallRequest request = new DeleteFirewallRequest { RequestId = "", Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Delete(project, firewall); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.DeleteAsync(project, firewall); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) GetFirewallRequest request = new GetFirewallRequest { Project = "", Firewall = "", }; // Make the request Firewall response = firewallsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetFirewallRequest, CallSettings) // Additional: GetAsync(GetFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) GetFirewallRequest request = new GetFirewallRequest { Project = "", Firewall = "", }; // Make the request Firewall response = await firewallsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request Firewall response = firewallsClient.Get(project, firewall); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request Firewall response = await firewallsClient.GetAsync(project, firewall); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) InsertFirewallRequest request = new InsertFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertFirewallRequest, CallSettings) // Additional: InsertAsync(InsertFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) InsertFirewallRequest request = new InsertFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Insert(project, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, Firewall, CallSettings) // Additional: InsertAsync(string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.InsertAsync(project, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListFirewallsRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) ListFirewallsRequest request = new ListFirewallsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<FirewallList, Firewall> response = firewallsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Firewall item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (FirewallList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Firewall> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Firewall item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListFirewallsRequest, CallSettings) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) ListFirewallsRequest request = new ListFirewallsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<FirewallList, Firewall> response = firewallsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Firewall item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((FirewallList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Firewall> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Firewall item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<FirewallList, Firewall> response = firewallsClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (Firewall item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (FirewallList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Firewall> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Firewall item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<FirewallList, Firewall> response = firewallsClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Firewall item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((FirewallList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Firewall> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Firewall item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) PatchFirewallRequest request = new PatchFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchFirewallRequest, CallSettings) // Additional: PatchAsync(PatchFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) PatchFirewallRequest request = new PatchFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Patch(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, Firewall, CallSettings) // Additional: PatchAsync(string, string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.PatchAsync(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void UpdateRequestObject() { // Snippet: Update(UpdateFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) UpdateFirewallRequest request = new UpdateFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Update(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateRequestObjectAsync() { // Snippet: UpdateAsync(UpdateFirewallRequest, CallSettings) // Additional: UpdateAsync(UpdateFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) UpdateFirewallRequest request = new UpdateFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.UpdateAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void Update() { // Snippet: Update(string, string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Update(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateAsync() { // Snippet: UpdateAsync(string, string, Firewall, CallSettings) // Additional: UpdateAsync(string, string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.UpdateAsync(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
// The MIT License // // Copyright (c) 2012-2015 Jordan E. Terrell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace iSynaptic.Commons.Runtime.Serialization { public partial class CloneableTests { [Test] public void CloneString() { Assert.IsTrue(Cloneable<string>.CanClone()); Assert.IsTrue(Cloneable<string>.CanShallowClone()); Assert.AreEqual("Testing...", Cloneable<string>.Clone("Testing...")); Assert.AreEqual("Testing...", Cloneable<string>.ShallowClone("Testing...")); } [Test] public void CloneInt16() { Assert.IsTrue(Cloneable<Int16>.CanClone()); Assert.IsTrue(Cloneable<Int16>.CanShallowClone()); Assert.IsTrue(Cloneable<Int16?>.CanClone()); Assert.IsTrue(Cloneable<Int16?>.CanShallowClone()); Assert.AreEqual((Int16)(-16), Cloneable<Int16>.Clone(-16)); Assert.AreEqual((Int16)(-16), Cloneable<Int16>.ShallowClone(-16)); Assert.AreEqual((Int16?)(-16), Cloneable<Int16?>.Clone(-16)); Assert.AreEqual((Int16?)(-16), Cloneable<Int16?>.ShallowClone(-16)); Assert.AreEqual((Int16?)(null), Cloneable<Int16?>.Clone(null)); Assert.AreEqual((Int16?)(null), Cloneable<Int16?>.ShallowClone(null)); } [Test] public void CloneUInt16() { Assert.IsTrue(Cloneable<UInt16>.CanClone()); Assert.IsTrue(Cloneable<UInt16>.CanShallowClone()); Assert.IsTrue(Cloneable<UInt16?>.CanClone()); Assert.IsTrue(Cloneable<UInt16?>.CanShallowClone()); Assert.AreEqual((UInt16)16, Cloneable<UInt16>.Clone(16)); Assert.AreEqual((UInt16)16, Cloneable<UInt16>.ShallowClone(16)); Assert.AreEqual((UInt16?)16, Cloneable<UInt16?>.Clone(16)); Assert.AreEqual((UInt16?)16, Cloneable<UInt16?>.ShallowClone(16)); Assert.AreEqual((UInt16?)null, Cloneable<UInt16?>.Clone(null)); Assert.AreEqual((UInt16?)null, Cloneable<UInt16?>.ShallowClone(null)); } [Test] public void CloneInt32() { Assert.IsTrue(Cloneable<Int32>.CanClone()); Assert.IsTrue(Cloneable<Int32>.CanShallowClone()); Assert.IsTrue(Cloneable<Int32?>.CanClone()); Assert.IsTrue(Cloneable<Int32?>.CanShallowClone()); Assert.AreEqual((Int32)(-32), Cloneable<Int32>.Clone(-32)); Assert.AreEqual((Int32)(-32), Cloneable<Int32>.ShallowClone(-32)); Assert.AreEqual((Int32?)(-32), Cloneable<Int32?>.Clone(-32)); Assert.AreEqual((Int32?)(-32), Cloneable<Int32?>.ShallowClone(-32)); Assert.AreEqual((Int32?)(null), Cloneable<Int32?>.Clone(null)); Assert.AreEqual((Int32?)(null), Cloneable<Int32?>.ShallowClone(null)); } [Test] public void CloneUInt32() { Assert.IsTrue(Cloneable<UInt32>.CanClone()); Assert.IsTrue(Cloneable<UInt32>.CanShallowClone()); Assert.IsTrue(Cloneable<UInt32?>.CanClone()); Assert.IsTrue(Cloneable<UInt32?>.CanShallowClone()); Assert.AreEqual((UInt32)32, Cloneable<UInt32>.Clone(32)); Assert.AreEqual((UInt32)32, Cloneable<UInt32>.ShallowClone(32)); Assert.AreEqual((UInt32?)32, Cloneable<UInt32?>.Clone(32)); Assert.AreEqual((UInt32?)32, Cloneable<UInt32?>.ShallowClone(32)); Assert.AreEqual((UInt32?)null, Cloneable<UInt32?>.Clone(null)); Assert.AreEqual((UInt32?)null, Cloneable<UInt32?>.ShallowClone(null)); } [Test] public void CloneInt64() { Assert.IsTrue(Cloneable<Int64>.CanClone()); Assert.IsTrue(Cloneable<Int64>.CanShallowClone()); Assert.IsTrue(Cloneable<Int64?>.CanClone()); Assert.IsTrue(Cloneable<Int64?>.CanShallowClone()); Assert.AreEqual((Int64)(-64), Cloneable<Int64>.Clone(-64)); Assert.AreEqual((Int64)(-64), Cloneable<Int64>.ShallowClone(-64)); Assert.AreEqual((Int64?)(-64), Cloneable<Int64?>.Clone(-64)); Assert.AreEqual((Int64?)(-64), Cloneable<Int64?>.ShallowClone(-64)); Assert.AreEqual((Int64?)(null), Cloneable<Int64?>.Clone(null)); Assert.AreEqual((Int64?)(null), Cloneable<Int64?>.ShallowClone(null)); } [Test] public void CloneUInt64() { Assert.IsTrue(Cloneable<UInt64>.CanClone()); Assert.IsTrue(Cloneable<UInt64>.CanShallowClone()); Assert.IsTrue(Cloneable<UInt64?>.CanClone()); Assert.IsTrue(Cloneable<UInt64?>.CanShallowClone()); Assert.AreEqual((UInt64)64, Cloneable<UInt64>.Clone(64)); Assert.AreEqual((UInt64)64, Cloneable<UInt64>.ShallowClone(64)); Assert.AreEqual((UInt64?)64, Cloneable<UInt64?>.Clone(64)); Assert.AreEqual((UInt64?)64, Cloneable<UInt64?>.ShallowClone(64)); Assert.AreEqual((UInt64?)null, Cloneable<UInt64?>.Clone(null)); Assert.AreEqual((UInt64?)null, Cloneable<UInt64?>.ShallowClone(null)); } [Test] public void CloneByte() { Assert.IsTrue(Cloneable<Byte>.CanClone()); Assert.IsTrue(Cloneable<Byte>.CanShallowClone()); Assert.IsTrue(Cloneable<Byte?>.CanClone()); Assert.IsTrue(Cloneable<Byte?>.CanShallowClone()); Assert.AreEqual((Byte)(8), Cloneable<Byte>.Clone(8)); Assert.AreEqual((Byte)(8), Cloneable<Byte>.ShallowClone(8)); Assert.AreEqual((Byte?)(8), Cloneable<Byte?>.Clone(8)); Assert.AreEqual((Byte?)(8), Cloneable<Byte?>.ShallowClone(8)); Assert.AreEqual((Byte?)(null), Cloneable<Byte?>.Clone(null)); Assert.AreEqual((Byte?)(null), Cloneable<Byte?>.ShallowClone(null)); } [Test] public void CloneSByte() { Assert.IsTrue(Cloneable<SByte>.CanClone()); Assert.IsTrue(Cloneable<SByte>.CanShallowClone()); Assert.IsTrue(Cloneable<SByte?>.CanClone()); Assert.IsTrue(Cloneable<SByte?>.CanShallowClone()); Assert.AreEqual((SByte)(-8), Cloneable<SByte>.Clone(-8)); Assert.AreEqual((SByte)(-8), Cloneable<SByte>.ShallowClone(-8)); Assert.AreEqual((SByte?)(-8), Cloneable<SByte?>.Clone(-8)); Assert.AreEqual((SByte?)(-8), Cloneable<SByte?>.ShallowClone(-8)); Assert.AreEqual((SByte?)(null), Cloneable<SByte?>.Clone(null)); Assert.AreEqual((SByte?)(null), Cloneable<SByte?>.ShallowClone(null)); } [Test] public void CloneBoolean() { Assert.IsTrue(Cloneable<Boolean>.CanClone()); Assert.IsTrue(Cloneable<Boolean>.CanShallowClone()); Assert.IsTrue(Cloneable<Boolean?>.CanClone()); Assert.IsTrue(Cloneable<Boolean?>.CanShallowClone()); Assert.AreEqual(true, Cloneable<Boolean>.Clone(true)); Assert.AreEqual(true, Cloneable<Boolean>.ShallowClone(true)); Assert.AreEqual(true, Cloneable<Boolean?>.Clone(true)); Assert.AreEqual(true, Cloneable<Boolean?>.ShallowClone(true)); Assert.AreEqual(null, Cloneable<Boolean?>.Clone(null)); Assert.AreEqual(null, Cloneable<Boolean?>.ShallowClone(null)); } [Test] public void CloneDouble() { Assert.IsTrue(Cloneable<Double>.CanClone()); Assert.IsTrue(Cloneable<Double>.CanShallowClone()); Assert.IsTrue(Cloneable<Double?>.CanClone()); Assert.IsTrue(Cloneable<Double?>.CanShallowClone()); Assert.AreEqual((Double)128, Cloneable<Double>.Clone(128)); Assert.AreEqual((Double)128, Cloneable<Double>.ShallowClone(128)); Assert.AreEqual((Double?)128, Cloneable<Double?>.Clone(128)); Assert.AreEqual((Double?)128, Cloneable<Double?>.ShallowClone(128)); Assert.AreEqual((Double?)null, Cloneable<Double?>.Clone(null)); Assert.AreEqual((Double?)null, Cloneable<Double?>.ShallowClone(null)); } [Test] public void CloneDecimal() { Assert.IsTrue(Cloneable<decimal>.CanClone()); Assert.IsTrue(Cloneable<decimal>.CanShallowClone()); Assert.IsTrue(Cloneable<decimal?>.CanClone()); Assert.IsTrue(Cloneable<decimal?>.CanShallowClone()); Assert.AreEqual((decimal)128, Cloneable<decimal>.Clone(128)); Assert.AreEqual((decimal)128, Cloneable<decimal>.ShallowClone(128)); Assert.AreEqual((decimal?)128, Cloneable<decimal?>.Clone(128)); Assert.AreEqual((decimal?)128, Cloneable<decimal?>.ShallowClone(128)); Assert.AreEqual((decimal?)null, Cloneable<decimal?>.Clone(null)); Assert.AreEqual((decimal?)null, Cloneable<decimal?>.ShallowClone(null)); } [Test] public void CloneChar() { Assert.IsTrue(Cloneable<Char>.CanClone()); Assert.IsTrue(Cloneable<Char>.CanShallowClone()); Assert.IsTrue(Cloneable<Char?>.CanClone()); Assert.IsTrue(Cloneable<Char?>.CanShallowClone()); Assert.AreEqual('A', Cloneable<Char>.Clone('A')); Assert.AreEqual('A', Cloneable<Char>.ShallowClone('A')); Assert.AreEqual('A', Cloneable<Char?>.Clone('A')); Assert.AreEqual('A', Cloneable<Char?>.ShallowClone('A')); Assert.AreEqual(null, Cloneable<Char?>.Clone(null)); Assert.AreEqual(null, Cloneable<Char?>.ShallowClone(null)); } [Test] public void CloneSingle() { Assert.IsTrue(Cloneable<Single>.CanClone()); Assert.IsTrue(Cloneable<Single>.CanShallowClone()); Assert.IsTrue(Cloneable<Single?>.CanClone()); Assert.IsTrue(Cloneable<Single?>.CanShallowClone()); Assert.AreEqual((Single)64, Cloneable<Single>.Clone(64)); Assert.AreEqual((Single)64, Cloneable<Single>.ShallowClone(64)); Assert.AreEqual((Single?)64, Cloneable<Single?>.Clone(64)); Assert.AreEqual((Single?)64, Cloneable<Single?>.ShallowClone(64)); Assert.AreEqual((Single?)null, Cloneable<Single?>.Clone(null)); Assert.AreEqual((Single?)null, Cloneable<Single?>.ShallowClone(null)); } [Test] public void CloneGuid() { Guid id = new Guid("6C31A07E-F633-479b-836B-9479CD7EF92F"); Assert.IsTrue(Cloneable<Guid>.CanClone()); Assert.IsTrue(Cloneable<Guid>.CanShallowClone()); Assert.IsTrue(Cloneable<Guid?>.CanClone()); Assert.IsTrue(Cloneable<Guid?>.CanShallowClone()); Assert.AreEqual(id, Cloneable<Guid>.Clone(id)); Assert.AreEqual(id, Cloneable<Guid>.ShallowClone(id)); Assert.AreEqual(id, Cloneable<Guid?>.Clone(id)); Assert.AreEqual(id, Cloneable<Guid?>.ShallowClone(id)); Assert.AreEqual(null, Cloneable<Guid?>.Clone(null)); Assert.AreEqual(null, Cloneable<Guid?>.ShallowClone(null)); } [Test] public void CloneDateTime() { DateTime now = SystemClock.UtcNow; Assert.IsTrue(Cloneable<DateTime>.CanClone()); Assert.IsTrue(Cloneable<DateTime>.CanShallowClone()); Assert.IsTrue(Cloneable<DateTime?>.CanClone()); Assert.IsTrue(Cloneable<DateTime?>.CanShallowClone()); Assert.AreEqual(now, Cloneable<DateTime>.Clone(now)); Assert.AreEqual(now, Cloneable<DateTime>.ShallowClone(now)); Assert.AreEqual(now, Cloneable<DateTime?>.Clone(now)); Assert.AreEqual(now, Cloneable<DateTime?>.ShallowClone(now)); Assert.AreEqual(null, Cloneable<DateTime?>.Clone(null)); Assert.AreEqual(null, Cloneable<DateTime?>.ShallowClone(null)); } [Test] public void CloneTimeSpan() { TimeSpan source = TimeSpan.FromMinutes(5); Assert.IsTrue(Cloneable<TimeSpan>.CanClone()); Assert.IsTrue(Cloneable<TimeSpan>.CanShallowClone()); Assert.IsTrue(Cloneable<TimeSpan?>.CanClone()); Assert.IsTrue(Cloneable<TimeSpan?>.CanShallowClone()); Assert.AreEqual(source, Cloneable<TimeSpan>.Clone(source)); Assert.AreEqual(source, Cloneable<TimeSpan>.ShallowClone(source)); Assert.AreEqual(source, Cloneable<TimeSpan?>.Clone(source)); Assert.AreEqual(source, Cloneable<TimeSpan?>.ShallowClone(source)); Assert.AreEqual(null, Cloneable<TimeSpan?>.Clone(null)); Assert.AreEqual(null, Cloneable<TimeSpan?>.ShallowClone(null)); } [Test] public void CloneIntPtr() { var source = new IntPtr(42); Assert.IsTrue(Cloneable<IntPtr>.CanClone()); Assert.IsTrue(Cloneable<IntPtr>.CanShallowClone()); Assert.IsTrue(Cloneable<IntPtr?>.CanClone()); Assert.IsTrue(Cloneable<IntPtr?>.CanShallowClone()); Assert.AreEqual(source, Cloneable<IntPtr>.Clone(source)); Assert.AreEqual(source, Cloneable<IntPtr>.ShallowClone(source)); Assert.AreEqual(source, Cloneable<IntPtr?>.Clone(source)); Assert.AreEqual(source, Cloneable<IntPtr?>.ShallowClone(source)); Assert.AreEqual(null, Cloneable<IntPtr?>.Clone(null)); Assert.AreEqual(null, Cloneable<IntPtr?>.ShallowClone(null)); } [Test] public void CloneUIntPtr() { var source = new UIntPtr(42); Assert.IsTrue(Cloneable<UIntPtr>.CanClone()); Assert.IsTrue(Cloneable<UIntPtr>.CanShallowClone()); Assert.IsTrue(Cloneable<UIntPtr?>.CanClone()); Assert.IsTrue(Cloneable<UIntPtr?>.CanShallowClone()); Assert.AreEqual(source, Cloneable<UIntPtr>.Clone(source)); Assert.AreEqual(source, Cloneable<UIntPtr>.ShallowClone(source)); Assert.AreEqual(source, Cloneable<UIntPtr?>.Clone(source)); Assert.AreEqual(source, Cloneable<UIntPtr?>.ShallowClone(source)); Assert.AreEqual(null, Cloneable<UIntPtr?>.Clone(null)); Assert.AreEqual(null, Cloneable<UIntPtr?>.ShallowClone(null)); } [Test] public void CannotCloneDelegate() { Assert.IsFalse(Cloneable<Action>.CanClone()); Assert.IsFalse(Cloneable<Action>.CanShallowClone()); Assert.Throws<InvalidOperationException>(() => Cloneable<Action>.Clone(null)); Assert.Throws<InvalidOperationException>(() => Cloneable<Action>.ShallowClone(null)); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; using SharpDX.Mathematics.Interop; namespace SharpDX.DirectWrite { public partial class TextAnalyzer { /// <summary> /// Returns an interface for performing text analysis. /// </summary> /// <param name="factory">A reference to a DirectWrite factory <see cref="Factory"/></param> /// <unmanaged>HRESULT IDWriteFactory::CreateTextAnalyzer([Out] IDWriteTextAnalyzer** textAnalyzer)</unmanaged> public TextAnalyzer(Factory factory) { factory.CreateTextAnalyzer(this); } /// <summary> /// Analyzes a text range for script boundaries, reading text attributes from the source and reporting the Unicode script ID to the sink callback {{SetScript}}. /// </summary> /// <param name="analysisSource">A reference to the source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeScript([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> public void AnalyzeScript(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeScript__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for script directionality, reading attributes from the source and reporting levels to the sink callback {{SetBidiLevel}}. /// </summary> /// <param name="analysisSource">A reference to a source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeBidi([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// While the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs. Otherwise, the returned levels may be wrong, because the Bidi algorithm is meant to apply to the paragraph as a whole. /// </remarks> public void AnalyzeBidi(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeBidi__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for spans where number substitution is applicable, reading attributes from the source and reporting substitutable ranges to the sink callback {{SetNumberSubstitution}}. /// </summary> /// <param name="analysisSource">The source object to analyze.</param> /// <param name="textPosition">The starting position within the source object.</param> /// <param name="textLength">The length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeNumberSubstitution([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// Although the function can handle multiple ranges of differing number substitutions, the text ranges should not arbitrarily split the middle of numbers. Otherwise, it will treat the numbers separately and will not translate any intervening punctuation. /// </remarks> public void AnalyzeNumberSubstitution(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeNumberSubstitution__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Analyzes a text range for potential breakpoint opportunities, reading attributes from the source and reporting breakpoint opportunities to the sink callback {{SetLineBreakpoints}}. /// </summary> /// <param name="analysisSource">A reference to the source object to analyze.</param> /// <param name="textPosition">The starting text position within the source object.</param> /// <param name="textLength">The text length to analyze.</param> /// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeLineBreakpoints([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged> /// <remarks> /// Although the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs, unless the specified text span is considered a whole unit. Otherwise, the returned properties for the first and last characters will inappropriately allow breaks. /// </remarks> public void AnalyzeLineBreakpoints(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink) { AnalyzeLineBreakpoints__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink)); } /// <summary> /// Gets the glyphs (TODO doc) /// </summary> /// <param name="textString">The text string.</param> /// <param name="textLength">Length of the text.</param> /// <param name="fontFace">The font face.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="numberSubstitution">The number substitution.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="maxGlyphCount">The max glyph count.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="actualGlyphCount">The actual glyph count.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphs([In, Buffer] const wchar_t* textString,[In] unsigned int textLength,[In] IDWriteFontFace* fontFace,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] IDWriteNumberSubstitution* numberSubstitution,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[In] unsigned int maxGlyphCount,[Out, Buffer] unsigned short* clusterMap,[Out, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[Out, Buffer] unsigned short* glyphIndices,[Out, Buffer] DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[Out] unsigned int* actualGlyphCount)</unmanaged> public void GetGlyphs(string textString, int textLength, SharpDX.DirectWrite.FontFace fontFace, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, SharpDX.DirectWrite.NumberSubstitution numberSubstitution, FontFeature[][] features, int[] featureRangeLengths, int maxGlyphCount, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, out int actualGlyphCount) { var pFeatures = AllocateFeatures(features); try { GetGlyphs( textString, textLength, fontFace, isSideways, isRightToLeft, scriptAnalysis, localeName, numberSubstitution, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, maxGlyphCount, clusterMap, textProps, glyphIndices, glyphProps, out actualGlyphCount); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font in ems.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the GDI compatible glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font em.</param> /// <param name="pixelsPerDip">The pixels per dip.</param> /// <param name="transform">The transform.</param> /// <param name="useGdiNatural">if set to <c>true</c> [use GDI natural].</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGdiCompatibleGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] float pixelsPerDip,[In, Optional] const DWRITE_MATRIX* transform,[In] BOOL useGdiNatural,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGdiCompatibleGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, float pixelsPerDip, RawMatrix3x2? transform, bool useGdiNatural, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGdiCompatibleGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, pixelsPerDip, transform, useGdiNatural, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Allocates the features from the jagged array.. /// </summary> /// <param name="features">The features.</param> /// <returns>A pointer to the allocated native features or 0 if features is null or empty.</returns> private static IntPtr AllocateFeatures(FontFeature[][] features) { unsafe { var pFeatures = (byte*)0; if (features != null && features.Length > 0) { // Calculate the total size of the buffer to allocate: // (0) (1) (2) // ------------------------------------------------------------- // | array | TypographicFeatures || FontFeatures || // | ptr to (1) | | | || || // | | ptr to FontFeatures || || // ------------------------------------------------------------- // Offset in bytes to (1) int offsetToTypographicFeatures = sizeof(IntPtr) * features.Length; // Add offset (1) and Size in bytes to (1) int calcSize = offsetToTypographicFeatures + sizeof(TypographicFeatures) * features.Length; // Calculate size (2) foreach (var fontFeature in features) { if (fontFeature == null) throw new ArgumentNullException("features", "FontFeature[] inside features array cannot be null."); // calcSize += typographicFeatures.Length * sizeof(FontFeature) calcSize += sizeof(FontFeature) * fontFeature.Length; } // Allocate the whole buffer pFeatures = (byte*)Marshal.AllocHGlobal(calcSize); // Pointer to (1) var pTypographicFeatures = (TypographicFeatures*)(pFeatures + offsetToTypographicFeatures); // Pointer to (2) var pFontFeatures = (FontFeature*)(pTypographicFeatures + features.Length); // Iterate on features and copy them to (2) for (int i = 0; i < features.Length; i++) { // Write array pointers in (0) ((void**)pFeatures)[i] = pTypographicFeatures; var featureSet = features[i]; // Write TypographicFeatures in (1) pTypographicFeatures->Features = (IntPtr)pFontFeatures; pTypographicFeatures->FeatureCount = featureSet.Length; pTypographicFeatures++; // Write FontFeatures in (2) for (int j = 0; j < featureSet.Length; j++) { *pFontFeatures = featureSet[j]; pFontFeatures++; } } } return (IntPtr)pFeatures; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Xunit; using static Oxide.Options; namespace Oxide.Tests { public class OptionTests { public static IEnumerable<object[]> Options() { yield return new object[] { Some(5L) }; yield return new object[] { None<long>() }; } #region IsNone/IsSome Tests [Fact] public void Some_is_not_none() => Assert.False(Some(1).IsNone); [Fact] public void Some_is_some() => Assert.True(Some(1).IsSome); [Fact] public void None_is_none() => Assert.True(None<int>().IsNone); [Fact] public void None_is_not_some() => Assert.False(None<int>().IsSome); #endregion #region Equality Tests [Theory] [MemberData(nameof(Options))] public void Is_never_equal_to_null(Option opt) => Assert.False(opt.Equals(null)); [Fact] public void Equals_with_null_rhs_returns_false() => Assert.False(Some(5).Equals(null)); [Theory] [MemberData(nameof(Options))] public void Op_equality_is_correct_for_null(Option opt) => Assert.False(opt == null); [Theory] [MemberData(nameof(Options))] public void Op_equality_is_correct_when_null_is_left(Option opt) => Assert.False(null == opt); [Theory] [MemberData(nameof(Options))] public void Op_inequality_is_correct_when_null_is_left(Option opt) => Assert.True(null != opt); [Theory] [MemberData(nameof(Options))] public void Op_inequality_is_correct_for_null(Option opt) => Assert.True(opt != null); [Fact] public void Some_is_not_equal_to_none() => Assert.False(Some(5).Equals(None<int>())); [Fact] public void Op_equality_is_correct_for_some_and_none() => Assert.False(Some(5) == None<int>()); [Fact] public void Op_inequality_is_correct_for_some_and_none() => Assert.True(Some(5) != None<int>()); [Fact] public void None_is_equal_to_none() => Assert.True(None<int>().Equals(None<int>())); [Fact] [SuppressMessage("ReSharper", "EqualExpressionComparison")] public void Op_equality_is_correct_for_none() => Assert.True(None<int>() == None<int>()); [Fact] [SuppressMessage("ReSharper", "EqualExpressionComparison")] public void Op_inequality_is_correct_for_none() => Assert.False(None<int>() != None<int>()); [Fact] public void Somes_with_different_values_are_not_equal() => Assert.False(Some(5).Equals(Some(10))); [Fact] public void Op_equality_is_correct_for_some_with_different_value() => Assert.False(Some(5) == Some(10)); [Fact] public void Op_inequality_is_correct_for_some_with_different_value() => Assert.True(Some(5) != Some(10)); [Fact] public void Somes_with_same_value_are_equal() => Assert.True(Some(5).Equals(Some(5))); [Fact] [SuppressMessage("ReSharper", "EqualExpressionComparison")] public void Op_equality_is_correct_for_somes_with_same_value() => Assert.True(Some(5) == Some(5)); [Fact] [SuppressMessage("ReSharper", "EqualExpressionComparison")] public void Op_inequality_is_correct_for_somes_with_same_value() => Assert.False(Some(5) != Some(5)); [Fact] public void Object_equals_is_correct_for_non_options() => Assert.False(Some(5).Equals(new object())); [Fact] public void Object_equals_is_correct_for_matching_values() => Assert.True(Some(5).Equals((object)Some(5))); [Fact] public void Object_equals_is_correct_for_mismatched_values() => Assert.False(Some(5).Equals((object)Some(10))); [Fact] [SuppressMessage("ReSharper", "SuspiciousTypeConversion.Global")] public void Object_equals_is_correct_for_mismatched_types() => Assert.False(Some(5).Equals(Some(10L))); [Fact] public void Object_equals_is_correct_for_some_and_none() => Assert.False(Some(5).Equals((object)None<int>())); [Fact] public void Object_equals_is_correct_for_none_and_none() => Assert.True(None<int>().Equals((object)None<int>())); #endregion #region Expect/Unwrap Tests [Fact] public void Expecting_some_returns_value() => Assert.Equal(5, Some(5).Expect("Expected value, got None.")); [Fact] public void Try_unwrap_returns_true_for_some() { int value; Assert.True(Some(int.MaxValue).TryUnwrap(out value)); Assert.Equal(int.MaxValue, value); } [Fact] public void Try_unwrap_returns_false_for_none() { Assert.False(None<int>().TryUnwrap(out var value)); // `out` requires us to set a value, and the value for a None<T> // is default(T). Assert.Equal(default, value); } [Fact] public void Expecting_none_throws_exception_matching_string() { string message = "Expected 5, got None."; var ex = Assert.Throws<InvalidOperationException>(() => None<int>().Expect(message)); Assert.Equal(message, ex.Message); } [Fact] public void Unwrapping_some_returns_value() => Assert.Equal(5, Some(5).Unwrap()); [Fact] public void Unwrapping_none_throws_exception() { var ex = Assert.Throws<InvalidOperationException>(() => None<int>().Unwrap()); Assert.Equal("Tried to unwrap a None<System.Int32>!", ex.Message); } [Fact] public void Unwrap_or_some_returns_some() => Assert.Equal(5, Some(5).UnwrapOr(10)); [Fact] public void Unwrap_or_none_returns_given_value() => Assert.Equal(10, None<int>().UnwrapOr(10)); [Fact] public void Unwrap_or_none_with_unspecified_value_returns_default() => Assert.Equal(default, None<long>().UnwrapOr()); [Fact] public void Unwrap_or_function_does_not_call_function_with_some() { var called = false; long Or() { called = true; return 10; } var result = Some(5L).UnwrapOr(Or); Assert.Equal(5, result); Assert.False(called); } [Fact] public void Unwrap_or_function_does_call_function_with_none() { var called = false; long Or() { called = true; return 10; } var result = None<long>().UnwrapOr(Or); Assert.Equal(10, result); Assert.True(called); } #endregion #region Map Tests [Fact] public void Mapping_some_returns_some_with_value() { double Mapper(long value) => Math.Pow(2, value); var some = Some(10L); var result = some.Map(Mapper); Assert.IsType<Some<double>>(result); Assert.NotSame(some, result); Assert.Equal(1024, result.Unwrap()); } [Fact] public void Mapping_none_returns_none() { double Mapper(long value) => Math.Pow(2, value); var none = None<long>(); var result = none.Map(Mapper); Assert.IsType<None<double>>(result); Assert.True(result.IsNone); } [Fact] public async Task Async_mapping_returns_awaitable_option() { Task<double> Mapper(long value) => Task.Run(() => Math.Pow(2, value)); var some = Some(16L); var result = some.MapAsync(Mapper); var newSome = await result; Assert.IsType<Some<double>>(newSome); Assert.Equal(65536, newSome.Unwrap()); } [Fact] public async Task Async_mapping_on_a_none_returns_none() { Task<double> Mapper(long value) => Task.Run(() => Math.Pow(2, value)); var none = None<long>(); var result = await none.MapAsync(Mapper); Assert.IsType<None<double>>(result); Assert.True(result.IsNone); } [Fact] public async Task Can_unwrap_task_of_option_into_task_of_t() { Task<double> Mapper(long value) => Task.Run(() => Math.Pow(2, value)); var some = Some(16L); var result = await some.MapAsync(Mapper).UnwrapAsync(); Assert.Equal(65536.0, result); } [Fact] public async Task Unwrapping_task_of_none_throws_as_expected() { Task<double> Mapper(long value) => Task.Run(() => Math.Pow(2, value)); var none = None<long>(); var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => none.MapAsync(Mapper).UnwrapAsync() ); Assert.Equal("Tried to unwrap a None<System.Double>!", ex.Message); } [Fact] public void Map_or_converts_value_if_some() => Assert.Equal( 65536, Some(16L).MapOr(val => Math.Pow(2, val), 10.0) ); [Fact] public void Map_or_returns_default_value_if_none() => Assert.Equal( 10.0, None<long>().MapOr(val => Math.Pow(2, val), 10.0) ); [Fact] public void Map_or_with_function_converts_value_if_some() => Assert.Equal( 65536, Some(16L).MapOr(val => Math.Pow(2, val), () => 10.0) ); [Fact] public void Map_or_with_function_provides_value_if_none() => Assert.Equal( 10.0, None<long>().MapOr(val => Math.Pow(2, val), () => 10.0) ); #endregion #region And Tests [Theory] [MemberData(nameof(Options))] public void Some_and_option_returns_option(Option<long> opt) => Assert.True(Some(1L).And(opt) == opt); [Theory] [MemberData(nameof(Options))] public void None_and_option_returns_none(Option<long> opt) => Assert.True(None<long>().And(opt).IsNone); [Fact] public void Some_and_then_func_returns_transform() => Assert.Equal(50, Some(10).AndThen<int>(val => 5*val)); [Fact] public void Some_and_finally_returns_some_and_calls_function() { var called = false; var some = Some(5); var res = some.Finally(val => called = true); Assert.Same(some, res); Assert.True(called); } [Fact] public void None_and_finally_returns_some_and_does_not_call_function() { var called = false; var none = None<int>(); var res = none.Finally(val => called = true); Assert.Same(none, res); Assert.False(called); } [Fact] public void None_and_ifnone_returns_none_and_calls_function() { var called = false; var none = None<int>(); var res = none.IfNone(() => called = true); Assert.Same(none, res); Assert.True(called); } [Fact] public void Some_and_ifnone_returns_some_and_does_not_call_function() { var called = false; var some = Some(5); var res = some.IfNone(() => called = true); Assert.Same(some, res); Assert.False(called); } [Fact] public void None_and_then_returns_none_of_correct_type() { var result = None<int>().AndThen<string>(val => val.ToString()); Assert.IsType<None<string>>(result); Assert.True(result.IsNone); } [Fact] public async Task Async_some_and_then_returns_transformed_value() { var timespan = TimeSpan.FromSeconds(1); var some = Some(timespan); var res = await some.AndThenAsync<double>(async ts => { await Task.Delay(ts); return ts.TotalDays; }).UnwrapAsync(); Assert.Equal(timespan.TotalDays, res); } [Fact] public async Task Continue_task_of_option_without_await() { var timespan = TimeSpan.FromSeconds(1); var task = Task.FromResult(Some(timespan)); var res = await task.AndThenAsync(ts => Some(ts.TotalDays)); Assert.Equal(timespan.TotalDays, res); } [Fact] public async Task Continue_task_of_option_with_async_continuation() { var timespan = TimeSpan.FromSeconds(1); var task = Task.FromResult(Some(timespan)); var res = await task.AndThenAsync(async ts => { await Task.Delay(ts); return Some(ts.TotalDays); }); Assert.Equal(timespan.TotalDays, res); } [Fact] public async Task Async_none_and_then_returns_none() { var none = None<TimeSpan>(); var res = await none.AndThenAsync<double>(async ts => await Task.FromResult(ts.TotalDays)); Assert.IsType<None<double>>(res); Assert.True(res.IsNone); } #endregion #region Or Tests [Fact] public void Some_or_other_returns_original() => Assert.Equal(10, Some(10).Or(5).Unwrap()); [Fact] public void None_or_other_returns_other() => Assert.Equal(5, None<int>().Or(5).Unwrap()); [Fact] public void Some_or_else_other_returns_original() => Assert.Equal(10, Some(10).OrElse(() => 5).Unwrap()); [Fact] public void None_or_else_other_returns_other() => Assert.Equal(5, None<int>().OrElse(() => 5).Unwrap()); [Fact] public async Task Async_some_or_else_returns_this() { var timespan = TimeSpan.FromSeconds(1); var some = Some(timespan); var called = false; var res = await some.OrElseAsync(async () => { await Task.Delay(timespan); called = true; return TimeSpan.FromSeconds(10); }); Assert.Same(some, res); Assert.False(called); } [Fact] public async Task Async_none_or_else_returns_other() { var timespan = TimeSpan.FromSeconds(1); var none = None<TimeSpan>(); var called = false; var res = await none.OrElseAsync(async () => { await Task.Delay(timespan); called = true; return TimeSpan.FromSeconds(10); }); Assert.NotSame(none, res); Assert.True(called); Assert.Equal(TimeSpan.FromSeconds(10), res.Unwrap()); } #endregion #region Hashcode Tests [Fact] public void Get_hash_code_returns_zero_for_none() => Assert.Equal(0, None<int>().GetHashCode()); [Fact] public void Get_hash_code_for_some_with_null_returns_minus_one() => Assert.Equal(-1, Some<string>(null).GetHashCode()); [Fact] public void Get_hash_code_returns_hashcode_of_value() { var obj = new object(); Assert.Equal(obj.GetHashCode(), Some(obj).GetHashCode()); } #endregion #region Miscellaneous Tests [Fact] public void ReferenceTypeCanBeSomeWithNull() { var some = Some<string>(null); Assert.True(some.IsSome); Assert.False(some.IsNone); Assert.Null(some.Unwrap()); } #endregion } }
using System; using System.Collections.Generic; using System.Reflection; using sly.lexer; using sly.parser.parser; using sly.parser.syntax.tree; using static sly.parser.parser.ValueOptionConstructors; namespace sly.parser.generator.visitor { public class SyntaxVisitorResult<IN, OUT> where IN : struct { public List<Group<IN, OUT>> GroupListResult; public Group<IN, OUT> GroupResult; public ValueOption<Group<IN, OUT>> OptionGroupResult; public ValueOption<OUT> OptionResult; public List<Token<IN>> TokenListResult; public Token<IN> TokenResult; public List<OUT> ValueListResult; public OUT ValueResult; public bool IsOption => OptionResult != null; public bool IsOptionGroup => OptionGroupResult != null; public bool IsToken { get; private set; } public bool Discarded => IsToken && TokenResult != null && TokenResult.Discarded; public bool IsValue { get; private set; } public bool IsValueList { get; private set; } public bool IsGroupList { get; private set; } public bool IsTokenList { get; private set; } public bool IsGroup { get; private set; } public bool IsNone => !IsToken && !IsValue && !IsTokenList && !IsValueList && !IsGroup && !IsGroupList; public static SyntaxVisitorResult<IN, OUT> NewToken(Token<IN> tok) { var res = new SyntaxVisitorResult<IN, OUT>(); res.TokenResult = tok; res.IsToken = true; return res; } public static SyntaxVisitorResult<IN, OUT> NewValue(OUT val) { var res = new SyntaxVisitorResult<IN, OUT>(); res.ValueResult = val; res.IsValue = true; return res; } public static SyntaxVisitorResult<IN, OUT> NewValueList(List<OUT> values) { var res = new SyntaxVisitorResult<IN, OUT>(); res.ValueListResult = values; res.IsValueList = true; return res; } public static SyntaxVisitorResult<IN, OUT> NewGroupList(List<Group<IN, OUT>> values) { var res = new SyntaxVisitorResult<IN, OUT>(); res.GroupListResult = values; res.IsGroupList = true; return res; } public static SyntaxVisitorResult<IN, OUT> NewTokenList(List<Token<IN>> tokens) { var res = new SyntaxVisitorResult<IN, OUT>(); res.TokenListResult = tokens; res.IsTokenList = true; return res; } public static SyntaxVisitorResult<IN, OUT> NewOptionSome(OUT value) { var res = new SyntaxVisitorResult<IN, OUT>(); res.OptionResult = Some(value); return res; } public static SyntaxVisitorResult<IN, OUT> NewOptionGroupSome(Group<IN, OUT> group) { var res = new SyntaxVisitorResult<IN, OUT>(); res.OptionGroupResult = Some(group); return res; } public static SyntaxVisitorResult<IN, OUT> NewOptionGroupNone() { var res = new SyntaxVisitorResult<IN, OUT>(); res.OptionGroupResult = NoneGroup<IN,OUT>(); return res; } public static SyntaxVisitorResult<IN, OUT> NewOptionNone() { var res = new SyntaxVisitorResult<IN, OUT>(); res.OptionResult = None<OUT>(); return res; } public static SyntaxVisitorResult<IN, OUT> NewGroup(Group<IN, OUT> group) { var res = new SyntaxVisitorResult<IN, OUT>(); res.GroupResult = group; res.IsGroup = true; return res; } public static SyntaxVisitorResult<IN, OUT> NoneResult() { var res = new SyntaxVisitorResult<IN, OUT>(); return res; } } public class SyntaxTreeVisitor<IN, OUT> where IN : struct { public SyntaxTreeVisitor(ParserConfiguration<IN, OUT> conf, object parserInstance) { ParserClass = ParserClass; Configuration = conf; ParserVsisitorInstance = parserInstance; } public Type ParserClass { get; set; } public object ParserVsisitorInstance { get; set; } public ParserConfiguration<IN, OUT> Configuration { get; set; } public OUT VisitSyntaxTree(ISyntaxNode<IN> root, object context = null) { var result = Visit(root, context); return result.ValueResult; } protected virtual SyntaxVisitorResult<IN, OUT> Visit(ISyntaxNode<IN> n, object context = null) { if (n is SyntaxLeaf<IN>) return Visit(n as SyntaxLeaf<IN>); if (n is SyntaxNode<IN>) return Visit(n as SyntaxNode<IN>, context); return null; } private SyntaxVisitorResult<IN, OUT> Visit(SyntaxNode<IN> node, object context = null) { var result = SyntaxVisitorResult<IN, OUT>.NoneResult(); if (node.Visitor != null || node.IsByPassNode) { var args = new List<object>(); var i = 0; foreach (var n in node.Children) { var v = Visit(n,context); if (v.IsToken) { if (!v.Discarded) args.Add(v.TokenResult); } else if (v.IsValue) { args.Add(v.ValueResult); } i++; } if (node.IsByPassNode) { result = SyntaxVisitorResult<IN, OUT>.NewValue((OUT) args[0]); } else { MethodInfo method = null; try { if (!(context is NoContext)) { args.Add(context); } method = node.Visitor; var t = method?.Invoke(ParserVsisitorInstance, args.ToArray()); var res = (OUT) t; result = SyntaxVisitorResult<IN, OUT>.NewValue(res); } catch (TargetInvocationException tie) { if (tie.InnerException != null) { throw tie.InnerException; } } } } return result; } private SyntaxVisitorResult<IN, OUT> Visit(SyntaxLeaf<IN> leaf) { return SyntaxVisitorResult<IN, OUT>.NewToken(leaf.Token); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.Extensions.Localization { public class CookieRequestCultureProviderTest { [Fact] public async Task GetCultureInfoFromPersistentCookie() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }; var provider = new CookieRequestCultureProvider { CookieName = "Preferences" }; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = new CultureInfo("ar-SA"); var requestCulture = new RequestCulture(culture); var value = CookieRequestCultureProvider.MakeCookieValue(requestCulture); client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", value).ToString()); var response = await client.GetAsync(string.Empty); Assert.Equal("c=ar-SA|uic=ar-SA", value); } } [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }; var provider = new CookieRequestCultureProvider { CookieName = "Preferences" }; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("en-US", requestCulture.Culture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", "uic=ar-SA").ToString()); var response = await client.GetAsync(string.Empty); } } [Fact] public async Task GetDefaultCultureInfoIfCookieDoesNotExist() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-SA") } }; var provider = new CookieRequestCultureProvider { CookieName = "Preferences" }; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("en-US", requestCulture.Culture.Name); return Task.FromResult(0); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); } } [Fact] public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures() { var sink = new TestSink( TestSink.EnableWithTypeName<RequestLocalizationMiddleware>, TestSink.EnableWithTypeName<RequestLocalizationMiddleware>); var loggerFactory = new TestLoggerFactory(sink, enabled: true); using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-YE") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-YE") } }; var provider = new CookieRequestCultureProvider { CookieName = "Preferences" }; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => Task.CompletedTask); }) .ConfigureServices(services => { services.AddSingleton(typeof(ILoggerFactory), loggerFactory); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "??"; var uiCulture = "ar-YE"; client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", $"c={culture}|uic={uiCulture}").ToString()); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } var expectedMessage = $"{nameof(CookieRequestCultureProvider)} returned the following unsupported cultures '??'."; var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); } [Fact] public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICultures() { var sink = new TestSink( TestSink.EnableWithTypeName<RequestLocalizationMiddleware>, TestSink.EnableWithTypeName<RequestLocalizationMiddleware>); var loggerFactory = new TestLoggerFactory(sink, enabled: true); using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("ar-YE") }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("ar-YE") } }; var provider = new CookieRequestCultureProvider { CookieName = "Preferences" }; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => Task.CompletedTask); }) .ConfigureServices(services => { services.AddSingleton(typeof(ILoggerFactory), loggerFactory); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "ar-YE"; var uiCulture = "??"; client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", $"c={culture}|uic={uiCulture}").ToString()); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } var expectedMessage = $"{nameof(CookieRequestCultureProvider)} returned the following unsupported UI Cultures '??'."; var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Newtonsoft.Json; using NJsonSchema.Annotations; using Xunit; namespace NJsonSchema.Tests.Generation { public class AnnotationsGenerationTests { public class AnnotationClass { public MyPoint Point { get; set; } [JsonSchema(JsonObjectType.String, Format = "point")] public AnnotationClass ClassAsString { get; set; } [JsonSchema(JsonObjectType.String, Format = "point")] public class MyPoint { public decimal X { get; set; } public decimal Y { get; set; } } } [Fact] public async Task When_class_annotation_is_available_then_type_and_format_can_be_customized() { //// Arrange var schema = JsonSchema.FromType<AnnotationClass>(); var data = schema.ToJson(); //// Act var property = schema.Properties["Point"]; //// Assert Assert.True(property.Type.HasFlag(JsonObjectType.String)); Assert.Equal("point", property.Format); } [Fact] public async Task When_property_annotation_is_available_then_type_and_format_can_be_customized() { //// Arrange var schema = JsonSchema.FromType<AnnotationClass>(); var data = schema.ToJson(); //// Act var property = schema.Properties["ClassAsString"]; //// Assert Assert.True(property.Type.HasFlag(JsonObjectType.String)); Assert.Equal("point", property.Format); } public class DateAttributeClass { [JsonSchemaDate] public DateTime Date { get; set; } } [Fact] public async Task When_DateTime_property_has_JsonSchemaDate_attribute_then_format_and_type_is_correct() { //// Arrange var schema = JsonSchema.FromType<DateAttributeClass>(); var data = schema.ToJson(); //// Act var property = schema.Properties["Date"]; //// Assert Assert.True(property.Type.HasFlag(JsonObjectType.String)); Assert.Equal("date", property.Format); } public class MultipleOfClass { [MultipleOf(4.5)] public double Number { get; set; } } [Fact] public async Task When_multipleOf_attribute_is_available_then_value_is_set_in_schema() { //// Arrange //// Act var schema = JsonSchema.FromType<MultipleOfClass>(); var property = schema.Properties["Number"]; //// Assert Assert.Equal(4.5m, property.MultipleOf.Value); } public class SimpleClass { [JsonProperty("number")] public decimal Number { get; set; } public SimpleClass(decimal number) { Number = number; } } [Fact] public async Task When_multipleOf_is_fraction_then_it_is_validated_correctly() { //// Arrange List<SimpleClass> testClasses = new List<SimpleClass>(); for (int i = 0; i < 100; i++) { testClasses.Add(new SimpleClass((decimal)(0.1 * i))); } string jsonData = JsonConvert.SerializeObject(testClasses, Formatting.Indented); var schema = await JsonSchema.FromJsonAsync(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""number"": { ""type"": ""number"", ""multipleOf"": 0.1, ""minimum"": 0.0, ""maximum"": 4903700.0 } }, ""required"": [ ""number"" ] } }"); //// Act var errors = schema.Validate(jsonData); //// Assert Assert.Equal(0, errors.Count); } [JsonSchema(JsonObjectType.Array, ArrayItem = typeof(string))] public class ArrayModel : IEnumerable<string> { public IEnumerator<string> GetEnumerator() { return null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Fact] public async Task When_class_has_array_item_type_defined_then_schema_has_this_item_type() { //// Arrange var schema = JsonSchema.FromType<ArrayModel>(); //// Act var data = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.String, schema.Item.Type); } [JsonSchema(JsonObjectType.Array, ArrayItem = typeof(string))] public class ArrayModel<T> : List<T> { } [Fact] public async Task When_class_has_array_item_type_defined_then_schema_has_this_item_type2() { //// Arrange var schema = JsonSchema.FromType<ArrayModel<string>>(); //// Act var data = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.String, schema.Item.Type); } public class MyStructContainer { public MyStruct Struct { get; set; } public MyStruct? NullableStruct { get; set; } } [JsonSchema(JsonObjectType.String)] public struct MyStruct { } [Fact] public async Task When_property_is_struct_then_it_is_not_nullable() { //// Arrange var schema = JsonSchema.FromType<MyStructContainer>(); //// Act var data = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Struct"].Type); Assert.Equal(JsonObjectType.String | JsonObjectType.Null, schema.Properties["NullableStruct"].Type); } public class StringLengthAttributeClass { [StringLength(10, MinimumLength = 5)] public string Foo { get; set; } } [Fact] public async Task When_StringLengthAttribute_is_set_then_minLength_and_maxLenght_is_set() { //// Arrange //// Act var schema = JsonSchema.FromType<StringLengthAttributeClass>(); //// Assert var property = schema.Properties["Foo"]; Assert.Equal(5, property.MinLength); Assert.Equal(10, property.MaxLength); } public class MinLengthAttributeClass { [MinLength(1)] public int[] Items { get; set; } [MinLength(50)] public string Foo { get; set; } } [Fact] public async Task When_MinLengthAttribute_is_set_then_minItems_or_minLength_is_set() { var schema = JsonSchema.FromType<MinLengthAttributeClass>(); var arrayProperty = schema.Properties["Items"]; Assert.Equal(1, arrayProperty.MinItems); var stringProperty = schema.Properties["Foo"]; Assert.Equal(50, stringProperty.MinLength); } public class MaxLengthAttributeClass { [MaxLength(100)] public int[] Items { get; set; } [MaxLength(500)] public string Foo { get; set; } } [Fact] public async Task When_MaxLengthAttribute_is_set_then_maxItems_or_maxLength_is_set() { var schema = JsonSchema.FromType<MaxLengthAttributeClass>(); var arrayProperty = schema.Properties["Items"]; Assert.Equal(100, arrayProperty.MaxItems); var stringProperty = schema.Properties["Foo"]; Assert.Equal(500, stringProperty.MaxLength); } public class StringRequiredClass { [Required(AllowEmptyStrings = false)] public string Foo { get; set; } } [Fact] public async Task When_RequiredAttribute_is_set_with_AllowEmptyStrings_false_then_minLength_and_required_are_set() { //// Arrange //// Act var schema = JsonSchema.FromType<StringRequiredClass>(); //// Assert var property = schema.Properties["Foo"]; Assert.Equal(1, property.MinLength); Assert.True(property.IsRequired); } public class DtoRequiredClass { [Required(AllowEmptyStrings = false)] public StringRequiredClass Foo { get; set; } } [Fact] public async Task When_RequiredAttribute_is_set_with_AllowEmptyStrings_false_on_class_property_then_minLength_is_not_set() { //// Arrange //// Act var schema = JsonSchema.FromType<DtoRequiredClass>(); var json = schema.ToJson(); //// Assert var property = schema.Properties["Foo"]; Assert.Null(property.MinLength); Assert.True(property.IsRequired); } public class DataTypeAttributeClass { [DataType(DataType.EmailAddress)] public string EmailAddress { get; set; } [DataType(DataType.PhoneNumber)] public string PhoneNumber { get; set; } [DataType(DataType.DateTime)] public string DateTime { get; set; } [DataType(DataType.Date)] public string Date { get; set; } [DataType(DataType.Time)] public string Time { get; set; } [DataType(DataType.Url)] public string Url { get; set; } [EmailAddress] // should be equivalent to [DataType(DataType.EmailAddress)] public string EmailAddress2 { get; set; } [Phone] // should be equivalent to [DataType(DataType.PhoneNumber)] public string PhoneNumber2 { get; set; } [Url] // should be equivalent to [DataType(DataType.Url)] public string Url2 { get; set; } } [Theory] [InlineData(nameof(DataTypeAttributeClass.EmailAddress), "email")] [InlineData(nameof(DataTypeAttributeClass.PhoneNumber), "phone")] [InlineData(nameof(DataTypeAttributeClass.DateTime), "date-time")] [InlineData(nameof(DataTypeAttributeClass.Time), "time")] [InlineData(nameof(DataTypeAttributeClass.Url), "uri")] [InlineData(nameof(DataTypeAttributeClass.EmailAddress2), "email")] [InlineData(nameof(DataTypeAttributeClass.PhoneNumber2), "phone")] [InlineData(nameof(DataTypeAttributeClass.Url2), "uri")] public async Task When_DataTypeAttribute_is_set_then_the_format_property_should_come_from_the_attribute(string propertyName, string expectedFormat) { var schema = JsonSchema.FromType<DataTypeAttributeClass>(); var property = schema.Properties[propertyName]; Assert.Equal(expectedFormat, property.Format); } [JsonSchemaIgnore] public class BaseObject { public string Foo { get; set; } } public class Person : BaseObject { public string Bar { get; set; } } public class Student : Person { public string Baz { get; set; } } [Fact] public async Task When_class_is_ignored_then_it_is_not_in_definitions() { /// Act var schema = JsonSchema.FromType<Student>(); var json = schema.ToJson(); /// Assert Assert.False(schema.Definitions.ContainsKey("BaseObject")); } } }
// 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; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: used when implementing a custom TraceLoggingTypeInfo. /// An instance of this type is provided to the TypeInfo.WriteMetadata method. /// </summary> internal class TraceLoggingMetadataCollector { private readonly Impl impl; private readonly FieldMetadata currentGroup; private int bufferedArrayFieldCount = int.MinValue; /// <summary> /// Creates a root-level collector. /// </summary> internal TraceLoggingMetadataCollector() { this.impl = new Impl(); } /// <summary> /// Creates a collector for a group. /// </summary> /// <param name="other">Parent collector</param> /// <param name="group">The field that starts the group</param> private TraceLoggingMetadataCollector( TraceLoggingMetadataCollector other, FieldMetadata group) { this.impl = other.impl; this.currentGroup = group; } /// <summary> /// The field tags to be used for the next field. /// This will be reset to None each time a field is written. /// </summary> internal EventFieldTags Tags { get; set; } internal int ScratchSize { get { return this.impl.scratchSize; } } internal int DataCount { get { return this.impl.dataCount; } } internal int PinCount { get { return this.impl.pinCount; } } private bool BeginningBufferedArray { get { return this.bufferedArrayFieldCount == 0; } } /// <summary> /// Call this method to add a group to the event and to return /// a new metadata collector that can be used to add fields to the /// group. After all of the fields in the group have been written, /// switch back to the original metadata collector to add fields /// outside of the group. /// Special-case: if name is null, no group is created, and AddGroup /// returns the original metadata collector. This is useful when /// adding the top-level group for an event. /// Note: do not use the original metadata collector while the group's /// metadata collector is in use, and do not use the group's metadata /// collector after switching back to the original. /// </summary> /// <param name="name"> /// The name of the group. If name is null, the call to AddGroup is a /// no-op (collector.AddGroup(null) returns collector). /// </param> /// <returns> /// A new metadata collector that can be used to add fields to the group. /// </returns> public TraceLoggingMetadataCollector AddGroup(string name) { TraceLoggingMetadataCollector result = this; if (name != null || // Normal. this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception. { var newGroup = new FieldMetadata( name, TraceLoggingDataType.Struct, 0, this.BeginningBufferedArray); this.AddField(newGroup); result = new TraceLoggingMetadataCollector(this, newGroup); } return result; } /// <summary> /// Adds a scalar field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a fixed-size type /// (e.g. string types are not supported). /// </param> public void AddScalar(string name, TraceLoggingDataType type) { int size; switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Int8: case TraceLoggingDataType.UInt8: case TraceLoggingDataType.Char8: size = 1; break; case TraceLoggingDataType.Int16: case TraceLoggingDataType.UInt16: case TraceLoggingDataType.Char16: size = 2; break; case TraceLoggingDataType.Int32: case TraceLoggingDataType.UInt32: case TraceLoggingDataType.HexInt32: case TraceLoggingDataType.Float: case TraceLoggingDataType.Boolean32: size = 4; break; case TraceLoggingDataType.Int64: case TraceLoggingDataType.UInt64: case TraceLoggingDataType.HexInt64: case TraceLoggingDataType.Double: case TraceLoggingDataType.FileTime: size = 8; break; case TraceLoggingDataType.Guid: case TraceLoggingDataType.SystemTime: size = 16; break; default: throw new ArgumentOutOfRangeException("type"); } this.impl.AddScalar(size); this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray)); } /// <summary> /// Adds a binary-format field to an event. /// Compatible with core types: Binary, CountedUtf16String, CountedMbcsString. /// Compatible with dataCollector methods: AddBinary(string), AddArray(Any8bitType[]). /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a Binary or CountedString type. /// </param> public void AddBinary(string name, TraceLoggingDataType type) { switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Binary: case TraceLoggingDataType.CountedMbcsString: case TraceLoggingDataType.CountedUtf16String: break; default: throw new ArgumentOutOfRangeException("type"); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray)); } /// <summary> /// Adds an array field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a fixed-size type /// or a string type. In the case of a string type, this adds an array /// of characters, not an array of strings. /// </param> public void AddArray(string name, TraceLoggingDataType type) { switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Utf16String: case TraceLoggingDataType.MbcsString: case TraceLoggingDataType.Int8: case TraceLoggingDataType.UInt8: case TraceLoggingDataType.Int16: case TraceLoggingDataType.UInt16: case TraceLoggingDataType.Int32: case TraceLoggingDataType.UInt32: case TraceLoggingDataType.Int64: case TraceLoggingDataType.UInt64: case TraceLoggingDataType.Float: case TraceLoggingDataType.Double: case TraceLoggingDataType.Boolean32: case TraceLoggingDataType.Guid: case TraceLoggingDataType.FileTime: case TraceLoggingDataType.HexInt32: case TraceLoggingDataType.HexInt64: case TraceLoggingDataType.Char16: case TraceLoggingDataType.Char8: break; default: throw new ArgumentOutOfRangeException("type"); } if (this.BeginningBufferedArray) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums")); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata(name, type, this.Tags, true)); } public void BeginBufferedArray() { if (this.bufferedArrayFieldCount >= 0) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums")); } this.bufferedArrayFieldCount = 0; this.impl.BeginBuffered(); } public void EndBufferedArray() { if (this.bufferedArrayFieldCount != 1) { throw new InvalidOperationException(Resources.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo")); } this.bufferedArrayFieldCount = int.MinValue; this.impl.EndBuffered(); } /// <summary> /// Adds a custom-serialized field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type">The encoding type for the field.</param> /// <param name="metadata">Additional information needed to decode the field, if any.</param> public void AddCustom(string name, TraceLoggingDataType type, byte[] metadata) { if (this.BeginningBufferedArray) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedCustomSerializedData")); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata( name, type, this.Tags, metadata)); } internal byte[] GetMetadata() { var size = this.impl.Encode(null); var metadata = new byte[size]; this.impl.Encode(metadata); return metadata; } private void AddField(FieldMetadata fieldMetadata) { this.Tags = EventFieldTags.None; this.bufferedArrayFieldCount++; this.impl.fields.Add(fieldMetadata); if (this.currentGroup != null) { this.currentGroup.IncrementStructFieldCount(); } } private class Impl { internal readonly List<FieldMetadata> fields = new List<FieldMetadata>(); internal short scratchSize; internal sbyte dataCount; internal sbyte pinCount; private int bufferNesting; private bool scalar; public void AddScalar(int size) { if (this.bufferNesting == 0) { if (!this.scalar) { this.dataCount = checked((sbyte)(this.dataCount + 1)); } this.scalar = true; this.scratchSize = checked((short)(this.scratchSize + size)); } } public void AddNonscalar() { if (this.bufferNesting == 0) { this.scalar = false; this.pinCount = checked((sbyte)(this.pinCount + 1)); this.dataCount = checked((sbyte)(this.dataCount + 1)); } } public void BeginBuffered() { if (this.bufferNesting == 0) { this.AddNonscalar(); } this.bufferNesting++; } public void EndBuffered() { this.bufferNesting--; } public int Encode(byte[] metadata) { int size = 0; foreach (var field in this.fields) { field.Encode(ref size, metadata); } return size; } } } }
/* **************************************************************************** * * 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. * * * ***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; [assembly: PythonModule("re", typeof(IronPython.Modules.PythonRegex))] namespace IronPython.Modules { /// <summary> /// Python regular expression module. /// </summary> public static class PythonRegex { private static CacheDict<PatternKey, RE_Pattern> _cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100); [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("reerror", dict, "error", "re"); PythonCopyReg.GetDispatchTable(context.SharedContext)[DynamicHelpers.GetPythonTypeFromType(typeof(RE_Pattern))] = dict["_pickle"]; } private static readonly Random r = new Random(DateTime.Now.Millisecond); #region CONSTANTS // short forms public const int I = 0x02; public const int L = 0x04; public const int M = 0x08; public const int S = 0x10; public const int U = 0x20; public const int X = 0x40; // long forms public const int IGNORECASE = 0x02; public const int LOCALE = 0x04; public const int MULTILINE = 0x08; public const int DOTALL = 0x10; public const int UNICODE = 0x20; public const int VERBOSE = 0x40; #endregion #region Public API Surface public static RE_Pattern compile(CodeContext/*!*/ context, object pattern) { try { return GetPattern(context, pattern, 0, true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } } public static RE_Pattern compile(CodeContext/*!*/ context, object pattern, object flags) { try { return GetPattern(context, pattern, PythonContext.GetContext(context).ConvertToInt32(flags), true); } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } } public const string engine = "cli reg ex"; public static string escape(string text) { if (text == null) throw PythonOps.TypeError("text must not be None"); for (int i = 0; i < text.Length; i++) { if (!Char.IsLetterOrDigit(text[i])) { StringBuilder sb = new StringBuilder(text, 0, i, text.Length); char ch = text[i]; do { sb.Append('\\'); sb.Append(ch); i++; int last = i; while (i < text.Length) { ch = text[i]; if (!Char.IsLetterOrDigit(ch)) { break; } i++; } sb.Append(text, last, i - last); } while (i < text.Length); return sb.ToString(); } } return text; } public static List findall(CodeContext/*!*/ context, object pattern, string @string) { return findall(context, pattern, @string, 0); } public static List findall(CodeContext/*!*/ context, object pattern, string @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags); ValidateString(@string, "string"); MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Length); return FixFindAllMatch(pat, mc, null); } public static List findall(CodeContext/*!*/ context, object pattern, IList<byte> @string) { return findall(context, pattern, @string, 0); } public static List findall(CodeContext/*!*/ context, object pattern, IList<byte> @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern (pattern), flags); ValidateString (@string, "string"); MatchCollection mc = pat.FindAllWorker(context, @string, 0, @string.Count); return FixFindAllMatch (pat, mc, FindMaker(@string)); } private static Func<string, object> FindMaker (object input) { Func<string, object> maker = null; if (input is ByteArray) { maker = delegate (string x) { return new ByteArray (x.MakeByteArray ()); }; } return maker; } private static List FixFindAllMatch(RE_Pattern pat, MatchCollection mc, Func<string, object> maker) { object[] matches = new object[mc.Count]; int numgrps = pat._re.GetGroupNumbers().Length; for (int i = 0; i < mc.Count; i++) { if (numgrps > 2) { // CLR gives us a "bonus" group of 0 - the entire expression // at this point we have more than one group in the pattern; // need to return a list of tuples in this case // for each match item in the matchcollection, create a tuple representing what was matched // e.g. findall("(\d+)|(\w+)", "x = 99y") == [('', 'x'), ('99', ''), ('', 'y')] // in the example above, ('', 'x') did not match (\d+) as indicated by '' but did // match (\w+) as indicated by 'x' and so on... int k = 0; List<object> tpl = new List<object>(); foreach (Group g in mc[i].Groups) { // here also the CLR gives us a "bonus" match as the first item which is the // group that was actually matched in the tuple e.g. we get 'x', '', 'x' for // the first match object...so we'll skip the first item when creating the // tuple if (k++ != 0) { tpl.Add(maker != null ? maker(g.Value) : g.Value); } } matches[i] = PythonTuple.Make(tpl); } else if (numgrps == 2) { // at this point we have exactly one group in the pattern (including the "bonus" one given // by the CLR // skip the first match since that contains the entire match and not the group match // e.g. re.findall(r"(\w+)\s+fish\b", "green fish") will have "green fish" in the 0 // index and "green" as the (\w+) group match matches[i] = maker != null ? maker(mc[i].Groups[1].Value) : mc[i].Groups[1].Value; } else { matches[i] = maker != null ? maker (mc[i].Value) : mc[i].Value; } } return List.FromArrayNoCopy(matches); } public static object finditer(CodeContext/*!*/ context, object pattern, object @string) { return finditer(context, pattern, @string, 0); } public static object finditer(CodeContext/*!*/ context, object pattern, object @string, int flags) { RE_Pattern pat = GetPattern(context, ValidatePattern(pattern), flags); string str = ValidateString(@string, "string"); return MatchIterator(pat.FindAllWorker(context, str, 0, str.Length), pat, str); } public static RE_Match match(CodeContext/*!*/ context, object pattern, object @string) { return match(context, pattern, @string, 0); } public static RE_Match match(CodeContext/*!*/ context, object pattern, object @string, int flags) { return GetPattern(context, ValidatePattern(pattern), flags).match(ValidateString(@string, "string")); } public static RE_Match search(CodeContext/*!*/ context, object pattern, object @string) { return search(context, pattern, @string, 0); } public static RE_Match search(CodeContext/*!*/ context, object pattern, object @string, int flags) { return GetPattern(context, ValidatePattern(pattern), flags).search(ValidateString(@string, "string")); } [return: SequenceTypeInfo(typeof(string))] public static List split(CodeContext/*!*/ context, object pattern, object @string) { return split(context, ValidatePattern(pattern), ValidateString(@string, "string"), 0); } [return: SequenceTypeInfo(typeof(string))] public static List split(CodeContext/*!*/ context, object pattern, object @string, int maxsplit) { return GetPattern(context, ValidatePattern(pattern), 0).split(ValidateString(@string, "string"), maxsplit); } public static string sub(CodeContext/*!*/ context, object pattern, object repl, object @string) { return sub(context, pattern, repl, @string, Int32.MaxValue); } public static string sub(CodeContext/*!*/ context, object pattern, object repl, object @string, int count) { return GetPattern(context, ValidatePattern(pattern), 0).sub(context, repl, ValidateString(@string, "string"), count); } public static object subn(CodeContext/*!*/ context, object pattern, object repl, object @string) { return subn(context, pattern, repl, @string, Int32.MaxValue); } public static object subn(CodeContext/*!*/ context, object pattern, object repl, object @string, int count) { return GetPattern(context, ValidatePattern(pattern), 0).subn(context, repl, ValidateString(@string, "string"), count); } public static void purge() { _cachedPatterns = new CacheDict<PatternKey, RE_Pattern>(100); } #endregion #region Public classes /// <summary> /// Compiled reg-ex pattern /// </summary> [PythonType] public class RE_Pattern : IWeakReferenceable { internal Regex _re; private PythonDictionary _groups; private int _compileFlags; private WeakRefTracker _weakRefTracker; internal ParsedRegex _pre; internal RE_Pattern(CodeContext/*!*/ context, object pattern) : this(context, pattern, 0) { } internal RE_Pattern(CodeContext/*!*/ context, object pattern, int flags) : this(context, pattern, flags, false) { } internal RE_Pattern(CodeContext/*!*/ context, object pattern, int flags, bool compiled) { _pre = PreParseRegex(context, ValidatePatternAsString(pattern)); try { flags |= OptionToFlags(_pre.Options); RegexOptions opts = FlagsToOption(flags); #if SILVERLIGHT this._re = new Regex(_pre.Pattern, opts); #else this._re = new Regex(_pre.Pattern, opts | (compiled ? RegexOptions.Compiled : RegexOptions.None)); #endif } catch (ArgumentException e) { throw PythonExceptions.CreateThrowable(error(context), e.Message); } this._compileFlags = flags; } public RE_Match match(object text) { string input = ValidateString(text, "text"); return RE_Match.makeMatch(_re.Match(input), this, input, 0, input.Length); } private static int FixPosition(string text, int position) { if (position < 0) return 0; if (position > text.Length) return text.Length; return position; } public RE_Match match(object text, int pos) { string input = ValidateString(text, "text"); pos = FixPosition(input, pos); return RE_Match.makeMatch(_re.Match(input, pos), this, input, pos, input.Length); } public RE_Match match(object text, [DefaultParameterValue(0)]int pos, int endpos) { string input = ValidateString(text, "text"); pos = FixPosition(input, pos); endpos = FixPosition(input, endpos); return RE_Match.makeMatch( _re.Match(input.Substring(0, endpos), pos), this, input, pos, endpos); } public RE_Match search(object text) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input), this, input); } public RE_Match search(object text, int pos) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input, pos, input.Length - pos), this, input); } public RE_Match search(object text, int pos, int endpos) { string input = ValidateString(text, "text"); return RE_Match.make(_re.Match(input, pos, Math.Min(Math.Max(endpos - pos, 0), input.Length - pos)), this, input); } public object findall(CodeContext/*!*/ context, string @string) { return findall(context, @string, 0, null); } public object findall(CodeContext/*!*/ context, string @string, int pos) { return findall(context, @string, pos, null); } public object findall(CodeContext/*!*/ context, object @string, int pos, object endpos) { MatchCollection mc = FindAllWorker(context, ValidateString(@string, "text"), pos, endpos); return FixFindAllMatch(this, mc, FindMaker(@string)); } internal MatchCollection FindAllWorker(CodeContext/*!*/ context, string str, int pos, object endpos) { string against = str; if (endpos != null) { int end = PythonContext.GetContext(context).ConvertToInt32(endpos); against = against.Substring(0, Math.Max(end, 0)); } return _re.Matches(against, pos); } internal MatchCollection FindAllWorker(CodeContext/*!*/ context, IList<byte> str, int pos, object endpos) { string against = str.MakeString(); if (endpos != null) { int end = PythonContext.GetContext(context).ConvertToInt32(endpos); against = against.Substring(0, Math.Max(end, 0)); } return _re.Matches(against, pos); } public object finditer(CodeContext/*!*/ context, object @string) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, 0, input.Length), this, input); } public object finditer(CodeContext/*!*/ context, object @string, int pos) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, pos, input.Length), this, input); } public object finditer(CodeContext/*!*/ context, object @string, int pos, int endpos) { string input = ValidateString(@string, "string"); return MatchIterator(FindAllWorker(context, input, pos, endpos), this, input); } [return: SequenceTypeInfo(typeof(string))] public List split(string @string) { return split(@string, 0); } [return: SequenceTypeInfo(typeof(string))] public List split(object @string, int maxsplit) { List result = new List(); // fast path for negative maxSplit ( == "make no splits") if (maxsplit < 0) { result.AddNoLock(ValidateString(@string, "string")); } else { // iterate over all matches string theStr = ValidateString(@string, "string"); MatchCollection matches = _re.Matches(theStr); int lastPos = 0; // is either start of the string, or first position *after* the last match int nSplits = 0; // how many splits have occurred? foreach (Match m in matches) { if (m.Length > 0) { // add substring from lastPos to beginning of current match result.AddNoLock(theStr.Substring(lastPos, m.Index - lastPos)); // if there are subgroups of the match, add their match or None if (m.Groups.Count > 1) for (int i = 1; i < m.Groups.Count; i++) if (m.Groups[i].Success) result.AddNoLock(m.Groups[i].Value); else result.AddNoLock(null); // update lastPos, nSplits lastPos = m.Index + m.Length; nSplits++; if (nSplits == maxsplit) break; } } // add tail following last match result.AddNoLock(theStr.Substring(lastPos)); } return result; } public string sub(CodeContext/*!*/ context, object repl, object @string) { return sub(context, repl, ValidateString(@string, "string"), Int32.MaxValue); } public string sub(CodeContext/*!*/ context, object repl, object @string, int count) { if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl"); // if 'count' is omitted or 0, all occurrences are replaced if (count == 0) count = Int32.MaxValue; string replacement = repl as string; if (replacement == null) { if (repl is ExtensibleString) { replacement = ((ExtensibleString)repl).Value; } else if (repl is Bytes) { replacement = ((Bytes)repl).ToString(); } } Match prev = null; string input = ValidateString(@string, "string"); return _re.Replace( input, delegate(Match match) { // from the docs: Empty matches for the pattern are replaced // only when not adjacent to a previous match if (String.IsNullOrEmpty(match.Value) && prev != null && (prev.Index + prev.Length) == match.Index) { return ""; }; prev = match; if (replacement != null) return UnescapeGroups(match, replacement); return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string; }, count); } public object subn(CodeContext/*!*/ context, object repl, string @string) { return subn(context, repl, @string, Int32.MaxValue); } public object subn(CodeContext/*!*/ context, object repl, object @string, int count) { if (repl == null) throw PythonOps.TypeError("NoneType is not valid repl"); // if 'count' is omitted or 0, all occurrences are replaced if (count == 0) count = Int32.MaxValue; int totalCount = 0; string res; string replacement = repl as string; if (replacement == null) { if (repl is ExtensibleString) { replacement = ((ExtensibleString)repl).Value; } else if (repl is Bytes) { replacement = ((Bytes)repl).ToString(); } } Match prev = null; string input = ValidateString(@string, "string"); res = _re.Replace( input, delegate(Match match) { // from the docs: Empty matches for the pattern are replaced // only when not adjacent to a previous match if (String.IsNullOrEmpty(match.Value) && prev != null && (prev.Index + prev.Length) == match.Index) { return ""; }; prev = match; totalCount++; if (replacement != null) return UnescapeGroups(match, replacement); return PythonCalls.Call(context, repl, RE_Match.make(match, this, input)) as string; }, count); return PythonTuple.MakeTuple(res, totalCount); } public int flags { get { return _compileFlags; } } public PythonDictionary groupindex { get { if (_groups == null) { PythonDictionary d = new PythonDictionary(); string[] names = _re.GetGroupNames(); int[] nums = _re.GetGroupNumbers(); for (int i = 1; i < names.Length; i++) { if (Char.IsDigit(names[i][0]) || names[i].StartsWith(_mangledNamedGroup)) { // skip numeric names and our mangling for unnamed groups mixed w/ named groups. continue; } d[names[i]] = nums[i]; } _groups = d; } return _groups; } } public int groups { get { return _re.GetGroupNumbers().Length - 1; } } public string pattern { get { return _pre.UserPattern; } } public override bool Equals(object obj) { RE_Pattern other = obj as RE_Pattern; if (other == null) { return false; } return other.pattern == pattern && other.flags == flags; } public override int GetHashCode() { return pattern.GetHashCode() ^ flags; } #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakRefTracker; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakRefTracker = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion } public static PythonTuple _pickle(CodeContext/*!*/ context, RE_Pattern pattern) { object scope = Importer.ImportModule(context, new PythonDictionary(), "re", false, 0); object compile; if (scope is PythonModule && ((PythonModule)scope).__dict__.TryGetValue("compile", out compile)) { return PythonTuple.MakeTuple(compile, PythonTuple.MakeTuple(pattern.pattern, pattern.flags)); } throw new InvalidOperationException("couldn't find compile method"); } [PythonType] public class RE_Match { RE_Pattern _pattern; private Match _m; private string _text; private int _lastindex = -1; private int _pos, _endPos; #region Internal makers internal static RE_Match make(Match m, RE_Pattern pattern, string input) { if (m.Success) return new RE_Match(m, pattern, input, 0, input.Length); return null; } internal static RE_Match make(Match m, RE_Pattern pattern, string input, int offset, int endpos) { if (m.Success) return new RE_Match(m, pattern, input, offset, endpos); return null; } internal static RE_Match makeMatch(Match m, RE_Pattern pattern, string input, int offset, int endpos) { if (m.Success && m.Index == offset) return new RE_Match(m, pattern, input, offset, endpos); return null; } #endregion #region Public ctors public RE_Match(Match m, RE_Pattern pattern, string text) { _m = m; _pattern = pattern; _text = text; } public RE_Match(Match m, RE_Pattern pattern, string text, int pos, int endpos) { _m = m; _pattern = pattern; _text = text; _pos = pos; _endPos = endpos; } #endregion // public override bool __nonzero__() { // return m.Success; // } #region Public API Surface public int end() { return _m.Index + _m.Length; } public int start() { return _m.Index; } public int start(object group) { int grpIndex = GetGroupIndex(group); if (!_m.Groups[grpIndex].Success) { return -1; } return _m.Groups[grpIndex].Index; } public int end(object group) { int grpIndex = GetGroupIndex(group); if (!_m.Groups[grpIndex].Success) { return -1; } return _m.Groups[grpIndex].Index + _m.Groups[grpIndex].Length; } public object group(object index, params object[] additional) { if (additional.Length == 0) { return group(index); } object[] res = new object[additional.Length + 1]; res[0] = _m.Groups[GetGroupIndex(index)].Success ? _m.Groups[GetGroupIndex(index)].Value : null; for (int i = 1; i < res.Length; i++) { int grpIndex = GetGroupIndex(additional[i - 1]); res[i] = _m.Groups[grpIndex].Success ? _m.Groups[grpIndex].Value : null; } return PythonTuple.MakeTuple(res); } public string group(object index) { int pos = GetGroupIndex(index); Group g = _m.Groups[pos]; return g.Success ? g.Value : null; } public string group() { return group(0); } [return: SequenceTypeInfo(typeof(string))] public PythonTuple groups() { return groups(null); } public PythonTuple groups(object @default) { object[] ret = new object[_m.Groups.Count - 1]; for (int i = 1; i < _m.Groups.Count; i++) { if (!_m.Groups[i].Success) { ret[i - 1] = @default; } else { ret[i - 1] = _m.Groups[i].Value; } } return PythonTuple.MakeTuple(ret); } public string expand(object template) { string strTmp = ValidateString(template, "template"); StringBuilder res = new StringBuilder(); for (int i = 0; i < strTmp.Length; i++) { if (strTmp[i] != '\\') { res.Append(strTmp[i]); continue; } if (++i == strTmp.Length) { res.Append(strTmp[i - 1]); continue; } if (Char.IsDigit(strTmp[i])) { AppendGroup(res, (int)(strTmp[i] - '0')); } else if (strTmp[i] == 'g') { if (++i == strTmp.Length) { res.Append("\\g"); return res.ToString(); } if (strTmp[i] != '<') { res.Append("\\g<"); continue; } else { // '<' StringBuilder name = new StringBuilder(); i++; while (strTmp[i] != '>' && i < strTmp.Length) { name.Append(strTmp[i++]); } AppendGroup(res, _pattern._re.GroupNumberFromName(name.ToString())); } } else { switch (strTmp[i]) { case 'n': res.Append('\n'); break; case 'r': res.Append('\r'); break; case 't': res.Append('\t'); break; case '\\': res.Append('\\'); break; } } } return res.ToString(); } [return: DictionaryTypeInfo(typeof(string), typeof(string))] public PythonDictionary groupdict() { return groupdict(null); } private static bool IsGroupNumber(string name) { foreach (char c in name) { if (!Char.IsNumber(c)) return false; } return true; } [return: DictionaryTypeInfo(typeof(string), typeof(string))] public PythonDictionary groupdict([NotNull]string value) { return groupdict((object)value); } [return: DictionaryTypeInfo(typeof(string), typeof(object))] public PythonDictionary groupdict(object value) { string[] groupNames = this._pattern._re.GetGroupNames(); Debug.Assert(groupNames.Length == this._m.Groups.Count); PythonDictionary d = new PythonDictionary(); for (int i = 0; i < groupNames.Length; i++) { if (IsGroupNumber(groupNames[i])) continue; // python doesn't report group numbers if (_m.Groups[i].Captures.Count != 0) { d[groupNames[i]] = _m.Groups[i].Value; } else { d[groupNames[i]] = value; } } return d; } [return: SequenceTypeInfo(typeof(int))] public PythonTuple span() { return PythonTuple.MakeTuple(this.start(), this.end()); } [return: SequenceTypeInfo(typeof(int))] public PythonTuple span(object group) { return PythonTuple.MakeTuple(this.start(group), this.end(group)); } public int pos { get { return _pos; } } public int endpos { get { return _endPos; } } public string @string { get { return _text; } } public PythonTuple regs { get { object[] res = new object[_m.Groups.Count]; for (int i = 0; i < res.Length; i++) { res[i] = PythonTuple.MakeTuple(start(i), end(i)); } return PythonTuple.MakeTuple(res); } } public RE_Pattern re { get { return _pattern; } } public object lastindex { get { // -1 : initial value of lastindex // 0 : no match found //other : the true lastindex // Match.Groups contains "lower" level matched groups, which has to be removed if (_lastindex == -1) { int i = 1; while (i < _m.Groups.Count) { if (_m.Groups[i].Success) { _lastindex = i; int start = _m.Groups[i].Index; int end = start + _m.Groups[i].Length; i++; // skip any group which fall into the range [start, end], // no matter match succeed or fail while (i < _m.Groups.Count && (_m.Groups[i].Index < end)) { i++; } } else { i++; } } if (_lastindex == -1) { _lastindex = 0; } } if (_lastindex == 0) { return null; } else { return _lastindex; } } } public string lastgroup { get { if (lastindex == null) return null; // when group was not explicitly named, RegEx assigns the number as name // This is different from C-Python, which returns None in such cases return this._pattern._re.GroupNameFromNumber((int)lastindex); } } #endregion #region Private helper functions private void AppendGroup(StringBuilder sb, int index) { sb.Append(_m.Groups[index].Value); } private int GetGroupIndex(object group) { int grpIndex; if (!Converter.TryConvertToInt32(group, out grpIndex)) { grpIndex = _pattern._re.GroupNumberFromName(ValidateString(group, "group")); } if (grpIndex < 0 || grpIndex >= _m.Groups.Count) { throw PythonOps.IndexError("no such group"); } return grpIndex; } #endregion } #endregion #region Private helper functions private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags) { return GetPattern(context, pattern, flags, false); } private static RE_Pattern GetPattern(CodeContext/*!*/ context, object pattern, int flags, bool compiled) { RE_Pattern res = pattern as RE_Pattern; if (res != null) { return res; } string strPattern = ValidatePatternAsString(pattern); PatternKey key = new PatternKey(strPattern, flags); lock (_cachedPatterns) { if (_cachedPatterns.TryGetValue(new PatternKey(strPattern, flags), out res)) { #if SILVERLIGHT return res; #else if ( ! compiled || (res._re.Options & RegexOptions.Compiled) == RegexOptions.Compiled) { return res; } #endif } res = new RE_Pattern(context, strPattern, flags, compiled); _cachedPatterns[key] = res; return res; } } private static IEnumerator MatchIterator(MatchCollection matches, RE_Pattern pattern, string input) { for (int i = 0; i < matches.Count; i++) { yield return RE_Match.make(matches[i], pattern, input, 0, input.Length); } } private static RegexOptions FlagsToOption(int flags) { RegexOptions opts = RegexOptions.None; if ((flags & (int)IGNORECASE) != 0) opts |= RegexOptions.IgnoreCase; if ((flags & (int)MULTILINE) != 0) opts |= RegexOptions.Multiline; if (((flags & (int)LOCALE)) == 0) opts &= (~RegexOptions.CultureInvariant); if ((flags & (int)DOTALL) != 0) opts |= RegexOptions.Singleline; if ((flags & (int)VERBOSE) != 0) opts |= RegexOptions.IgnorePatternWhitespace; return opts; } private static int OptionToFlags(RegexOptions options) { int flags = 0; if ((options & RegexOptions.IgnoreCase) != 0) { flags |= IGNORECASE; } if ((options & RegexOptions.Multiline) != 0) { flags |= MULTILINE; } if ((options & RegexOptions.CultureInvariant) == 0) { flags |= LOCALE; } if ((options & RegexOptions.Singleline) != 0) { flags |= DOTALL; } if ((options & RegexOptions.IgnorePatternWhitespace) != 0) { flags |= VERBOSE; } return flags; } internal class ParsedRegex { public ParsedRegex(string pattern) { this.UserPattern = pattern; } public string UserPattern; public string Pattern; public RegexOptions Options = RegexOptions.CultureInvariant; } private static char[] _preParsedChars = new[] { '(', '{', '[', ']' }; private const string _mangledNamedGroup = "___PyRegexNameMangled"; /// <summary> /// Preparses a regular expression text returning a ParsedRegex class /// that can be used for further regular expressions. /// </summary> private static ParsedRegex PreParseRegex(CodeContext/*!*/ context, string pattern) { ParsedRegex res = new ParsedRegex(pattern); //string newPattern; int cur = 0, nameIndex; int curGroup = 0; bool isCharList = false; bool containsNamedGroup = false; for (; ; ) { nameIndex = pattern.IndexOfAny(_preParsedChars, cur); if (nameIndex > 0 && pattern[nameIndex - 1] == '\\') { int curIndex = nameIndex - 2; int backslashCount = 1; while (curIndex >= 0 && pattern[curIndex] == '\\') { backslashCount++; curIndex--; } // odd number of back slashes, this is an optional // paren that we should ignore. if ((backslashCount & 0x01) != 0) { cur++; continue; } } if (nameIndex == -1) break; if (nameIndex == pattern.Length - 1) break; switch (pattern[nameIndex]) { case '{': if (pattern[++nameIndex] == ',') { // no beginning specified for the n-m quntifier, add the // default 0 value. pattern = pattern.Insert(nameIndex, "0"); } break; case '[': nameIndex++; isCharList = true; break; case ']': nameIndex++; isCharList = false; break; case '(': // make sure we're not dealing with [(] if (!isCharList) { switch (pattern[++nameIndex]) { case '?': // extension syntax if (nameIndex == pattern.Length - 1) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex"); switch (pattern[++nameIndex]) { case 'P': // named regex, .NET doesn't expect the P so we'll remove it; // also, once we see a named group i.e. ?P then we need to start artificially // naming all unnamed groups from then on---this is to get around the fact that // the CLR RegEx support orders all the unnamed groups before all the named // groups, even if the named groups are before the unnamed ones in the pattern; // the artificial naming preserves the order of the groups and thus the order of // the matches if (nameIndex + 1 < pattern.Length && pattern[nameIndex + 1] == '=') { // match whatever was previously matched by the named group // remove the (?P= pattern = pattern.Remove(nameIndex - 2, 4); pattern = pattern.Insert(nameIndex - 2, "\\k<"); int tmpIndex = nameIndex; while (tmpIndex < pattern.Length && pattern[tmpIndex] != ')') tmpIndex++; if (tmpIndex == pattern.Length) throw PythonExceptions.CreateThrowable(error(context), "unexpected end of regex"); pattern = pattern.Substring(0, tmpIndex) + ">" + pattern.Substring(tmpIndex + 1); } else { containsNamedGroup = true; pattern = pattern.Remove(nameIndex, 1); } break; case 'i': res.Options |= RegexOptions.IgnoreCase; RemoveOption(ref pattern, ref nameIndex); break; case 'L': res.Options &= ~(RegexOptions.CultureInvariant); RemoveOption(ref pattern, ref nameIndex); break; case 'm': res.Options |= RegexOptions.Multiline; RemoveOption(ref pattern, ref nameIndex); break; case 's': res.Options |= RegexOptions.Singleline; RemoveOption(ref pattern, ref nameIndex); break; case 'u': // specify unicode; not relevant and not valid under .NET as we're always unicode // -- so the option needs to be removed RemoveOption(ref pattern, ref nameIndex); break; case 'x': res.Options |= RegexOptions.IgnorePatternWhitespace; RemoveOption(ref pattern, ref nameIndex); break; case ':': break; // non-capturing case '=': break; // look ahead assertion case '<': break; // positive look behind assertion case '!': break; // negative look ahead assertion case '#': break; // inline comment case '(': // conditional match alternation (?(id/name)yes-pattern|no-pattern) // move past ?( so we don't preparse the name. nameIndex++; break; default: throw PythonExceptions.CreateThrowable(error(context), "Unrecognized extension " + pattern[nameIndex]); } break; default: // just another group curGroup++; if (containsNamedGroup) { // need to name this unnamed group pattern = pattern.Insert(nameIndex, "?<" + _mangledNamedGroup + GetRandomString() + ">"); } break; } } else { nameIndex++; } break; } cur = nameIndex; } cur = 0; for (; ; ) { nameIndex = pattern.IndexOf('\\', cur); if (nameIndex == -1 || nameIndex == pattern.Length - 1) break; cur = ++nameIndex; char curChar = pattern[cur]; switch (curChar) { case 'x': case 'u': case 'a': case 'b': case 'e': case 'f': case 'k': case 'n': case 'r': case 't': case 'v': case 'c': case 's': case 'W': case 'w': case 'p': case 'P': case 'S': case 'd': case 'D': case 'A': case 'Z': case '\\': // known escape sequences, leave escaped. break; default: System.Globalization.UnicodeCategory charClass = Char.GetUnicodeCategory(curChar); switch (charClass) { // recognized word characters, always unescape. case System.Globalization.UnicodeCategory.ModifierLetter: case System.Globalization.UnicodeCategory.LowercaseLetter: case System.Globalization.UnicodeCategory.UppercaseLetter: case System.Globalization.UnicodeCategory.TitlecaseLetter: case System.Globalization.UnicodeCategory.OtherLetter: case System.Globalization.UnicodeCategory.LetterNumber: case System.Globalization.UnicodeCategory.OtherNumber: case System.Globalization.UnicodeCategory.ConnectorPunctuation: pattern = pattern.Remove(nameIndex - 1, 1); cur--; break; case System.Globalization.UnicodeCategory.DecimalDigitNumber: // actually don't want to unescape '\1', '\2' etc. which are references to groups break; } break; } if (++cur >= pattern.Length) { break; } } res.Pattern = pattern; return res; } private static void RemoveOption(ref string pattern, ref int nameIndex) { if (pattern[nameIndex - 1] == '?' && nameIndex < (pattern.Length - 1) && pattern[nameIndex + 1] == ')') { pattern = pattern.Remove(nameIndex - 2, 4); nameIndex -= 2; } else { pattern = pattern.Remove(nameIndex, 1); nameIndex -= 2; } } private static string GetRandomString() { return r.Next(Int32.MaxValue / 2, Int32.MaxValue).ToString(); } private static string UnescapeGroups(Match m, string text) { for (int i = 0; i < text.Length; i++) { if (text[i] == '\\') { StringBuilder sb = new StringBuilder(text, 0, i, text.Length); do { if (text[i] == '\\') { i++; if (i == text.Length) { sb.Append('\\'); break; } switch (text[i]) { case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case '\\': sb.Append('\\'); break; case '\'': sb.Append('\''); break; case 'b': sb.Append('\b'); break; case 'g': // \g<#>, \g<name> need to be substituted by the groups they // matched if (text[i + 1] == '<') { int anglebrkStart = i + 1; int anglebrkEnd = text.IndexOf('>', i + 2); if (anglebrkEnd != -1) { // grab the # or 'name' of the group between '< >' int lengrp = anglebrkEnd - (anglebrkStart + 1); string grp = text.Substring(anglebrkStart + 1, lengrp); int num; Group g; if (StringUtils.TryParseInt32(grp, out num)) { g = m.Groups[num]; if (String.IsNullOrEmpty(g.Value)) { throw PythonOps.IndexError("unknown group reference"); } sb.Append(g.Value); } else { g = m.Groups[grp]; if (String.IsNullOrEmpty(g.Value)) { throw PythonOps.IndexError("unknown group reference"); } sb.Append(g.Value); } i = anglebrkEnd; } break; } sb.Append('\\'); sb.Append((char)text[i]); break; default: if (Char.IsDigit(text[i]) && text[i] <= '7') { int val = 0; int digitCount = 0; while (i < text.Length && Char.IsDigit(text[i]) && text[i] <= '7') { digitCount++; val += val * 8 + (text[i] - '0'); i++; } i--; if (digitCount == 1 && val > 0 && val < m.Groups.Count) { sb.Append(m.Groups[val].Value); } else { sb.Append((char)val); } } else { sb.Append('\\'); sb.Append((char)text[i]); } break; } } else { sb.Append(text[i]); } } while (++i < text.Length); return sb.ToString(); } } return text; } private static object ValidatePattern(object pattern) { if (pattern is string) return pattern as string; ExtensibleString es = pattern as ExtensibleString; if (es != null) return es.Value; Bytes bytes = pattern as Bytes; if (bytes != null) { return bytes.ToString(); } RE_Pattern rep = pattern as RE_Pattern; if (rep != null) return rep; throw PythonOps.TypeError("pattern must be a string or compiled pattern"); } private static string ValidatePatternAsString(object pattern) { if (pattern is string) return pattern as string; ExtensibleString es = pattern as ExtensibleString; if (es != null) return es.Value; Bytes bytes = pattern as Bytes; if (bytes != null) { return bytes.ToString(); } RE_Pattern rep = pattern as RE_Pattern; if (rep != null) return rep._pre.UserPattern; throw PythonOps.TypeError("pattern must be a string or compiled pattern"); } private static string ValidateString(object str, string param) { if (str is string) return str as string; ExtensibleString es = str as ExtensibleString; if (es != null) return es.Value; PythonBuffer buf = str as PythonBuffer; if (buf != null) { return buf.ToString(); } Bytes bytes = str as Bytes; if (bytes != null) { return bytes.ToString(); } ByteArray byteArray = str as ByteArray; if (byteArray != null) { return byteArray.MakeString(); } #if FEATURE_MMAP MmapModule.mmap mmapFile = str as MmapModule.mmap; if (mmapFile != null) { return mmapFile.GetSearchString(); } #endif throw PythonOps.TypeError("expected string for parameter '{0}' but got '{1}'", param, PythonOps.GetPythonTypeName(str)); } private static PythonType error(CodeContext/*!*/ context) { return (PythonType)PythonContext.GetContext(context).GetModuleState("reerror"); } class PatternKey : IEquatable<PatternKey> { public string Pattern; public int Flags; public PatternKey(string pattern, int flags) { Pattern = pattern; Flags = flags; } public override bool Equals(object obj) { PatternKey key = obj as PatternKey; if (key != null) { return Equals(key); } return false; } public override int GetHashCode() { return Pattern.GetHashCode() ^ Flags; } #region IEquatable<PatternKey> Members public bool Equals(PatternKey other) { return other.Pattern == Pattern && other.Flags == Flags; } #endregion } #endregion } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Xml; using log4net; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.DataSnapshot.Interfaces; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.DataSnapshot { public class DataSnapshotManager : ISharedRegionModule, IDataSnapshot { #region Class members //Information from config private bool m_enabled = false; private bool m_configLoaded = false; private List<string> m_disabledModules = new List<string>(); private Dictionary<string, string> m_gridinfo = new Dictionary<string, string>(); private string m_snapsDir = "DataSnapshot"; private string m_exposure_level = "minimum"; //Lists of stuff we need private List<IScene> m_scenes = new List<IScene>(); private List<IDataSnapshotProvider> m_dataproviders = new List<IDataSnapshotProvider>(); //Various internal objects private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); internal object m_syncInit = new object(); //DataServices and networking private string m_dataServices = "noservices"; public string m_listener_port = ""; public string m_hostname = "127.0.0.1"; //Update timers private int m_period = 20; // in seconds private int m_maxStales = 500; private int m_stales = 0; private int m_lastUpdate = 0; //Program objects private SnapshotStore m_snapStore = null; #endregion #region Properties public string ExposureLevel { get { return m_exposure_level; } } #endregion #region IRegionModule public void Initialise(IConfigSource config) { if (!m_configLoaded) { m_configLoaded = true; //m_log.Debug("[DATASNAPSHOT]: Loading configuration"); //Read from the config for options lock (m_syncInit) { if (config.Configs["DataSnapshot"] == null) return; try { m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled); IConfig conf = config.Configs["GridService"]; if (conf != null) m_gridinfo.Add("gridserverURL", conf.GetString("GridServerURI", "http://127.0.0.1:8003")); m_gridinfo.Add( "Name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo")); m_exposure_level = config.Configs["DataSnapshot"].GetString("data_exposure", m_exposure_level); m_period = config.Configs["DataSnapshot"].GetInt("default_snapshot_period", m_period); m_maxStales = config.Configs["DataSnapshot"].GetInt("max_changes_before_update", m_maxStales); m_snapsDir = config.Configs["DataSnapshot"].GetString("snapshot_cache_directory", m_snapsDir); m_dataServices = config.Configs["DataSnapshot"].GetString("data_services", m_dataServices); m_listener_port = config.Configs["Network"].GetString("http_listener_port", m_listener_port); String[] annoying_string_array = config.Configs["DataSnapshot"].GetString("disable_modules", "").Split(".".ToCharArray()); foreach (String bloody_wanker in annoying_string_array) { m_disabledModules.Add(bloody_wanker); } m_lastUpdate = Environment.TickCount; } catch (Exception) { m_enabled = false; return; } } } } public void AddRegion (IScene scene) { if (m_enabled) { //Hand it the first scene, assuming that all scenes have the same BaseHTTPServer new DataRequestHandler(scene, this); m_hostname = MainServer.Instance.HostName; m_snapStore = new SnapshotStore(m_snapsDir, m_gridinfo, m_listener_port, m_hostname); MakeEverythingStale(); if (m_dataServices != "" && m_dataServices != "noservices") NotifyDataServices(m_dataServices, "online"); } if (m_enabled) { //m_log.Info("[DATASNAPSHOT]: Scene added to module."); m_snapStore.AddScene(scene); m_scenes.Add(scene); Assembly currentasm = Assembly.GetExecutingAssembly(); foreach (Type pluginType in currentasm.GetTypes()) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { if (pluginType.GetInterface("IDataSnapshotProvider") != null) { IDataSnapshotProvider module = (IDataSnapshotProvider)Activator.CreateInstance(pluginType); module.Initialize(scene, this); module.OnStale += MarkDataStale; m_dataproviders.Add(module); m_snapStore.AddProvider(module); //m_log.Info("[DATASNAPSHOT]: Added new data provider type: " + pluginType.Name); } } } } //scene.OnRestart += OnSimRestart; //scene.EventManager.OnShutdown += delegate() { OnSimRestart(scene.RegionInfo); }; scene.RegisterModuleInterface<IDataSnapshot>(this); } else { //m_log.Debug("[DATASNAPSHOT]: Data snapshot disabled, not adding scene to module (or anything else)."); } } public void RemoveRegion(IScene scene) { if (m_enabled && m_dataServices != "" && m_dataServices != "noservices") NotifyDataServices(m_dataServices, "offline"); } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { } public bool IsSharedModule { get { return true; } } public string Name { get { return "External Data Generator"; } } public void PostInitialise() { } #endregion #region Associated helper functions public IScene SceneForName(string name) { foreach (IScene scene in m_scenes) if (scene.RegionInfo.RegionName == name) return scene; return null; } public IScene SceneForUUID(UUID id) { foreach (IScene scene in m_scenes) if (scene.RegionInfo.RegionID == id) return scene; return null; } #endregion #region [Public] Snapshot storage functions /** * Reply to the http request */ public XmlDocument GetSnapshot(string regionName) { CheckStale(); XmlDocument requestedSnap = new XmlDocument(); requestedSnap.AppendChild(requestedSnap.CreateXmlDeclaration("1.0", null, null)); requestedSnap.AppendChild(requestedSnap.CreateWhitespace("\r\n")); XmlNode regiondata = requestedSnap.CreateNode(XmlNodeType.Element, "regiondata", ""); try { if (regionName == null || regionName == "") { XmlNode timerblock = requestedSnap.CreateNode(XmlNodeType.Element, "expire", ""); timerblock.InnerText = m_period.ToString(); regiondata.AppendChild(timerblock); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); foreach (IScene scene in m_scenes) { regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } } else { IScene scene = SceneForName(regionName); regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } requestedSnap.AppendChild(regiondata); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); } catch (XmlException e) { m_log.Warn("[DATASNAPSHOT]: XmlException while trying to load snapshot: " + e.ToString()); requestedSnap = GetErrorMessage(regionName, e); } catch (Exception e) { m_log.Warn("[DATASNAPSHOT]: Caught unknown exception while trying to load snapshot: " + e.StackTrace); requestedSnap = GetErrorMessage(regionName, e); } return requestedSnap; } private XmlDocument GetErrorMessage(string regionName, Exception e) { XmlDocument errorMessage = new XmlDocument(); XmlNode error = errorMessage.CreateNode(XmlNodeType.Element, "error", ""); XmlNode region = errorMessage.CreateNode(XmlNodeType.Element, "region", ""); region.InnerText = regionName; XmlNode exception = errorMessage.CreateNode(XmlNodeType.Element, "exception", ""); exception.InnerText = e.ToString(); error.AppendChild(region); error.AppendChild(exception); errorMessage.AppendChild(error); return errorMessage; } #endregion #region External data services private void NotifyDataServices(string servicesStr, string serviceName) { Stream reply = null; string delimStr = ";"; char [] delimiter = delimStr.ToCharArray(); string[] services = servicesStr.Split(delimiter); for (int i = 0; i < services.Length; i++) { string url = services[i].Trim(); RestClient cli = new RestClient(url); cli.AddQueryParameter("service", serviceName); cli.AddQueryParameter("host", m_hostname); cli.AddQueryParameter("port", m_listener_port); cli.RequestMethod = "GET"; try { reply = cli.Request(); } catch (WebException) { m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url); } catch (Exception e) { m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString()); } byte[] response = new byte[1024]; // int n = 0; try { // n = reply.Read(response, 0, 1024); reply.Read(response, 0, 1024); } catch (Exception e) { m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace); } // This is not quite working, so... // string responseStr = Util.UTF8.GetString(response); //m_log.Info("[DATASNAPSHOT]: data service notified: " + url); } } #endregion #region Latency-based update functions public void MarkDataStale(IDataSnapshotProvider provider) { //Behavior here: Wait m_period seconds, then update if there has not been a request in m_period seconds //or m_maxStales has been exceeded m_stales++; } private void CheckStale() { // Wrap check if (Environment.TickCount < m_lastUpdate) { m_lastUpdate = Environment.TickCount; } if (m_stales >= m_maxStales) { if (Environment.TickCount - m_lastUpdate >= 20000) { m_stales = 0; m_lastUpdate = Environment.TickCount; MakeEverythingStale(); } } else { if (m_lastUpdate + 1000 * m_period < Environment.TickCount) { m_stales = 0; m_lastUpdate = Environment.TickCount; MakeEverythingStale(); } } } public void MakeEverythingStale() { //m_log.Debug("[DATASNAPSHOT]: Marking all scenes as stale."); foreach (IScene scene in m_scenes) { m_snapStore.ForceSceneStale(scene); } } #endregion public void OnSimRestart(RegionInfo thisRegion) { //m_log.Info("[DATASNAPSHOT]: Region " + thisRegion.RegionName + " is restarting, removing from indexing"); IScene restartedScene = SceneForUUID(thisRegion.RegionID); m_scenes.Remove(restartedScene); m_snapStore.RemoveScene(restartedScene); //Getting around the fact that we can't remove objects from a collection we are enumerating over List<IDataSnapshotProvider> providersToRemove = new List<IDataSnapshotProvider>(); foreach (IDataSnapshotProvider provider in m_dataproviders) { if (provider.GetParentScene == restartedScene) { providersToRemove.Add(provider); } } foreach (IDataSnapshotProvider provider in providersToRemove) { m_dataproviders.Remove(provider); m_snapStore.RemoveProvider(provider); } m_snapStore.RemoveScene(restartedScene); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if !FEATURE_SERIALIZATION namespace System.CodeDom #else namespace System.Runtime.Serialization #endif { [Flags] #if !FEATURE_SERIALIZATION public enum CodeTypeReferenceOptions #else internal enum CodeTypeReferenceOptions #endif { GlobalReference = 0x00000001, GenericTypeParameter = 0x00000002 } #if !FEATURE_SERIALIZATION public class CodeTypeReference : CodeObject #else internal class CodeTypeReference : CodeObject #endif { private string _baseType; private readonly bool _isInterface; private CodeTypeReferenceCollection _typeArguments; private bool _needsFixup = false; public CodeTypeReference() { _baseType = string.Empty; ArrayRank = 0; ArrayElementType = null; } public CodeTypeReference(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsArray) { ArrayRank = type.GetArrayRank(); ArrayElementType = new CodeTypeReference(type.GetElementType()); _baseType = null; } else { InitializeFromType(type); ArrayRank = 0; ArrayElementType = null; } _isInterface = type.IsInterface; } public CodeTypeReference(Type type, CodeTypeReferenceOptions codeTypeReferenceOption) : this(type) { Options = codeTypeReferenceOption; } public CodeTypeReference(string typeName, CodeTypeReferenceOptions codeTypeReferenceOption) { Initialize(typeName, codeTypeReferenceOption); } public CodeTypeReference(string typeName) { Initialize(typeName); } private void InitializeFromType(Type type) { _baseType = type.Name; if (!type.IsGenericParameter) { Type currentType = type; while (currentType.IsNested) { currentType = currentType.DeclaringType; _baseType = currentType.Name + "+" + _baseType; } if (!string.IsNullOrEmpty(type.Namespace)) { _baseType = type.Namespace + "." + _baseType; } } // pick up the type arguments from an instantiated generic type but not an open one if (type.IsGenericType && !type.ContainsGenericParameters) { Type[] genericArgs = type.GetGenericArguments(); for (int i = 0; i < genericArgs.Length; i++) { TypeArguments.Add(new CodeTypeReference(genericArgs[i])); } } else if (!type.IsGenericTypeDefinition) { // if the user handed us a non-generic type, but later // appends generic type arguments, we'll pretend // it's a generic type for their sake - this is good for // them if they pass in System.Nullable class when they // meant the System.Nullable<T> value type. _needsFixup = true; } } private void Initialize(string typeName) { Initialize(typeName, Options); } private void Initialize(string typeName, CodeTypeReferenceOptions options) { Options = options; if (string.IsNullOrEmpty(typeName)) { typeName = typeof(void).FullName; _baseType = typeName; ArrayRank = 0; ArrayElementType = null; return; } typeName = RipOffAssemblyInformationFromTypeName(typeName); int end = typeName.Length - 1; int current = end; _needsFixup = true; // default to true, and if we find arity or generic type args, we'll clear the flag. // Scan the entire string for valid array tails and store ranks for array tails // we found in a queue. var q = new Queue<int>(); while (current >= 0) { int rank = 1; if (typeName[current--] == ']') { while (current >= 0 && typeName[current] == ',') { rank++; current--; } if (current >= 0 && typeName[current] == '[') { // found a valid array tail q.Enqueue(rank); current--; end = current; continue; } } break; } // Try find generic type arguments current = end; var typeArgumentList = new List<CodeTypeReference>(); var subTypeNames = new Stack<string>(); if (current > 0 && typeName[current--] == ']') { _needsFixup = false; int unmatchedRightBrackets = 1; int subTypeNameEndIndex = end; // Try find the matching '[', if we can't find it, we will not try to parse the string while (current >= 0) { if (typeName[current] == '[') { // break if we found matched brackets if (--unmatchedRightBrackets == 0) break; } else if (typeName[current] == ']') { ++unmatchedRightBrackets; } else if (typeName[current] == ',' && unmatchedRightBrackets == 1) { // // Type name can contain nested generic types. Following is an example: // System.Collections.Generic.Dictionary`2[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], // [System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], // mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] // // Spliltting by ',' won't work. We need to do first-level split by ','. // if (current + 1 < subTypeNameEndIndex) { subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1)); } subTypeNameEndIndex = current; } --current; } if (current > 0 && (end - current - 1) > 0) { // push the last generic type argument name if there is any if (current + 1 < subTypeNameEndIndex) { subTypeNames.Push(typeName.Substring(current + 1, subTypeNameEndIndex - current - 1)); } // we found matched brackets and the brackets contains some characters. while (subTypeNames.Count > 0) { string name = RipOffAssemblyInformationFromTypeName(subTypeNames.Pop()); typeArgumentList.Add(new CodeTypeReference(name)); } end = current - 1; } } if (end < 0) { // this can happen if we have some string like "[...]" _baseType = typeName; return; } if (q.Count > 0) { CodeTypeReference type = new CodeTypeReference(typeName.Substring(0, end + 1), Options); for (int i = 0; i < typeArgumentList.Count; i++) { type.TypeArguments.Add(typeArgumentList[i]); } while (q.Count > 1) { type = new CodeTypeReference(type, q.Dequeue()); } // we don't need to create a new CodeTypeReference for the last one. Debug.Assert(q.Count == 1, "We should have one and only one in the rank queue."); _baseType = null; ArrayRank = q.Dequeue(); ArrayElementType = type; } else if (typeArgumentList.Count > 0) { for (int i = 0; i < typeArgumentList.Count; i++) { TypeArguments.Add(typeArgumentList[i]); } _baseType = typeName.Substring(0, end + 1); } else { _baseType = typeName; } // Now see if we have some arity. baseType could be null if this is an array type. if (_baseType != null && _baseType.IndexOf('`') != -1) // string.Contains(char) is .NetCore2.1+ specific { _needsFixup = false; } } public CodeTypeReference(string typeName, params CodeTypeReference[] typeArguments) : this(typeName) { if (typeArguments != null && typeArguments.Length > 0) { TypeArguments.AddRange(typeArguments); } } #if !FEATURE_SERIALIZATION public CodeTypeReference(CodeTypeParameter typeParameter) : this(typeParameter?.Name) { Options = CodeTypeReferenceOptions.GenericTypeParameter; } #endif public CodeTypeReference(string baseType, int rank) { _baseType = null; ArrayRank = rank; ArrayElementType = new CodeTypeReference(baseType); } public CodeTypeReference(CodeTypeReference arrayType, int rank) { _baseType = null; ArrayRank = rank; ArrayElementType = arrayType; } public CodeTypeReference ArrayElementType { get; set; } public int ArrayRank { get; set; } internal int NestedArrayDepth => ArrayElementType == null ? 0 : 1 + ArrayElementType.NestedArrayDepth; public string BaseType { get { if (ArrayRank > 0 && ArrayElementType != null) { return ArrayElementType.BaseType; } if (string.IsNullOrEmpty(_baseType)) { return string.Empty; } string returnType = _baseType; return _needsFixup && TypeArguments.Count > 0 ? returnType + '`' + TypeArguments.Count.ToString(CultureInfo.InvariantCulture) : returnType; } set { _baseType = value; Initialize(_baseType); } } public CodeTypeReferenceOptions Options { get; set; } public CodeTypeReferenceCollection TypeArguments { get { if (ArrayRank > 0 && ArrayElementType != null) { return ArrayElementType.TypeArguments; } if (_typeArguments == null) { _typeArguments = new CodeTypeReferenceCollection(); } return _typeArguments; } } internal bool IsInterface => _isInterface; // Note that this only works correctly if the Type ctor was used. Otherwise, it's always false. // // The string for generic type argument might contain assembly information and square bracket pair. // There might be leading spaces in front the type name. // Following function will rip off assembly information and brackets // Following is an example: // " [System.Collections.Generic.List[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, // PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]" // private string RipOffAssemblyInformationFromTypeName(string typeName) { int start = 0; int end = typeName.Length - 1; string result = typeName; // skip whitespace in the beginning while (start < typeName.Length && char.IsWhiteSpace(typeName[start])) start++; while (end >= 0 && char.IsWhiteSpace(typeName[end])) end--; if (start < end) { if (typeName[start] == '[' && typeName[end] == ']') { start++; end--; } // if we still have a ] at the end, there's no assembly info. if (typeName[end] != ']') { int commaCount = 0; for (int index = end; index >= start; index--) { if (typeName[index] == ',') { commaCount++; if (commaCount == 4) { result = typeName.Substring(start, index - start); break; } } } } } return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Xml; using OLEDB.Test.ModuleCore; using System.Collections; using System.Collections.Generic; using System.Xml.XmlDiff; namespace XmlCoreTest.Common { /* * Helper class used by all test frameworks to create an instance of XmlWriter * Supports the following writer types */ public enum WriterType { UTF8Writer, // V2 writer with Encoding.UTF8 UnicodeWriter, // V2 writer with Encoding.Unicode CustomWriter, // CustomWriter implemented in this same folder CharCheckingWriter, // CharCheckingWriter implemented in this same folder UTF8WriterIndent, // UTF8WriterIndent implemented in this same folder UnicodeWriterIndent, // UnicodeWriterIndent implemented in this same folder WrappedWriter // WrappedWriter implemented in this same folder } public class WriterFactory { private string _fileName; protected WriterType writerType1; public WriterType WriterType { get { return writerType1; } } public WriterFactory(WriterType t) { writerType1 = t; } private XmlWriterSettings _wSettings = null; private XmlWriter _xmlWriter = null; private Stream _writerStream = null; XmlWriter CreateWriterImpl() { this.CleanUp(); switch (writerType1) { case WriterType.UTF8Writer: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; _wSettings.Encoding = Encoding.UTF8; _wSettings.NamespaceHandling = NamespaceHandling.Default; _xmlWriter = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); break; case WriterType.UnicodeWriter: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; _wSettings.Encoding = Encoding.Unicode; _wSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; _xmlWriter = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); break; case WriterType.CustomWriter: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; FilePathUtil.addStream(_fileName, _writerStream); _xmlWriter = new CustomWriter(_fileName, _wSettings); break; case WriterType.UTF8WriterIndent: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; _wSettings.Encoding = Encoding.UTF8; _wSettings.Indent = true; _xmlWriter = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); break; case WriterType.UnicodeWriterIndent: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; _wSettings.Encoding = Encoding.Unicode; _wSettings.Indent = true; _xmlWriter = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); break; case WriterType.CharCheckingWriter: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; _wSettings.CheckCharacters = false; XmlWriter ww = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); XmlWriterSettings ws = _wSettings.Clone(); ws.CheckCharacters = true; _xmlWriter = WriterHelper.Create(ww, ws); break; case WriterType.WrappedWriter: _writerStream = new MemoryStream(); _wSettings.CloseOutput = false; XmlWriter w = WriterHelper.Create(_writerStream, _wSettings); FilePathUtil.addStream(_fileName, _writerStream); _xmlWriter = WriterHelper.Create(w, _wSettings); break; default: throw new Exception("Incorrect writer type"); } return _xmlWriter; } public XmlWriter CreateWriter() { _fileName = "writer.out"; return this.CreateWriter(_fileName); } public XmlWriter CreateWriter(string fileName) { _fileName = fileName; _wSettings = new XmlWriterSettings(); _wSettings.OmitXmlDeclaration = true; _wSettings.ConformanceLevel = ConformanceLevel.Document; _wSettings.CloseOutput = true; return this.CreateWriterImpl(); } public XmlWriter CreateWriter(string fileName, XmlWriterSettings wSettings) { _wSettings = wSettings; _fileName = fileName; return this.CreateWriterImpl(); } public XmlWriter CreateWriter(XmlWriterSettings wSettings) { _wSettings = wSettings; _fileName = "writer.out"; return this.CreateWriterImpl(); } public XmlWriter CreateWriter(ConformanceLevel cl) { _fileName = "writer.out"; _wSettings = new XmlWriterSettings(); _wSettings.ConformanceLevel = cl; _wSettings.OmitXmlDeclaration = true; _wSettings.CloseOutput = true; return this.CreateWriterImpl(); } public string GetString() { string strRet = String.Empty; switch (writerType1) { case WriterType.UTF8Writer: case WriterType.UnicodeWriter: case WriterType.CustomWriter: case WriterType.UTF8WriterIndent: case WriterType.UnicodeWriterIndent: case WriterType.CharCheckingWriter: case WriterType.WrappedWriter: Stream tempStream = new MemoryStream(); FilePathUtil.getStream(_fileName).CopyTo(tempStream); if (tempStream.CanSeek) { tempStream.Position = 0; } using (Stream temp = tempStream) { using (StreamReader srTemp = new StreamReader(temp)) { strRet = srTemp.ReadToEnd(); } } break; default: throw new Exception("Incorrect writer type"); } return strRet; } public XmlReader GetReader() { XmlReader xr = null; XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; readerSettings.CloseInput = false; readerSettings.ConformanceLevel = ConformanceLevel.Auto; switch (WriterType) { case WriterType.UTF8Writer: case WriterType.UnicodeWriter: case WriterType.CustomWriter: case WriterType.UTF8WriterIndent: case WriterType.UnicodeWriterIndent: case WriterType.CharCheckingWriter: case WriterType.WrappedWriter: xr = ReaderHelper.Create(FilePathUtil.getStream(_fileName), readerSettings); break; default: throw new Exception("Incorrect writer type"); } return xr; } public bool CompareReader(XmlReader xrExpected) { return CompareReader(xrExpected, XmlDiffOption.IgnoreAttributeOrder); } public bool CompareReader(XmlReader xrExpected, XmlDiffOption option) { bool bReturn = false; XmlReader xrActual = GetReader(); XmlDiff diff = new XmlDiff(); diff.Option = option; try { bReturn = diff.Compare(xrExpected, xrActual); } catch (Exception e) { CError.WriteLine(e); } finally { xrActual.Dispose(); xrExpected.Dispose(); } if (!bReturn) { CError.WriteLine("Mismatch in XmlDiff"); CError.WriteLine("Actual o/p:"); CError.WriteLine(this.GetString()); } return bReturn; } public bool CompareString(string strExpected) { string strActual = this.GetString(); if (strExpected != strActual) { int expLen = (strExpected == null ? 0 : strExpected.Length); int actLen = (strActual == null ? 0 : strActual.Length); int minLen = (expLen < actLen ? expLen : actLen); // find the first different character int i; for (i = 0; i < minLen; i++) { if (strExpected[i] != strActual[i]) { CError.WriteLine("Position:" + i); CError.WriteLine("Expected char:'" + strExpected[i] + "'(" + Convert.ToInt32(strExpected[i]) + ")"); CError.WriteLine("Actual char:'" + strActual[i] + "'(" + Convert.ToInt32(strActual[i]) + ")"); break; } } if (i == minLen) { // one string contains the other CError.WriteLine("Expected length:" + expLen + " Actual length:" + actLen); return false; } CError.WriteLine("Expected string:" + strExpected); CError.WriteLine("Actual string:" + strActual); CError.Compare(false, "CompareString failed"); return false; } return true; } private const char PREFIX_CHAR = '~'; private const char AUTOGENERATED = 'a'; private const char FIXED = 'f'; public bool CompareStringWithPrefixes(string strExpected) { MyDict<string, object> AutoIDs = new MyDict<string, object>(); List<string> AttNames = new List<string>(); List<string> AttScopes = new List<string>(); string strActual = this.GetString(); int expLen = (strExpected == null ? 0 : strExpected.Length); int actLen = (strActual == null ? 0 : strActual.Length); int minLen = (expLen < actLen ? expLen : actLen); // find the first different character int i, j = 0; for (i = 0; i < actLen; i++) { if (j >= expLen) { CError.WriteLine("Output longer than expected!"); CError.WriteLine("Actual string: '" + strActual + "'"); return false; } if (strExpected[j] != strActual[i]) { if (strExpected[j] != PREFIX_CHAR) { CError.WriteLine("Position:" + i); CError.WriteLine("Expected char:'" + strExpected[i] + "'(" + Convert.ToInt32(strExpected[i]) + ")"); CError.WriteLine("Actual char:'" + strActual[i] + "'(" + Convert.ToInt32(strActual[i]) + ")"); return false; } bool AutoGenerated = strExpected[++j] == AUTOGENERATED; j += 2; string ActName = ""; string ExpName = ""; string Scope = ""; while (i <= actLen) { if (strActual[i] == '=' || strActual[i] == ' ' || strActual[i] == ':') { i--; break; } else { ActName += strActual[i]; } i++; } while (strExpected[j] != ' ') { ExpName += strExpected[j++]; } j++; while (strExpected[j] != PREFIX_CHAR) { Scope += strExpected[j++]; } if (AutoGenerated) { if (AutoIDs.ContainsKey(ExpName)) { if ((string)AutoIDs[ExpName] != ActName) { CError.WriteLine("Invalid Prefix: '" + ActName + "'"); return false; } } else { AutoIDs.Add(ExpName, ActName); } } else { if (ExpName != ActName) { CError.WriteLine("Invalid Prefix: '" + ActName + "'"); return false; } } for (int k = 0; k < AttNames.Count; k++) { if ((string)AttNames[k] == ActName) { for (int m = 0; m < ((string)AttScopes[k]).Length; m++) for (int n = 0; n < Scope.Length; n++) if (((string)AttScopes[k])[m] == Scope[n]) { CError.WriteLine("Invalid Prefix: '" + ActName + "'"); return false; } } } AttNames.Add(ActName); AttScopes.Add(Scope); } j++; } if (j != expLen) { CError.WriteLine("Output shorter than expected!"); CError.WriteLine("Actual string: '" + strActual + "'"); return false; } return true; } public void CleanUp() { if (_writerStream != null) _writerStream.Dispose(); } } public static class WriterHelper { public static XmlWriter Create(string outputFileName) { FilePathUtil.addStream(outputFileName, new MemoryStream()); if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(FilePathUtil.getStream(outputFileName)); } else { return XmlWriter.Create(FilePathUtil.getStream(outputFileName)); } } public static XmlWriter Create(string outputFileName, XmlWriterSettings settings) { FilePathUtil.addStream(outputFileName, new MemoryStream()); if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(FilePathUtil.getStream(outputFileName), settings); } else { return XmlWriter.Create(FilePathUtil.getStream(outputFileName), settings); } } public static XmlWriter Create(Stream output) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output); } else { return XmlWriter.Create(output); } } public static XmlWriter Create(Stream output, XmlWriterSettings settings) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output, settings); } else { return XmlWriter.Create(output, settings); } } public static XmlWriter Create(TextWriter output) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output); } else { return XmlWriter.Create(output); } } public static XmlWriter Create(TextWriter output, XmlWriterSettings settings) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output, settings); } else { return XmlWriter.Create(output, settings); } } public static XmlWriter Create(StringBuilder output) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output); } else { return XmlWriter.Create(output); } } public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output, settings); } else { return XmlWriter.Create(output, settings); } } public static XmlWriter Create(XmlWriter output) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output); } else { return XmlWriter.Create(output); } } public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings) { if (AsyncUtil.IsAsyncEnabled) { return XmlWriterAsync.Create(output, settings); } else { return XmlWriter.Create(output, settings); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using NUnit.Framework; using NUnit.Framework.Internal; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Extensions; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing.Drawables; using osu.Framework.Testing.Drawables.Steps; using osu.Framework.Timing; using osuTK; using osuTK.Graphics; using osuTK.Input; using Logger = osu.Framework.Logging.Logger; namespace osu.Framework.Testing { [Cached] public class TestBrowser : KeyBindingContainer<TestBrowserAction>, IKeyBindingHandler<TestBrowserAction>, IHandleGlobalKeyboardInput { public TestScene CurrentTest { get; private set; } private BasicTextBox searchTextBox; private SearchContainer<TestGroupButton> leftFlowContainer; private Container testContentContainer; private Container compilingNotice; public readonly List<Type> TestTypes = new List<Type>(); private ConfigManager<TestBrowserSetting> config; private DynamicClassCompiler<TestScene> backgroundCompiler; private bool interactive; private readonly List<Assembly> assemblies; /// <summary> /// Creates a new TestBrowser that displays the TestCases of every assembly that start with either "osu" or the specified namespace (if it isn't null) /// </summary> /// <param name="assemblyNamespace">Assembly prefix which is used to match assemblies whose tests should be displayed</param> public TestBrowser(string assemblyNamespace = null) { assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n => n.FullName.StartsWith("osu") || assemblyNamespace != null && n.FullName.StartsWith(assemblyNamespace)).ToList(); //we want to build the lists here because we're interested in the assembly we were *created* on. foreach (Assembly asm in assemblies.ToList()) { var tests = asm.GetLoadableTypes().Where(isValidVisualTest).ToList(); if (!tests.Any()) { assemblies.Remove(asm); continue; } foreach (Type type in tests) TestTypes.Add(type); } TestTypes.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal)); } private bool isValidVisualTest(Type t) => t.IsSubclassOf(typeof(TestScene)) && !t.IsAbstract && t.IsPublic && !t.GetCustomAttributes<HeadlessTestAttribute>().Any(); private void updateList(ValueChangedEvent<Assembly> args) { leftFlowContainer.Clear(); //Add buttons for each TestCase. string namespacePrefix = TestTypes.Select(t => t.Namespace).GetCommonPrefix(); leftFlowContainer.AddRange(TestTypes.Where(t => t.Assembly == args.NewValue) .GroupBy( t => { string group = t.Namespace?.AsSpan(namespacePrefix.Length).TrimStart('.').ToString(); return string.IsNullOrWhiteSpace(group) ? "Ungrouped" : group; }, t => t, (group, types) => new TestGroup { Name = group, TestTypes = types.ToArray() } ).OrderBy(g => g.Name) .Select(t => new TestGroupButton(type => LoadTest(type), t))); } internal readonly BindableDouble PlaybackRate = new BindableDouble(1) { MinValue = 0, MaxValue = 2, Default = 1 }; internal readonly Bindable<Assembly> Assembly = new Bindable<Assembly>(); internal readonly Bindable<bool> RunAllSteps = new Bindable<bool>(); internal readonly Bindable<RecordState> RecordState = new Bindable<RecordState>(); internal readonly BindableInt CurrentFrame = new BindableInt { MinValue = 0, MaxValue = 0 }; private TestBrowserToolbar toolbar; private Container leftContainer; private Container mainContainer; private const float test_list_width = 200; private Action exit; private Bindable<bool> showLogOverlay; private readonly BindableDouble audioRateAdjust = new BindableDouble(1); [BackgroundDependencyLoader] private void load(Storage storage, GameHost host, FrameworkConfigManager frameworkConfig, FontStore fonts, Game game, AudioManager audio) { interactive = host.Window != null; config = new TestBrowserConfig(storage); exit = host.Exit; audio.AddAdjustment(AdjustableProperty.Frequency, audioRateAdjust); var resources = game.Resources; //Roboto game.AddFont(resources, @"Fonts/Roboto/Roboto-Regular"); game.AddFont(resources, @"Fonts/Roboto/Roboto-Bold"); //RobotoCondensed game.AddFont(resources, @"Fonts/RobotoCondensed/RobotoCondensed-Regular"); game.AddFont(resources, @"Fonts/RobotoCondensed/RobotoCondensed-Bold"); showLogOverlay = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay); var rateAdjustClock = new StopwatchClock(true); var framedClock = new FramedClock(rateAdjustClock); Children = new Drawable[] { mainContainer = new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Left = test_list_width }, Children = new Drawable[] { new SafeAreaContainer { SafeAreaOverrideEdges = Edges.Right | Edges.Bottom, RelativeSizeAxes = Axes.Both, Child = testContentContainer = new Container { Clock = framedClock, RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = 50 }, Child = compilingNotice = new Container { Alpha = 0, Anchor = Anchor.Centre, Origin = Anchor.Centre, Masking = true, Depth = float.MinValue, CornerRadius = 5, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, new SpriteText { Font = new FontUsage(size: 30), Text = @"Compiling new version..." } }, } } }, toolbar = new TestBrowserToolbar { RelativeSizeAxes = Axes.X, Height = 50, }, } }, leftContainer = new Container { RelativeSizeAxes = Axes.Y, Size = new Vector2(test_list_width, 1), Masking = true, Children = new Drawable[] { new SafeAreaContainer { SafeAreaOverrideEdges = Edges.Left | Edges.Top | Edges.Bottom, RelativeSizeAxes = Axes.Both, Child = new Box { Colour = FrameworkColour.GreenDark, RelativeSizeAxes = Axes.Both } }, new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { searchTextBox = new TestBrowserTextBox { OnCommit = delegate { var firstTest = leftFlowContainer.Where(b => b.IsPresent).SelectMany(b => b.FilterableChildren).OfType<TestSubButton>() .FirstOrDefault(b => b.MatchingFilter)?.TestType; if (firstTest != null) LoadTest(firstTest); }, Height = 25, RelativeSizeAxes = Axes.X, PlaceholderText = "type to search", Depth = -1, }, new BasicScrollContainer { RelativeSizeAxes = Axes.Both, Masking = false, Child = leftFlowContainer = new SearchContainer<TestGroupButton> { Padding = new MarginPadding { Top = 3, Bottom = 20 }, Direction = FillDirection.Vertical, AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, } } } } } }, }; searchTextBox.Current.ValueChanged += e => leftFlowContainer.SearchTerm = e.NewValue; if (RuntimeInfo.SupportsJIT) { backgroundCompiler = new DynamicClassCompiler<TestScene>(); backgroundCompiler.CompilationStarted += compileStarted; backgroundCompiler.CompilationFinished += compileFinished; backgroundCompiler.CompilationFailed += compileFailed; try { backgroundCompiler.Start(); } catch { //it's okay for this to fail for now. } } foreach (Assembly asm in assemblies) toolbar.AddAssembly(asm.GetName().Name, asm); Assembly.BindValueChanged(updateList); RunAllSteps.BindValueChanged(v => runTests(null)); PlaybackRate.BindValueChanged(e => { rateAdjustClock.Rate = e.NewValue; audioRateAdjust.Value = e.NewValue; }, true); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); backgroundCompiler?.Dispose(); } private void compileStarted() => Schedule(() => { compilingNotice.Show(); compilingNotice.FadeColour(Color4.White); }); private void compileFailed(Exception ex) => Schedule(() => { showLogOverlay.Value = true; Logger.Error(ex, "Error with dynamic compilation!"); compilingNotice.FadeIn(100, Easing.OutQuint).Then().FadeOut(800, Easing.InQuint); compilingNotice.FadeColour(Color4.Red, 100); }); private void compileFinished(Type newType) => Schedule(() => { compilingNotice.FadeOut(800, Easing.InQuint); compilingNotice.FadeColour(Color4.YellowGreen, 100); if (newType == null) return; int i = TestTypes.FindIndex(t => t.Name == newType.Name && t.Assembly.GetName().Name == newType.Assembly.GetName().Name); if (i < 0) TestTypes.Add(newType); else TestTypes[i] = newType; try { LoadTest(newType, isDynamicLoad: true); } catch (Exception e) { compileFailed(e); } }); protected override void LoadComplete() { base.LoadComplete(); if (CurrentTest == null) LoadTest(TestTypes.Find(t => t.Name == config.Get<string>(TestBrowserSetting.LastTest))); } private void toggleTestList() { if (leftContainer.Width > 0) { leftContainer.Width = 0; mainContainer.Padding = new MarginPadding(); } else { leftContainer.Width = test_list_width; mainContainer.Padding = new MarginPadding { Left = test_list_width }; } } protected override bool OnKeyDown(KeyDownEvent e) { if (!e.Repeat) { switch (e.Key) { case Key.Escape: exit(); return true; } } return base.OnKeyDown(e); } public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(new[] { InputKey.Control, InputKey.F }, TestBrowserAction.Search), new KeyBinding(new[] { InputKey.Control, InputKey.R }, TestBrowserAction.Reload), // for macOS new KeyBinding(new[] { InputKey.Super, InputKey.F }, TestBrowserAction.Search), // for macOS new KeyBinding(new[] { InputKey.Super, InputKey.R }, TestBrowserAction.Reload), // for macOS new KeyBinding(new[] { InputKey.Control, InputKey.H }, TestBrowserAction.ToggleTestList), }; public bool OnPressed(TestBrowserAction action) { switch (action) { case TestBrowserAction.Search: if (leftContainer.Width == 0) toggleTestList(); GetContainingInputManager().ChangeFocus(searchTextBox); return true; case TestBrowserAction.Reload: LoadTest(CurrentTest.GetType()); return true; case TestBrowserAction.ToggleTestList: toggleTestList(); return true; } return false; } public void OnReleased(TestBrowserAction action) { } public void LoadTest(Type testType = null, Action onCompletion = null, bool isDynamicLoad = false) { if (CurrentTest?.Parent != null) { testContentContainer.Remove(CurrentTest.Parent); CurrentTest.Dispose(); } var lastTest = CurrentTest; CurrentTest = null; if (testType == null && TestTypes.Count > 0) testType = TestTypes[0]; config.Set(TestBrowserSetting.LastTest, testType?.Name ?? string.Empty); if (testType == null) return; var newTest = (TestScene)Activator.CreateInstance(testType); Debug.Assert(newTest != null); const string dynamic_prefix = "dynamic"; // if we are a dynamically compiled type (via DynamicClassCompiler) we should update the dropdown accordingly. if (isDynamicLoad) { newTest.DynamicCompilationOriginal = lastTest?.DynamicCompilationOriginal ?? lastTest ?? newTest; toolbar.AddAssembly($"{dynamic_prefix} ({testType.Name})", testType.Assembly); } else { TestTypes.RemoveAll(t => t.Assembly.FullName.Contains(dynamic_prefix)); newTest.DynamicCompilationOriginal = newTest; } Assembly.Value = testType.Assembly; CurrentTest = newTest; CurrentTest.OnLoadComplete += _ => Schedule(() => finishLoad(newTest, onCompletion)); updateButtons(); resetRecording(); testContentContainer.Add(new ErrorCatchingDelayedLoadWrapper(CurrentTest, isDynamicLoad) { OnCaughtError = compileFailed }); } private void resetRecording() { CurrentFrame.Value = 0; if (RecordState.Value == Testing.RecordState.Stopped) RecordState.Value = Testing.RecordState.Normal; } private void finishLoad(TestScene newTest, Action onCompletion) { if (CurrentTest != newTest) { // There could have been multiple loads fired after us. In such a case we want to silently remove ourselves. testContentContainer.Remove(newTest.Parent); return; } updateButtons(); bool hadTestAttributeTest = false; foreach (var m in newTest.GetType().GetMethods()) { var name = m.Name; if (name == nameof(TestScene.TestConstructor) || m.GetCustomAttribute(typeof(IgnoreAttribute), false) != null) continue; if (name.StartsWith("Test")) name = name.Substring(4); int runCount = 1; if (m.GetCustomAttribute(typeof(RepeatAttribute), false) != null) runCount += (int)m.GetCustomAttributesData().Single(a => a.AttributeType == typeof(RepeatAttribute)).ConstructorArguments.Single().Value; for (int i = 0; i < runCount; i++) { string repeatSuffix = i > 0 ? $" ({i + 1})" : string.Empty; if (m.GetCustomAttribute(typeof(TestAttribute), false) != null) { hadTestAttributeTest = true; CurrentTest.AddLabel($"{name}{repeatSuffix}"); handleTestMethod(m); } foreach (var tc in m.GetCustomAttributes(typeof(TestCaseAttribute), false).OfType<TestCaseAttribute>()) { hadTestAttributeTest = true; CurrentTest.AddLabel($"{name}({string.Join(", ", tc.Arguments)}){repeatSuffix}"); handleTestMethod(m, tc.Arguments); } } } // even if no [Test] or [TestCase] methods were found, [SetUp] steps should be added. if (!hadTestAttributeTest) addSetUpSteps(); backgroundCompiler?.SetRecompilationTarget(CurrentTest); runTests(onCompletion); updateButtons(); void addSetUpSteps() { var setUpMethods = Reflect.GetMethodsWithAttribute(newTest.GetType(), typeof(SetUpAttribute), true) .Where(m => m.Name != nameof(TestScene.SetUpTestForNUnit)); if (setUpMethods.Any()) { CurrentTest.AddStep(new SetUpStepButton { Action = () => setUpMethods.ForEach(s => s.Invoke(CurrentTest, null)) }); } CurrentTest.RunSetUpSteps(); } void handleTestMethod(MethodInfo methodInfo, object[] arguments = null) { addSetUpSteps(); methodInfo.Invoke(CurrentTest, arguments); CurrentTest.RunTearDownSteps(); } } private void runTests(Action onCompletion) { int actualStepCount = 0; CurrentTest.RunAllSteps(onCompletion, e => Logger.Log($@"Error on step: {e}"), s => { if (!interactive || RunAllSteps.Value) return false; if (actualStepCount > 0) // stop once one actual step has been run. return true; if (!(s is SetUpStepButton) && !(s is LabelStep)) actualStepCount++; return false; }); } private void updateButtons() { foreach (var b in leftFlowContainer.Children) b.Current = CurrentTest.GetType(); } private class ErrorCatchingDelayedLoadWrapper : DelayedLoadWrapper { private readonly bool catchErrors; private bool hasCaught; public Action<Exception> OnCaughtError; public ErrorCatchingDelayedLoadWrapper(Drawable content, bool catchErrors) : base(content, 0) { this.catchErrors = catchErrors; } public override bool UpdateSubTree() { try { return base.UpdateSubTree(); } catch (Exception e) { if (!catchErrors) throw; // without this we will enter an infinite loading loop (DelayedLoadWrapper will see the child removed below and retry). hasCaught = true; OnCaughtError?.Invoke(e); RemoveInternal(Content); } return false; } protected override bool ShouldLoadContent => !hasCaught; } private class TestBrowserTextBox : BasicTextBox { protected override float LeftRightPadding => TestButtonBase.LEFT_TEXT_PADDING; public TestBrowserTextBox() { TextFlow.Height = 0.75f; } } } internal enum RecordState { /// <summary> /// The game is playing back normally. /// </summary> Normal, /// <summary> /// Drawn game frames are currently being recorded. /// </summary> Recording, /// <summary> /// The default game playback is stopped, recorded frames are being played back. /// </summary> Stopped } public enum TestBrowserAction { ToggleTestList, Reload, Search } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Drawing; namespace Microsoft.DirectX.Direct3D { public sealed class RenderStateManager { public int BlendFactorColor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int FogColorValue { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int AmbientColor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool SrgbWriteEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Color BlendFactor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Color FogColor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Color Ambient { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public BlendOperation AlphaBlendOperation { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Blend AlphaDestinationBlend { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Blend AlphaSourceBlend { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool SeparateAlphaBlendEnabled { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorWriteEnable ColorWriteEnable3 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorWriteEnable ColorWriteEnable2 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorWriteEnable ColorWriteEnable1 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Compare CounterClockwiseStencilFunction { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation CounterClockwiseStencilPass { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation CounterClockwiseStencilZBufferFail { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation CounterClockwiseStencilFail { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool TwoSidedStencilMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool EnableAdaptiveTessellation { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float AdaptiveTessellateW { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float AdaptiveTessellateZ { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float AdaptiveTessellateY { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float AdaptiveTessellateX { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float MinTessellationLevel { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float MaxTessellationLevel { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool AntiAliasedLineEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float DepthBias { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float SlopeScaleDepthBias { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool ScissorTestEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public DegreeType NormalDegree { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public DegreeType PositionDegree { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public BlendOperation BlendOperation { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float TweenFactor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorWriteEnable ColorWriteEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool IndexedVertexBlendEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointSizeMax { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool DebugMonitorTokenEnabled { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public PatchEdge PatchEdgeStyle { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int MultiSampleMask { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool MultiSampleAntiAlias { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointScaleC { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointScaleB { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointScaleA { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool PointScaleEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool PointSpriteEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointSizeMin { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float PointSize { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public VertexBlend VertexBlend { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorSource EmissiveMaterialSource { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorSource AmbientMaterialSource { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorSource SpecularMaterialSource { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ColorSource DiffuseMaterialSource { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool NormalizeNormals { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool LocalViewer { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool ColorVertex { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public FogMode FogVertexMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool Lighting { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool Clipping { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap15 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap14 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap13 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap12 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap11 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap10 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap9 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap8 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap7 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap6 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap5 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap4 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap3 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap2 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap1 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WrapCoordinates Wrap0 { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int TextureFactor { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int StencilWriteMask { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int StencilMask { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int ReferenceStencil { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Compare StencilFunction { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation StencilPass { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation StencilZBufferFail { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public StencilOperation StencilFail { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool StencilEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool RangeFogEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float FogDensity { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float FogEnd { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public float FogStart { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public FogMode FogTableMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool SpecularEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool FogEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool AlphaBlendEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool DitherEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Compare AlphaFunction { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int ReferenceAlpha { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Compare ZBufferFunction { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Cull CullMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Blend DestinationBlend { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Blend SourceBlend { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool LastPixel { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool AlphaTestEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool ZBufferWriteEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool UseWBuffer { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool ZBufferEnable { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ShadeMode ShadeMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public FillMode FillMode { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public override string ToString () { throw new NotImplementedException (); } } }
using System; using System.IO; using System.Text; namespace BplusDotNet { /// <summary> /// Tree index mapping strings to strings. /// </summary> public class BplusTree : IStringTree { /// <summary> /// Internal tree mapping strings to bytes (for conversion to strings). /// </summary> public ITreeIndex Tree; public BplusTree(ITreeIndex tree) { if (!(tree is BplusTreeBytes) && checkTree()) { throw new BplusTreeException("Bplustree (superclass) can only wrap BplusTreeBytes, not other ITreeIndex implementations"); } Tree = tree; } protected virtual bool checkTree() { // this is to prevent accidental misuse with the wrong ITreeIndex implementation, // but to also allow subclasses to override the behaviour... (there must be a better way...) return true; } public static BplusTree Initialize(string treefileName, string blockfileName, int keyLength, int cultureId, int nodesize, int buffersize) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefileName, blockfileName, keyLength, cultureId, nodesize, buffersize); return new BplusTree(tree); } public static BplusTree Initialize(string treefileName, string blockfileName, int keyLength, int cultureId) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefileName, blockfileName, keyLength, cultureId); return new BplusTree(tree); } public static BplusTree Initialize(string treefileName, string blockfileName, int keyLength) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefileName, blockfileName, keyLength); return new BplusTree(tree); } public static BplusTree Initialize(Stream treefile, Stream blockfile, int keyLength, int cultureId, int nodesize, int buffersize) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefile, blockfile, keyLength, cultureId, nodesize, buffersize); return new BplusTree(tree); } public static BplusTree Initialize(Stream treefile, Stream blockfile, int keyLength, int cultureId) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefile, blockfile, keyLength, cultureId); return new BplusTree(tree); } public static BplusTree Initialize(Stream treefile, Stream blockfile, int keyLength) { BplusTreeBytes tree = BplusTreeBytes.Initialize(treefile, blockfile, keyLength); return new BplusTree(tree); } public static BplusTree ReOpen(Stream treefile, Stream blockfile) { BplusTreeBytes tree = BplusTreeBytes.ReOpen(treefile, blockfile); return new BplusTree(tree); } public static BplusTree ReOpen(string treefileName, string blockfileName) { BplusTreeBytes tree = BplusTreeBytes.ReOpen(treefileName, blockfileName); return new BplusTree(tree); } public static BplusTree ReadOnly(string treefileName, string blockfileName) { BplusTreeBytes tree = BplusTreeBytes.ReadOnly(treefileName, blockfileName); return new BplusTree(tree); } #region ITreeIndex Members public void Recover(bool correctErrors) { Tree.Recover(correctErrors); } public void RemoveKey(string key) { Tree.RemoveKey(key); } public string FirstKey() { return Tree.FirstKey(); } public string NextKey(string afterThisKey) { return Tree.NextKey(afterThisKey); } public bool ContainsKey(string key) { return Tree.ContainsKey(key); } public object Get(string key, object defaultValue) { object test = Tree.Get(key, ""); if (test is byte[]) { return BytesToString((byte[]) test); } return defaultValue; } public void Set(string key, object map) { if (!(map is string)) { throw new BplusTreeException("BplusTree only stores strings as values"); } var thestring = (string) map; byte[] bytes = StringToBytes(thestring); //this.tree[key] = bytes; Tree.Set(key, bytes); } public void Commit() { Tree.Commit(); } public void Abort() { Tree.Abort(); } public void SetFootPrintLimit(int limit) { Tree.SetFootPrintLimit(limit); } public void Shutdown() { Tree.Shutdown(); } public int Compare(string left, string right) { return Tree.Compare(left, right); } #endregion public string this[string key] { get { object theGet = Tree.Get(key, ""); if (theGet is byte[]) { var bytes = (byte[]) theGet; return BytesToString(bytes); } //System.Diagnostics.Debug.WriteLine(this.toHtml()); throw new BplusTreeKeyMissing("key not found "+key); } set { byte[] bytes = StringToBytes(value); //this.tree[key] = bytes; Tree.Set(key, bytes); } } public static string BytesToString(byte[] bytes) { Decoder decode = Encoding.UTF8.GetDecoder(); long length = decode.GetCharCount(bytes, 0, bytes.Length); var chars = new char[length]; decode.GetChars(bytes, 0, bytes.Length, chars, 0); var result = new String(chars); return result; } public static byte[] StringToBytes(string thestring) { Encoder encode = Encoding.UTF8.GetEncoder(); char[] chars = thestring.ToCharArray(); long length = encode.GetByteCount(chars, 0, chars.Length, true); var bytes = new byte[length]; encode.GetBytes(chars, 0, chars.Length,bytes, 0, true); return bytes; } public virtual string toHtml() { return ((BplusTreeBytes) Tree).toHtml(); } } }
// 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. // // Basic test for dependent handles. // // Note that though this test uses ConditionalWeakTable it is not a test for that class. This is a stress // test that utilizes ConditionalWeakTable features, which would be used heavily if Dynamic Language Runtime // catches on. // // Basic test overview: // * Allocate an array of objects (we call these Nodes) with finalizers. // * Create a set of dependent handles that reference these objects as primary and secondary members (this is // where ConditionalWeakTable comes in, adding a key/value pair to such a table creates a dependent handle // with the primary set to the key and the secondary set to the value). // * Null out selected objects from the array in various patterns. This removes the only normal strong root // for such objects (leaving only the dependent handles to provide additional roots). // * Perform a full GC and wait for it and finalization to complete. Each object which is collected will use // its finalizer to inform the test that it's been disposed of. // * Run our own reachability analysis (a simple mark array approach) to build a picture of which objects in // the array should have been collected or not. // * Validate that the actual set of live objects matches our computed live set exactly. // // Test variations include the number of objects allocated, the relationship between the primary and secondary // in each handle we allocate and the pattern with which we null out object references in the array. // // Additionally this test stresses substantially more complex code paths in the GC if server mode is enabled. // This can be achieved by setting the environment variable COMPlus_BuildFlavor=svr prior to executing the // test executable. // // Note that we don't go to any lengths to ensure that dependent handle ownership is spread over multiple cpus // on a server GC/MP test run. For large node counts (e.g. 100000) this happens naturally since initialization // takes a while with multiple thread/CPU switches involved. We could be more explicit here (allocate handles // using CPU affinitized threads) but if we do that we'd probably better look into different patterns of node // ownership to avoid unintentionally restricting our test coverage. // // Another area into which we could look deeper is trying to force mark stack overflows in the GC (presumably // by allocating complex object graphs with lots of interconnections, though I don't the specifics of the best // way to force this). Causing mark stack overflows should open up a class of bug the old dependent handle // implementation was subject to without requiring server GC mode or multiple CPUs. // using System; using System.Runtime.CompilerServices; // How we assign nodes to dependent handles. enum TableStyle { Unconnected, // The primary and secondary handles are assigned completely disjoint objects ForwardLinked, // The primary of each handle is the secondary of the previous handle BackwardLinked, // The primary of each handle is the secondary of the next handle Random // The primaries are each object in sequence, the secondaries are selected randomly from // the same set } // How we choose object references in the array to null out (and thus potentially become collected). enum CollectStyle { None, // Don't null out any (nothing should be collected) All, // Null them all out (any remaining live objects should be collected) Alternate, // Null out every second reference Random // Null out each entry with a 50% probability } // We report errors by throwing an exception. Define our own Exception subclass so we can identify these // errors unambiguously. class TestException : Exception { // We just supply a simple message string on error. public TestException(string message) : base(message) { } } // Class encapsulating test runs over a set of objects/handles allocated with the specified TableStyle. class TestSet { // Create a new test with the given table style and object count. public TestSet(TableStyle ts, int count) { // Use one random number generator for the life of the test. Could support explicit seeds for // reproducible tests here. m_rng = new Random(); // Remember our parameters. m_count = count; m_style = ts; // Various arrays. m_nodes = new Node[count]; // The array of objects m_collected = new bool[count]; // Records whether each object has been collected (entries are set by // the finalizer on Node) m_marks = new bool[count]; // Array used during individual test runs to calculate whether each // object should still be alive (allocated once here to avoid // injecting further garbage collections at run time) // Allocate each object (Node). Each knows its own unique ID (the index into the node array) and has a // back pointer to this test object (so it can phone home to report its own collection at finalization // time). for (int i = 0; i < count; i++) m_nodes[i] = new Node(this, i); // Determine how many handles we need to allocate given the number of nodes. This varies based on the // table style. switch (ts) { case TableStyle.Unconnected: // Primaries and secondaries are completely different objects so we split our nodes in half and // allocate that many handles. m_handleCount = count / 2; break; case TableStyle.ForwardLinked: // Nodes are primaries in one handle and secondary in another except one that falls off the end. // So we have as many handles as nodes - 1. m_handleCount = count - 1; break; case TableStyle.BackwardLinked: // Nodes are primaries in one handle and secondary in another except one that falls off the end. // So we have as many handles as nodes - 1. m_handleCount = count - 1; break; case TableStyle.Random: // Each node is a primary in some handle (secondaries are selected from amongst all the same nodes // randomly). So we have as many nodes as handles. m_handleCount = count; break; } // Allocate an array of HandleSpecs. These aren't the real handles, just structures that allow us // remember what's in each handle (in terms of the node index number for the primary and secondary). // We need to track this information separately because we can't access the real handles directly // (ConditionalWeakTable hides them) and we need to recall exactly what the primary and secondary of // each handle is so we can compute our own notion of object liveness later. m_handles = new HandleSpec[m_handleCount]; // Initialize the handle specs to assign objects to handles based on the table style. for (int i = 0; i < m_handleCount; i++) { int primary = -1, secondary = -1; switch (ts) { case TableStyle.Unconnected: // Assign adjacent nodes to the primary and secondary of each handle. primary = i * 2; secondary = (i * 2) + 1; break; case TableStyle.ForwardLinked: // Primary of each handle is the secondary of the last handle. primary = i; secondary = i + 1; break; case TableStyle.BackwardLinked: // Primary of each handle is the secondary of the next handle. primary = i + 1; secondary = i; break; case TableStyle.Random: // Primary is each node in sequence, secondary is any of the nodes randomly. primary = i; secondary = m_rng.Next(m_handleCount); break; } m_handles[i].Set(primary, secondary); } // Allocate a ConditionalWeakTable mapping Node keys to Node values. m_table = new ConditionalWeakTable<Node, Node>(); // Using our handle specs computed above add each primary/secondary node pair to the // ConditionalWeakTable in turn. This causes the ConditionalWeakTable to allocate a dependent handle // for each entry with the primary and secondary objects we specified as keys and values (note that // this scheme prevents us from creating multiple handles with the same primary though if this is // desired we could achieve it by allocating multiple ConditionalWeakTables). for (int i = 0; i < m_handleCount; i++) m_table.Add(m_nodes[m_handles[i].m_primary], m_nodes[m_handles[i].m_secondary]); } // Call this method to indicate a test error with a given message. This will terminate the test // immediately. void Error(string message) { throw new TestException(message); } // Run a single test pass on the node set. Null out node references according to the given CollectStyle, // run a garbage collection and then verify that each node is either live or dead as we predict. Take care // of the order in which test runs are made against a single TestSet: e.g. running a CollectStyle.All will // collect all nodes, rendering further runs relatively uninteresting. public void Run(CollectStyle cs) { Console.WriteLine("Running test TS:{0} CS:{1} {2} entries...", Enum.GetName(typeof(TableStyle), m_style), Enum.GetName(typeof(CollectStyle), cs), m_count); // Iterate over the array of nodes deciding for each whether to sever the reference (null out the // entry). for (int i = 0; i < m_count; i++) { bool sever = false; switch (cs) { case CollectStyle.All: // Sever all references. sever = true; break; case CollectStyle.None: // Don't sever any references. break; case CollectStyle.Alternate: // Sever every second reference (starting with the first). if ((i % 2) == 0) sever = true; break; case CollectStyle.Random: // Sever any reference with a 50% probability. if (m_rng.Next(100) > 50) sever = true; break; } if (sever) m_nodes[i] = null; } // Initialize a full GC and wait for all finalizers to complete (so we get an accurate picture of // which nodes were collected). GC.Collect(); GC.WaitForPendingFinalizers(); // Calculate our own view of which nodes should be alive or dead. Use a simple mark array for this. // Once the algorithm is complete a true value at a given index in the array indicates a node that // should still be alive, otherwise the node should have been collected. // Initialize the mark array. Set true for nodes we still have a strong reference to from the array // (these should definitely not have been collected yet). Set false for the other nodes (we assume // they must have been collected until we prove otherwise). for (int i = 0; i < m_count; i++) m_marks[i] = m_nodes[i] != null; // Perform multiple passes over the handles we allocated (or our recorded version of the handles at // least). If we find a handle with a marked (live) primary where the secondary is not yet marked then // go ahead and mark that secondary (dependent handles are defined to do this: primaries act as if // they have a strong reference to the secondary up until the point they are collected). Repeat this // until we manage a scan over the entire table without marking any additional nodes as live. At this // point the marks array should reflect which objects are still live. while (true) { // Assume we're not going any further nodes to mark as live. bool marked = false; // Look at each handle in turn. for (int i = 0; i < m_handleCount; i++) if (m_marks[m_handles[i].m_primary]) { // Primary is live. if (!m_marks[m_handles[i].m_secondary]) { // Secondary wasn't marked as live yet. Do so and remember that we marked at least // node as live this pass (so we need to loop again since this secondary could be the // same as a primary earlier in the table). m_marks[m_handles[i].m_secondary] = true; marked = true; } } // Terminate the loop if we scanned the entire table without marking any additional nodes as live // (since additional scans can't make any difference). if (!marked) break; } // Validate our view of node liveness (m_marks) correspond to reality (m_nodes and m_collected). for (int i = 0; i < m_count; i++) { // Catch nodes which still have strong references but have collected anyway. This is stricly a // subset of the next test but it would be a very interesting bug to call out. if (m_nodes[i] != null && m_collected[i]) Error(String.Format("Node {0} was collected while it still had a strong root", i)); // Catch nodes which we compute as alive but have been collected. if (m_marks[i] && m_collected[i]) Error(String.Format("Node {0} was collected while it was still reachable", i)); // Catch nodes which we compute as dead but haven't been collected. if (!m_marks[i] && !m_collected[i]) Error(String.Format("Node {0} wasn't collected even though it was unreachable", i)); } } // Method called by nodes when they're finalized (i.e. the node has been collected). public void Collected(int id) { // Catch nodes which are collected twice. if (m_collected[id]) Error(String.Format("Node {0} collected twice", id)); m_collected[id] = true; } // Structure used to record the primary and secondary nodes in every dependent handle we allocated. Nodes // are identified by ID (their index into the node array). struct HandleSpec { public int m_primary; public int m_secondary; public void Set(int primary, int secondary) { m_primary = primary; m_secondary = secondary; } } int m_count; // Count of nodes in array TableStyle m_style; // Style of handle creation Node[] m_nodes; // Array of nodes bool[] m_collected; // Array indicating which nodes have been collected bool[] m_marks; // Array indicating which nodes should be live ConditionalWeakTable<Node, Node> m_table; // Table that creates and holds our dependent handles int m_handleCount; // Number of handles we create HandleSpec[] m_handles; // Array of descriptions of each handle Random m_rng; // Random number generator } // The type of object we reference from our dependent handles. Doesn't do much except report its own garbage // collection to the owning TestSet. class Node { // Allocate a node and remember our owner (TestSet) and ID (index into node array). public Node(TestSet owner, int id) { m_owner = owner; m_id = id; } // On finalization report our collection to the owner TestSet. ~Node() { m_owner.Collected(m_id); } TestSet m_owner; // TestSet which created us int m_id; // Our index into above TestSet's node array } // The test class itself. class DhTest1 { // Entry point. public static int Main() { // The actual test runs are controlled from RunTest. True is returned if all succeeded, false // otherwise. if (new DhTest1().RunTest()) { Console.WriteLine("Test PASS"); return 100; } else { Console.WriteLine("Test FAIL"); return 999; } } // Run a series of tests with different table and collection styles. bool RunTest() { // Number of nodes we'll allocate in each run (we could take this as an argument instead). int numNodes = 10000; // Run everything under an exception handler since test errors are reported as exceptions. try { // Run a pass with each table style. For each style run through the collection styles in the order // None, Alternate, Random and All. This sequence is carefully selected to remove progressively // more nodes from the array (since, within a given TestSet instance, once a node has actually // been collected it won't be resurrected for future runs). TestSet ts1 = new TestSet(TableStyle.Unconnected, numNodes); ts1.Run(CollectStyle.None); ts1.Run(CollectStyle.Alternate); ts1.Run(CollectStyle.Random); ts1.Run(CollectStyle.All); TestSet ts2 = new TestSet(TableStyle.ForwardLinked, numNodes); ts2.Run(CollectStyle.None); ts2.Run(CollectStyle.Alternate); ts2.Run(CollectStyle.Random); ts2.Run(CollectStyle.All); TestSet ts3 = new TestSet(TableStyle.BackwardLinked, numNodes); ts3.Run(CollectStyle.None); ts3.Run(CollectStyle.Alternate); ts3.Run(CollectStyle.Random); ts3.Run(CollectStyle.All); TestSet ts4 = new TestSet(TableStyle.Random, numNodes); ts4.Run(CollectStyle.None); ts4.Run(CollectStyle.Alternate); ts4.Run(CollectStyle.Random); ts4.Run(CollectStyle.All); } catch (TestException te) { // "Expected" errors. Console.WriteLine("TestError: {0}", te.Message); return false; } catch (Exception e) { // Totally unexpected errors (probably shouldn't see these unless there's a test bug). Console.WriteLine("Unexpected exception: {0}", e.GetType().Name); return false; } // If we get as far as here the test succeeded. return true; } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace System.Tests { public class TypeTestsNetcore { private static readonly IList<Type> NonArrayBaseTypes; static TypeTestsNetcore() { NonArrayBaseTypes = new List<Type>() { typeof(int), typeof(void), typeof(int*), typeof(Outside), typeof(Outside<int>), typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0], new object().GetType().GetType() }; if (PlatformDetection.IsWindows) { NonArrayBaseTypes.Add(Type.GetTypeFromCLSID(default(Guid))); } } [Fact] public void IsSZArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_TrueForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.True(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForVariableBoundArrayTypes() { if (!PlatformDetection.IsNetNative) // Multidim arrays of rank 1 not supported on UapAot: https://github.com/dotnet/corert/issues/3331 { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.False(type.IsSZArray); } } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsSZArray); } [Fact] public void IsVariableBoundArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_TrueForVariableBoundArrayTypes() { if (!PlatformDetection.IsNetNative) // Multidim arrays of rank 1 not supported on UapAot: https://github.com/dotnet/corert/issues/3331 { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.True(type.IsVariableBoundArray); } } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.True(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsVariableBoundArray); } [Theory] [MemberData(nameof(DefinedTypes))] public void IsTypeDefinition_True(Type type) { Assert.True(type.IsTypeDefinition); } [Theory] [MemberData(nameof(NotDefinedTypes))] public void IsTypeDefinition_False(Type type) { Assert.False(type.IsTypeDefinition); } // In the unlikely event we ever add new values to the CorElementType enumeration, CoreCLR will probably miss it because of the way IsTypeDefinition // works. It's likely that such a type will live in the core assembly so to improve our chances of catching this situation, test IsTypeDefinition // on every type exposed out of that assembly. // // Skipping this on .Net Native because: // - We really don't want to opt in all the metadata in System.Private.CoreLib // - The .Net Native implementation of IsTypeDefinition is not the one that works by enumerating selected values off CorElementType. // It has much less need of a test like this. [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)] public void IsTypeDefinition_AllDefinedTypesInCoreAssembly() { foreach (Type type in typeof(object).Assembly.DefinedTypes) { Assert.True(type.IsTypeDefinition, "IsTypeDefinition expected to be true for type " + type); } } public static IEnumerable<object[]> DefinedTypes { get { yield return new object[] { typeof(void) }; yield return new object[] { typeof(int) }; yield return new object[] { typeof(Outside) }; yield return new object[] { typeof(Outside.Inside) }; yield return new object[] { typeof(Outside<>) }; yield return new object[] { typeof(IEnumerable<>) }; yield return new object[] { 3.GetType().GetType() }; // This yields a reflection-blocked type on .Net Native - which is implemented separately if (PlatformDetection.IsWindows) yield return new object[] { Type.GetTypeFromCLSID(default(Guid)) }; } } public static IEnumerable<object[]> NotDefinedTypes { get { Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { typeof(int[]) }; yield return new object[] { theT.MakeArrayType(1) }; // Using an open type as element type gets around .Net Native nonsupport of rank-1 multidim arrays yield return new object[] { typeof(int[,]) }; yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(int).MakePointerType() }; yield return new object[] { typeof(Outside<int>) }; yield return new object[] { typeof(Outside<int>.Inside<int>) }; yield return new object[] { theT }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExpressionTreeRewriter : ExprVisitorBase { public static EXPR Rewrite(EXPR expr, ExprFactory expressionFactory, SymbolLoader symbolLoader) { ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader); rewriter.alwaysRewrite = true; return rewriter.Visit(expr); } private ExprFactory expressionFactory; private SymbolLoader symbolLoader; private EXPRBOUNDLAMBDA currentAnonMeth; private bool alwaysRewrite; private ExprFactory GetExprFactory() { return expressionFactory; } private SymbolLoader GetSymbolLoader() { return symbolLoader; } private ExpressionTreeRewriter(ExprFactory expressionFactory, SymbolLoader symbolLoader) { this.expressionFactory = expressionFactory; this.symbolLoader = symbolLoader; this.alwaysRewrite = false; } protected override EXPR Dispatch(EXPR expr) { Debug.Assert(expr != null); EXPR result = base.Dispatch(expr); if (result == expr) { throw Error.InternalCompilerError(); } return result; } ///////////////////////////////////////////////////////////////////////////////// // Statement types. protected override EXPR VisitASSIGNMENT(EXPRASSIGNMENT assignment) { Debug.Assert(assignment != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); // For assignments, we either have a member assignment or an indexed assignment. //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL()); EXPR lhs; if (assignment.GetLHS().isPROP()) { EXPRPROP prop = assignment.GetLHS().asPROP(); if (prop.GetOptionalArguments() == null) { // Regular property. lhs = Visit(prop); } else { // Indexed assignment. Here we need to find the instance of the object, create the // PropInfo for the thing, and get the array of expressions that make up the index arguments. // // The LHS becomes Expression.Property(instance, indexerInfo, arguments). EXPR instance = Visit(prop.GetMemberGroup().GetOptionalObject()); EXPR propInfo = GetExprFactory().CreatePropertyInfo(prop.pwtSlot.Prop(), prop.pwtSlot.Ats); EXPR arguments = GenerateParamsArray( GenerateArgsList(prop.GetOptionalArguments()), PredefinedType.PT_EXPRESSION); lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments); } } else { lhs = Visit(assignment.GetLHS()); } EXPR rhs = Visit(assignment.GetRHS()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } protected override EXPR VisitMULTIGET(EXPRMULTIGET pExpr) { return Visit(pExpr.GetOptionalMulti().Left); } protected override EXPR VisitMULTI(EXPRMULTI pExpr) { EXPR rhs = Visit(pExpr.Operator); EXPR lhs = Visit(pExpr.Left); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } ///////////////////////////////////////////////////////////////////////////////// // Expression types. protected override EXPR VisitBOUNDLAMBDA(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); EXPRBOUNDLAMBDA prevAnonMeth = currentAnonMeth; currentAnonMeth = anonmeth; MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA); CType delegateType = anonmeth.DelegateType(); TypeArray lambdaTypeParams = GetSymbolLoader().getBSymmgr().AllocParams(1, new CType[] { delegateType }); AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams); EXPR createParameters = CreateWraps(anonmeth); EXPR body = RewriteLambdaBody(anonmeth); EXPR parameters = RewriteLambdaParameters(anonmeth); EXPR args = GetExprFactory().CreateList(body, parameters); CType typeRet = GetSymbolLoader().GetTypeManager().SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPR callLambda = GetExprFactory().CreateCall(0, typeRet, args, pMemGroup, mwi); callLambda.asCALL().PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA; currentAnonMeth = prevAnonMeth; if (createParameters != null) { callLambda = GetExprFactory().CreateSequence(createParameters, callLambda); } EXPR expr = DestroyWraps(anonmeth, callLambda); // If we are already inside an expression tree rewrite and this is an expression tree lambda // then it needs to be quoted. if (currentAnonMeth != null) { expr = GenerateCall(PREDEFMETH.PM_EXPRESSION_QUOTE, expr); } return expr; } protected override EXPR VisitCONSTANT(ExprConstant expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateConstant(expr); } protected override EXPR VisitLOCAL(EXPRLOCAL local) { Debug.Assert(local != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(!local.local.isThis); // this is true for all parameters of an expression lambda if (local.local.wrap != null) { return local.local.wrap; } Debug.Assert(local.local.fUsedInAnonMeth); return GetExprFactory().CreateHoistedLocalInExpression(local); } protected override EXPR VisitTHISPOINTER(EXPRTHISPOINTER expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(expr.local.isThis); return GenerateConstant(expr); } protected override EXPR VisitFIELD(EXPRFIELD expr) { Debug.Assert(expr != null); EXPR pObject; if (expr.GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.GetOptionalObject()); } EXPRFIELDINFO pFieldInfo = GetExprFactory().CreateFieldInfo(expr.fwt.Field(), expr.fwt.GetType()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo); } protected override EXPR VisitUSERDEFINEDCONVERSION(EXPRUSERDEFINEDCONVERSION expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateUserDefinedConversion(expr, expr.Argument); } protected override EXPR VisitCAST(EXPRCAST pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR pArgument = pExpr.GetArgument(); // If we have generated an identity cast or reference cast to a base class // we can omit the cast. if (pArgument.type == pExpr.type || GetSymbolLoader().IsBaseClassOfClass(pArgument.type, pExpr.type) || CConversions.FImpRefConv(GetSymbolLoader(), pArgument.type, pExpr.type)) { return Visit(pArgument); } // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree. if (pExpr.type != null && pExpr.type.isPredefType(PredefinedType.PT_G_EXPRESSION) && pArgument.isBOUNDLAMBDA()) { return Visit(pArgument); } EXPR result = GenerateConversion(pArgument, pExpr.type, pExpr.isChecked()); if ((pExpr.flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter. result.flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } return result; } protected override EXPR VisitCONCAT(EXPRCONCAT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; if (expr.GetFirstArgument().type.isPredefType(PredefinedType.PT_STRING) && expr.GetSecondArgument().type.isPredefType(PredefinedType.PT_STRING)) { pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2; } else { pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2; } EXPR p1 = Visit(expr.GetFirstArgument()); EXPR p2 = Visit(expr.GetSecondArgument()); MethodSymbol method = GetPreDefMethod(pdm); EXPR methodInfo = GetExprFactory().CreateMethodInfo(method, GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING), null); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo); } protected override EXPR VisitBINOP(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); if (expr.GetUserDefinedCallMethod() != null) { return GenerateUserDefinedBinaryOperator(expr); } else { return GenerateBuiltInBinaryOperator(expr); } } protected override EXPR VisitUNARYOP(EXPRUNARYOP pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); if (pExpr.UserDefinedCallMethod != null) { return GenerateUserDefinedUnaryOperator(pExpr); } else { return GenerateBuiltInUnaryOperator(pExpr); } } protected override EXPR VisitARRAYINDEX(EXPRARRAYINDEX pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR arr = Visit(pExpr.GetArray()); EXPR args = GenerateIndexList(pExpr.GetIndex()); if (args.isLIST()) { EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args); } protected override EXPR VisitARRAYLENGTH(EXPRARRAYLENGTH pExpr) { return GenerateBuiltInUnaryOperator(PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, pExpr.GetArray(), pExpr); } protected override EXPR VisitQUESTIONMARK(EXPRQUESTIONMARK pExpr) { Debug.Assert(pExpr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR p1 = Visit(pExpr.GetTestExpression()); EXPR p2 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalLeftChild()); EXPR p3 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalRightChild()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONDITION, p1, p2, p3); } protected override EXPR VisitCALL(EXPRCALL expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); switch (expr.nubLiftKind) { default: break; case NullableCallLiftKind.NullableIntermediateConversion: case NullableCallLiftKind.NullableConversion: case NullableCallLiftKind.NullableConversionConstructor: return GenerateConversion(expr.GetOptionalArguments(), expr.type, expr.isChecked()); case NullableCallLiftKind.NotLiftedIntermediateConversion: case NullableCallLiftKind.UserDefinedConversion: return GenerateUserDefinedConversion(expr.GetOptionalArguments(), expr.type, expr.mwi); } if (expr.mwi.Meth().IsConstructor()) { return GenerateConstructor(expr); } EXPRMEMGRP memberGroup = expr.GetMemberGroup(); if (memberGroup.isDelegate()) { return GenerateDelegateInvoke(expr); } EXPR pObject; if (expr.mwi.Meth().isStatic || expr.GetMemberGroup().GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = expr.GetMemberGroup().GetOptionalObject(); // If we have, say, an int? which is the object of a call to ToString // then we do NOT want to generate ((object)i).ToString() because that // will convert a null-valued int? to a null object. Rather what we want // to do is box it to a ValueType and call ValueType.ToString. // // To implement this we say that if the object of the call is an implicit boxing cast // then just generate the object, not the cast. If the cast is explicit in the // source code then it will be an EXPLICITCAST and we will visit it normally. // // It might be better to rewrite the expression tree API so that it // can handle in the general case all implicit boxing conversions. Right now it // requires that all arguments to a call that need to be boxed be explicitly boxed. if (pObject != null && pObject.isCAST() && pObject.asCAST().IsBoxingCast()) { pObject = pObject.asCAST().GetArgument(); } pObject = Visit(pObject); } EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.mwi); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL; Debug.Assert(!expr.mwi.Meth().isVirtual || expr.GetMemberGroup().GetOptionalObject() != null); return GenerateCall(pdm, pObject, methodInfo, Params); } protected override EXPR VisitPROP(EXPRPROP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); EXPR pObject; if (expr.pwtSlot.Prop().isStatic || expr.GetMemberGroup().GetOptionalObject() == null) { pObject = GetExprFactory().CreateNull(); } else { pObject = Visit(expr.GetMemberGroup().GetOptionalObject()); } EXPR propInfo = GetExprFactory().CreatePropertyInfo(expr.pwtSlot.Prop(), expr.pwtSlot.GetType()); if (expr.GetOptionalArguments() != null) { // It is an indexer property. Turn it into a virtual method call. EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo); } protected override EXPR VisitARRINIT(EXPRARRINIT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); // POSSIBLE ERROR: Multi-d should be an error? EXPR pTypeOf = CreateTypeOf(expr.type.AsArrayType().GetElementType()); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params); } protected override EXPR VisitZEROINIT(EXPRZEROINIT expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); Debug.Assert(expr.OptionalArgument == null); if (expr.IsConstructor) { // We have a parameterless "new MyStruct()" which has been realized as a zero init. EXPRTYPEOF pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_TYPE, pTypeOf); } return GenerateConstant(expr); } protected override EXPR VisitTYPEOF(EXPRTYPEOF expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); return GenerateConstant(expr); } private EXPR GenerateQuestionMarkOperand(EXPR pExpr) { Debug.Assert(pExpr != null); // We must not optimize away compiler-generated reference casts because // the expression tree API insists that the CType of both sides be identical. if (pExpr.isCAST()) { return GenerateConversion(pExpr.asCAST().GetArgument(), pExpr.type, pExpr.isChecked()); } return Visit(pExpr); } private EXPR GenerateDelegateInvoke(EXPRCALL expr) { Debug.Assert(expr != null); EXPRMEMGRP memberGroup = expr.GetMemberGroup(); Debug.Assert(memberGroup.isDelegate()); EXPR oldObject = memberGroup.GetOptionalObject(); Debug.Assert(oldObject != null); EXPR pObject = Visit(oldObject); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params); } private EXPR GenerateBuiltInBinaryOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break; case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break; case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break; case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR; break; case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND; break; case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break; case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break; case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break; case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break; case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break; case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break; case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break; case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break; case ExpressionKind.EK_MUL: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY; break; case ExpressionKind.EK_SUB: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT; break; case ExpressionKind.EK_ADD: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD; break; default: throw Error.InternalCompilerError(); } EXPR origL = expr.GetOptionalLeftChild(); EXPR origR = expr.GetOptionalRightChild(); Debug.Assert(origL != null); Debug.Assert(origR != null); CType typeL = origL.type; CType typeR = origR.type; EXPR newL = Visit(origL); EXPR newR = Visit(origR); bool didEnumConversion = false; CType convertL = null; CType convertR = null; if (typeL.isEnumType()) { // We have already inserted casts if not lifted, so we should never see an enum. Debug.Assert(expr.isLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.underlyingEnumType()); typeL = convertL; didEnumConversion = true; } else if (typeL.IsNullableType() && typeL.StripNubs().isEnumType()) { Debug.Assert(expr.isLifted); convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.StripNubs().underlyingEnumType()); typeL = convertL; didEnumConversion = true; } if (typeR.isEnumType()) { Debug.Assert(expr.isLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.underlyingEnumType()); typeR = convertR; didEnumConversion = true; } else if (typeR.IsNullableType() && typeR.StripNubs().isEnumType()) { Debug.Assert(expr.isLifted); convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.StripNubs().underlyingEnumType()); typeR = convertR; didEnumConversion = true; } if (typeL.IsNullableType() && typeL.StripNubs() == typeR) { convertR = typeL; } if (typeR.IsNullableType() && typeR.StripNubs() == typeL) { convertL = typeR; } if (convertL != null) { newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL)); } if (convertR != null) { newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR)); } EXPR call = GenerateCall(pdm, newL, newR); if (didEnumConversion && expr.type.StripNubs().isEnumType()) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.type)); } return call; } private EXPR GenerateBuiltInUnaryOperator(EXPRUNARYOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_UPLUS: return Visit(expr.Child); case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.EK_NEG: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE; break; default: throw Error.InternalCompilerError(); } EXPR origOp = expr.Child; return GenerateBuiltInUnaryOperator(pdm, origOp, expr); } private EXPR GenerateBuiltInUnaryOperator(PREDEFMETH pdm, EXPR pOriginalOperator, EXPR pOperator) { EXPR op = Visit(pOriginalOperator); if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType()) { Debug.Assert(pOperator.kind == ExpressionKind.EK_BITNOT); // The only built-in unary operator defined on nullable enum. CType underlyingType = pOriginalOperator.type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); op = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, op, CreateTypeOf(nullableType)); } EXPR call = GenerateCall(pdm, op); if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType()) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(pOperator.type)); } return call; } private EXPR GenerateUserDefinedBinaryOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break; case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break; case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break; case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break; case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break; case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break; case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break; case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break; case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break; case ExpressionKind.EK_STRINGEQ: case ExpressionKind.EK_STRINGNE: case ExpressionKind.EK_DELEGATEEQ: case ExpressionKind.EK_DELEGATENE: case ExpressionKind.EK_EQ: case ExpressionKind.EK_NE: case ExpressionKind.EK_GE: case ExpressionKind.EK_GT: case ExpressionKind.EK_LE: case ExpressionKind.EK_LT: return GenerateUserDefinedComparisonOperator(expr); case ExpressionKind.EK_DELEGATESUB: case ExpressionKind.EK_SUB: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED; break; case ExpressionKind.EK_DELEGATEADD: case ExpressionKind.EK_ADD: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED; break; case ExpressionKind.EK_MUL: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } EXPR p1 = expr.GetOptionalLeftChild(); EXPR p2 = expr.GetOptionalRightChild(); EXPR udcall = expr.GetOptionalUserDefinedCall(); if (udcall != null) { Debug.Assert(udcall.kind == ExpressionKind.EK_CALL || udcall.kind == ExpressionKind.EK_USERLOGOP); if (udcall.kind == ExpressionKind.EK_CALL) { EXPRLIST args = udcall.asCALL().GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement(); p2 = args.GetOptionalNextListNode(); } else { EXPRLIST args = udcall.asUSERLOGOP().OperatorCall.GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement().asWRAP().GetOptionalExpression(); p2 = args.GetOptionalNextListNode(); } } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod()); EXPR call = GenerateCall(pdm, p1, p2, methodInfo); // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate, // not the operand delegate CType. We must cast to the delegate CType. if (expr.kind == ExpressionKind.EK_DELEGATESUB || expr.kind == ExpressionKind.EK_DELEGATEADD) { EXPR pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } return call; } private EXPR GenerateUserDefinedUnaryOperator(EXPRUNARYOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; EXPR arg = expr.Child; EXPRCALL call = expr.OptionalUserDefinedCall.asCALL(); if (call != null) { // Use the actual argument of the call; it may contain user-defined // conversions or be a bound lambda, and that will not be in the original // argument stashed away in the left child of the operator. arg = call.GetOptionalArguments(); } Debug.Assert(arg != null && arg.kind != ExpressionKind.EK_LIST); switch (expr.kind) { case ExpressionKind.EK_TRUE: case ExpressionKind.EK_FALSE: return Visit(call); case ExpressionKind.EK_UPLUS: pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED; break; case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.EK_DECIMALNEG: case ExpressionKind.EK_NEG: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED; break; case ExpressionKind.EK_INC: case ExpressionKind.EK_DEC: case ExpressionKind.EK_DECIMALINC: case ExpressionKind.EK_DECIMALDEC: pdm = PREDEFMETH.PM_EXPRESSION_CALL; break; default: throw Error.InternalCompilerError(); } EXPR op = Visit(arg); EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod); if (expr.kind == ExpressionKind.EK_INC || expr.kind == ExpressionKind.EK_DEC || expr.kind == ExpressionKind.EK_DECIMALINC || expr.kind == ExpressionKind.EK_DECIMALDEC) { return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION)); } return GenerateCall(pdm, op, methodInfo); } private EXPR GenerateUserDefinedComparisonOperator(EXPRBINOP expr) { Debug.Assert(expr != null); Debug.Assert(alwaysRewrite || currentAnonMeth != null); PREDEFMETH pdm; switch (expr.kind) { case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_DELEGATEEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_DELEGATENE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break; case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } EXPR p1 = expr.GetOptionalLeftChild(); EXPR p2 = expr.GetOptionalRightChild(); if (expr.GetOptionalUserDefinedCall() != null) { EXPRCALL udcall = expr.GetOptionalUserDefinedCall().asCALL(); EXPRLIST args = udcall.GetOptionalArguments().asLIST(); Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST); p1 = args.GetOptionalElement(); p2 = args.GetOptionalNextListNode(); } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); EXPR lift = GetExprFactory().CreateBoolConstant(false); // We never lift to null in C#. EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod()); return GenerateCall(pdm, p1, p2, lift, methodInfo); } private EXPR RewriteLambdaBody(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); Debug.Assert(anonmeth.OptionalBody != null); Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements() != null); // There ought to be no way to get an empty statement block successfully converted into an expression tree. Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements().GetOptionalNextStatement() == null); EXPRBLOCK body = anonmeth.OptionalBody; // The most likely case: if (body.GetOptionalStatements().isRETURN()) { Debug.Assert(body.GetOptionalStatements().asRETURN().GetOptionalObject() != null); return Visit(body.GetOptionalStatements().asRETURN().GetOptionalObject()); } // This can only if it is a void delegate and this is a void expression, such as a call to a void method // or something like Expression<Action<Foo>> e = (Foo f) => f.MyEvent += MyDelegate; throw Error.InternalCompilerError(); } private EXPR RewriteLambdaParameters(EXPRBOUNDLAMBDA anonmeth) { Debug.Assert(anonmeth != null); // new ParameterExpression[2] {Parameter(typeof(type1), name1), Parameter(typeof(type2), name2)} EXPR paramArrayInitializerArgs = null; EXPR paramArrayInitializerArgsTail = paramArrayInitializerArgs; for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } GetExprFactory().AppendItemToList(local.wrap, ref paramArrayInitializerArgs, ref paramArrayInitializerArgsTail); } return GenerateParamsArray(paramArrayInitializerArgs, PredefinedType.PT_PARAMETEREXPRESSION); } private EXPR GenerateConversion(EXPR arg, CType CType, bool bChecked) { return GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked()); } private EXPR GenerateConversionWithSource(EXPR pTarget, CType pType, bool bChecked) { PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; EXPR pTypeOf = CreateTypeOf(pType); return GenerateCall(pdm, pTarget, pTypeOf); } private EXPR GenerateValueAccessConversion(EXPR pArgument) { Debug.Assert(pArgument != null); CType pStrippedTypeOfArgument = pArgument.type.StripNubs(); EXPR pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr); } private EXPR GenerateUserDefinedConversion(EXPR arg, CType type, MethWithInst method) { EXPR target = Visit(arg); return GenerateUserDefinedConversion(arg, type, target, method); } private EXPR GenerateUserDefinedConversion(EXPR arg, CType CType, EXPR target, MethWithInst method) { // The user-defined explicit conversion from enum? to decimal or decimal? requires // that we convert the enum? to its nullable underlying CType. if (isEnumToDecimalConversion(arg.type, CType)) { // Special case: If we have enum? to decimal? then we need to emit // a conversion from enum? to its nullable underlying CType first. // This is unfortunate; we ought to reorganize how conversions are // represented in the EXPR tree so that this is more transparent. // converting an enum to its underlying CType never fails, so no need to check it. CType underlyingType = arg.type.StripNubs().underlyingEnumType(); CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType); EXPR typeofNubEnum = CreateTypeOf(nullableType); target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum); } // If the methodinfo does not return the target CType AND this is not a lifted conversion // from one value CType to another, then we need to wrap the whole thing in another conversion, // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S)) CType pMethodReturnType = GetSymbolLoader().GetTypeManager().SubstType(method.Meth().RetType, method.GetType(), method.TypeArgs); bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.type) && IsNullableValueType(CType))); EXPR typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType); EXPR methodInfo = GetExprFactory().CreateMethodInfo(method); PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED; EXPR callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo); if (fDontLiftReturnType) { return callUserDefinedConversion; } PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; EXPR typeofOuter = CreateTypeOf(CType); return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter); } private EXPR GenerateUserDefinedConversion(EXPRUSERDEFINEDCONVERSION pExpr, EXPR pArgument) { EXPR pCastCall = pExpr.UserDefinedCall; EXPR pCastArgument = pExpr.Argument; EXPR pConversionSource = null; if (!isEnumToDecimalConversion(pArgument.type, pExpr.type) && IsNullableValueAccess(pCastArgument, pArgument)) { // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it. pConversionSource = GenerateValueAccessConversion(pArgument); } else if (pCastCall.isCALL() && pCastCall.asCALL().pConversions != null) { EXPR pUDConversion = pCastCall.asCALL().pConversions; if (pUDConversion.isCALL()) { EXPR pUDConversionArgument = pUDConversion.asCALL().GetOptionalArguments(); if (IsNullableValueAccess(pUDConversionArgument, pArgument)) { pConversionSource = GenerateValueAccessConversion(pArgument); } else { pConversionSource = Visit(pUDConversionArgument); } return GenerateConversionWithSource(pConversionSource, pCastCall.type, pCastCall.asCALL().isChecked()); } else { // This can happen if we have a UD conversion from C to, say, int, // and we have an explicit cast to decimal?. The conversion should // then be bound as two chained user-defined conversions. Debug.Assert(pUDConversion.isUSERDEFINEDCONVERSION()); // Just recurse. return GenerateUserDefinedConversion(pUDConversion.asUSERDEFINEDCONVERSION(), pArgument); } } else { pConversionSource = Visit(pCastArgument); } return GenerateUserDefinedConversion(pCastArgument, pExpr.type, pConversionSource, pExpr.UserDefinedCallMethod); } private EXPR GenerateParameter(string name, CType CType) { GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING); // force an ensure state ExprConstant nameString = GetExprFactory().CreateStringConstant(name); EXPRTYPEOF pTypeOf = CreateTypeOf(CType); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString); } private MethodSymbol GetPreDefMethod(PREDEFMETH pdm) { return GetSymbolLoader().getPredefinedMembers().GetMethod(pdm); } private EXPRTYPEOF CreateTypeOf(CType CType) { return GetExprFactory().CreateTypeOf(CType); } private EXPR CreateWraps(EXPRBOUNDLAMBDA anonmeth) { EXPR sequence = null; for (Symbol sym = anonmeth.ArgumentScope().firstChild; sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } Debug.Assert(anonmeth.OptionalBody != null); EXPR create = GenerateParameter(local.name.Text, local.GetType()); local.wrap = GetExprFactory().CreateWrapNoAutoFree(anonmeth.OptionalBody.OptionalScopeSymbol, create); EXPR save = GetExprFactory().CreateSave(local.wrap); if (sequence == null) { sequence = save; } else { sequence = GetExprFactory().CreateSequence(sequence, save); } } return sequence; } private EXPR DestroyWraps(EXPRBOUNDLAMBDA anonmeth, EXPR sequence) { for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild) { if (!sym.IsLocalVariableSymbol()) { continue; } LocalVariableSymbol local = sym.AsLocalVariableSymbol(); if (local.isThis) { continue; } Debug.Assert(local.wrap != null); Debug.Assert(anonmeth.OptionalBody != null); EXPR freeWrap = GetExprFactory().CreateWrap(anonmeth.OptionalBody.OptionalScopeSymbol, local.wrap); sequence = GetExprFactory().CreateReverseSequence(sequence, freeWrap); } return sequence; } private EXPR GenerateConstructor(EXPRCALL expr) { Debug.Assert(expr != null); Debug.Assert(expr.mwi.Meth().IsConstructor()); // Realize a call to new DELEGATE(obj, FUNCPTR) as though it actually was // (DELEGATE)CreateDelegate(typeof(DELEGATE), obj, GetMethInfoFromHandle(FUNCPTR)) if (IsDelegateConstructorCall(expr)) { return GenerateDelegateConstructor(expr); } EXPR constructorInfo = GetExprFactory().CreateMethodInfo(expr.mwi); EXPR args = GenerateArgsList(expr.GetOptionalArguments()); EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); if (expr.type.IsAggregateType() && expr.type.AsAggregateType().getAggregate().IsAnonymousType()) { EXPR members = GenerateMembersArray(expr.type.AsAggregateType(), PredefinedType.PT_METHODINFO); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, constructorInfo, Params, members); } else { return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params); } } private EXPR GenerateDelegateConstructor(EXPRCALL expr) { // In: // // new DELEGATE(obj, &FUNC) // // Out: // // Cast( // Call( // null, // (MethodInfo)GetMethodFromHandle(&CreateDelegate), // new Expression[3]{ // Constant(typeof(DELEGATE)), // transformed-object, // Constant((MethodInfo)GetMethodFromHandle(&FUNC)}), // typeof(DELEGATE)) // Debug.Assert(expr != null); Debug.Assert(expr.mwi.Meth().IsConstructor()); Debug.Assert(expr.type.isDelegateType()); Debug.Assert(expr.GetOptionalArguments() != null); Debug.Assert(expr.GetOptionalArguments().isLIST()); EXPRLIST origArgs = expr.GetOptionalArguments().asLIST(); EXPR target = origArgs.GetOptionalElement(); Debug.Assert(origArgs.GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR); EXPRFUNCPTR funcptr = origArgs.GetOptionalNextListNode().asFUNCPTR(); MethodSymbol createDelegateMethod = GetPreDefMethod(PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT); AggregateType delegateType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_DELEGATE, true); MethWithInst mwi = new MethWithInst(createDelegateMethod, delegateType); EXPR instance = GenerateConstant(GetExprFactory().CreateMethodInfo(funcptr.mwi)); EXPR methinfo = GetExprFactory().CreateMethodInfo(mwi); EXPR param1 = GenerateConstant(CreateTypeOf(expr.type)); EXPR param2 = Visit(target); EXPR paramsList = GetExprFactory().CreateList(param1, param2); EXPR Params = GenerateParamsArray(paramsList, PredefinedType.PT_EXPRESSION); EXPR call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CALL, instance, methinfo, Params); EXPR pTypeOf = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } private EXPR GenerateArgsList(EXPR oldArgs) { EXPR newArgs = null; EXPR newArgsTail = newArgs; for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext()) { EXPR oldArg = it.Current(); GetExprFactory().AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail); } return newArgs; } private EXPR GenerateIndexList(EXPR oldIndices) { CType intType = symbolLoader.GetReqPredefType(PredefinedType.PT_INT, true); EXPR newIndices = null; EXPR newIndicesTail = newIndices; for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext()) { EXPR newIndex = it.Current(); if (newIndex.type != intType) { EXPRCLASS exprType = expressionFactory.CreateClass(intType, null, null); newIndex = expressionFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, exprType, newIndex); newIndex.flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } EXPR rewrittenIndex = Visit(newIndex); expressionFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail); } return newIndices; } private EXPR GenerateConstant(EXPR expr) { EXPRFLAG flags = 0; AggregateType pObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true); if (expr.type.IsNullType()) { EXPRTYPEOF pTypeOf = CreateTypeOf(pObject); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf); } AggregateType stringType = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING, true); if (expr.type != stringType) { flags = EXPRFLAG.EXF_BOX; } EXPRCLASS objectType = GetExprFactory().MakeClass(pObject); EXPRCAST cast = GetExprFactory().CreateCast(flags, objectType, expr); EXPRTYPEOF pTypeOf2 = CreateTypeOf(expr.type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2); } private EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1) { MethodSymbol method = GetPreDefMethod(pdm); // this should be enforced in an earlier pass and the transform pass should not // be handling this error if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3, EXPR arg4) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true); EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3, arg4); MethWithInst mwi = new MethWithInst(method, expressionType); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private EXPRARRINIT GenerateParamsArray(EXPR args, PredefinedType pt) { int parameterCount = ExpressionIterator.Count(args); AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true); ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1); ExprConstant paramsArrayArg = GetExprFactory().CreateIntegerConstant(parameterCount); EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, args, paramsArrayArg, null); arrayInit.dimSize = parameterCount; arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory? return arrayInit; } private EXPRARRINIT GenerateMembersArray(AggregateType anonymousType, PredefinedType pt) { EXPR newArgs = null; EXPR newArgsTail = newArgs; int methodCount = 0; AggregateSymbol aggSym = anonymousType.getAggregate(); for (Symbol member = aggSym.firstChild; member != null; member = member.nextChild) { if (member.IsMethodSymbol()) { MethodSymbol method = member.AsMethodSymbol(); if (method.MethKind() == MethodKindEnum.PropAccessor) { EXPRMETHODINFO methodInfo = GetExprFactory().CreateMethodInfo(method, anonymousType, method.Params); GetExprFactory().AppendItemToList(methodInfo, ref newArgs, ref newArgsTail); methodCount++; } } } AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true); ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1); ExprConstant paramsArrayArg = GetExprFactory().CreateIntegerConstant(methodCount); EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, newArgs, paramsArrayArg, null); arrayInit.dimSize = methodCount; arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory? return arrayInit; } private void FixLiftedUserDefinedBinaryOperators(EXPRBINOP expr, ref EXPR pp1, ref EXPR pp2) { // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then // we need to ensure that the unlifted actual arguments are promoted to their nullable CType. Debug.Assert(expr != null); Debug.Assert(pp1 != null); Debug.Assert(pp1 != null); Debug.Assert(pp2 != null); Debug.Assert(pp2 != null); MethodSymbol method = expr.GetUserDefinedCallMethod().Meth(); EXPR orig1 = expr.GetOptionalLeftChild(); EXPR orig2 = expr.GetOptionalRightChild(); Debug.Assert(orig1 != null && orig2 != null); EXPR new1 = pp1; EXPR new2 = pp2; CType fptype1 = method.Params[0]; CType fptype2 = method.Params[1]; CType aatype1 = orig1.type; CType aatype2 = orig2.type; // Is the operator even a candidate for lifting? if (fptype1.IsNullableType() || fptype2.IsNullableType() || !fptype1.IsAggregateType() || !fptype2.IsAggregateType() || !fptype1.AsAggregateType().getAggregate().IsValueType() || !fptype2.AsAggregateType().getAggregate().IsValueType()) { return; } CType nubfptype1 = GetSymbolLoader().GetTypeManager().GetNullable(fptype1); CType nubfptype2 = GetSymbolLoader().GetTypeManager().GetNullable(fptype2); // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1? if (aatype1.IsNullType() || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2.IsNullType())) { new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1)); } // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2? if (aatype2.IsNullType() || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1.IsNullType())) { new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2)); } pp1 = new1; pp2 = new2; } private bool IsNullableValueType(CType pType) { if (pType.IsNullableType()) { CType pStrippedType = pType.StripNubs(); return pStrippedType.IsAggregateType() && pStrippedType.AsAggregateType().getAggregate().IsValueType(); } return false; } private bool IsNullableValueAccess(EXPR pExpr, EXPR pObject) { Debug.Assert(pExpr != null); return pExpr.isPROP() && (pExpr.asPROP().GetMemberGroup().GetOptionalObject() == pObject) && pObject.type.IsNullableType(); } private bool IsDelegateConstructorCall(EXPR pExpr) { Debug.Assert(pExpr != null); if (!pExpr.isCALL()) { return false; } EXPRCALL pCall = pExpr.asCALL(); return pCall.mwi.Meth() != null && pCall.mwi.Meth().IsConstructor() && pCall.type.isDelegateType() && pCall.GetOptionalArguments() != null && pCall.GetOptionalArguments().isLIST() && pCall.GetOptionalArguments().asLIST().GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR; } private static bool isEnumToDecimalConversion(CType argtype, CType desttype) { CType strippedArgType = argtype.IsNullableType() ? argtype.StripNubs() : argtype; CType strippedDestType = desttype.IsNullableType() ? desttype.StripNubs() : desttype; return strippedArgType.isEnumType() && strippedDestType.isPredefType(PredefinedType.PT_DECIMAL); } } }
using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Synergy.Contracts.Test.Failures { [TestFixture] public class FailCastableTest { #region object.AsOrFail<T>() [Test] public void AsOrFail() { // ARRANGE var someObjectButSurelyNotString = new object(); // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => someObjectButSurelyNotString.AsOrFail<string>() ); // ASSERT Assert.That(exception.Message, Is.EqualTo("Expected object of type 'System.String' but was 'System.Object'")); } [Test] public void AsOrFailSuccess() { // ARRANGE object somethingCastable = "text"; // ACT somethingCastable.AsOrFail<string>(); } [Test] public void AsOrFailSuccessWithNull() { // ARRANGE object somethingCastable = null; // ACT // ReSharper disable once ExpressionIsAlwaysNull somethingCastable.AsOrFail<string>(); } #endregion #region object.CastOrFail<T>() [Test] public void CastOrFail() { // ARRANGE // ReSharper disable once HeapView.BoxingAllocation object somethingNotCastable = 1; // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => somethingNotCastable.CastOrFail<string>() ); // ASSERT Assert.That(exception.Message, Is.EqualTo("Expected object of type 'System.String' but was '1'")); } [Test] public void CastOrFailWithNull() { // ARRANGE object somethingNotCastable = null; // ACT var exception = Assert.Throws<DesignByContractViolationException>( // ReSharper disable once ExpressionIsAlwaysNull () => somethingNotCastable.CastOrFail<string>() ); // ASSERT Assert.That(exception.Message, Is.EqualTo("Expected object of type 'System.String' but was 'null'")); } [Test] public void CastOrFailSuccess() { // ARRANGE var somethingCastable = "text"; // ACT somethingCastable.CastOrFail<string>(); } #endregion #region Fail.IfNotCastable<T>() [Test] public void IfNotCastable() { // ARRANGE var somethingNotCastable = new object(); // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => Fail.IfNotCastable<IQueryable>(somethingNotCastable, "wrong type") ); // ASSERT Assert.That(exception.Message, Is.EqualTo("wrong type")); } [Test] public void IfNotCastableWithNull() { Fail.IfNotCastable<IList<string>>(null, "wrong type"); } [Test] public void IfNotCastableSuccess() { Fail.IfNotCastable<IList<string>>(new List<string>(), "wrong type"); } #endregion #region Fail.IfNotCastable() [Test] public void WeaklyTypedIfNotCastable() { // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => Fail.IfNotCastable(new object(), typeof(IQueryable), "wrong type") ); // ASSERT Assert.That(exception.Message, Is.EqualTo("wrong type")); } [Test] public void WeaklyTypedIfNotCastableWithNull() { Fail.IfNotCastable(null, typeof(IList<string>), "wrong type"); } [Test] public void WeaklyTypedIfNotCastableSuccess() { Fail.IfNotCastable(new List<string>(), typeof(IList<string>), "wrong type"); } #endregion #region Fail.IfNullOrNotCastable<T>() [Test] public void IfNullOrNotCastable() { // ARRANGE object somethingNotCastable = new object(); // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => Fail.IfNullOrNotCastable<IQueryable>(somethingNotCastable) ); // ASSERT Assert.That(exception.Message, Is.EqualTo("Expected object of type 'System.Linq.IQueryable' but was 'System.Object'")); } [Test] public void IfNullOrNotCastableWithMessage() { // ARRANGE object somethingNotCastable = new object(); // ACT var exception = Assert.Throws<DesignByContractViolationException>( () => Fail.IfNullOrNotCastable<IQueryable>(somethingNotCastable, "wrong type") ); // ASSERT Assert.That(exception.Message, Is.EqualTo("wrong type")); } [Test] public void IfNullOrNotCastableWithNull() { // ARRANGE object somethingNotCastable = null; // ACT var exception = Assert.Throws<DesignByContractViolationException>( // ReSharper disable once ExpressionIsAlwaysNull () => Fail.IfNullOrNotCastable<IQueryable>(somethingNotCastable) ); // ASSERT Assert.That(exception.Message, Is.EqualTo("Expected object of type 'System.Linq.IQueryable' but was '<null>'")); } [Test] public void IfNullOrNotCastableSuccess() { Fail.IfNullOrNotCastable<IList<string>>(new List<string>()); } [Test] public void IfNullOrNotCastableSuccessWithMessage() { Fail.IfNullOrNotCastable<IList<string>>(new List<string>(), "wrong type"); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Agent.Sdk.Knob; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(JobRunner))] public interface IJobRunner : IAgentService { Task<TaskResult> RunAsync(Pipelines.AgentJobRequestMessage message, CancellationToken jobRequestCancellationToken); void UpdateMetadata(JobMetadataMessage message); } public sealed class JobRunner : AgentService, IJobRunner { private IJobServerQueue _jobServerQueue; private ITempDirectoryManager _tempDirectoryManager; public async Task<TaskResult> RunAsync(Pipelines.AgentJobRequestMessage message, CancellationToken jobRequestCancellationToken) { // Validate parameters. Trace.Entering(); ArgUtil.NotNull(message, nameof(message)); ArgUtil.NotNull(message.Resources, nameof(message.Resources)); ArgUtil.NotNull(message.Variables, nameof(message.Variables)); ArgUtil.NotNull(message.Steps, nameof(message.Steps)); Trace.Info("Job ID {0}", message.JobId); DateTime jobStartTimeUtc = DateTime.UtcNow; ServiceEndpoint systemConnection = message.Resources.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); // System.AccessToken if (message.Variables.ContainsKey(Constants.Variables.System.EnableAccessToken) && StringUtil.ConvertToBoolean(message.Variables[Constants.Variables.System.EnableAccessToken].Value)) { message.Variables[Constants.Variables.System.AccessToken] = new VariableValue(systemConnection.Authorization.Parameters["AccessToken"], false); } // back compat TfsServerUrl message.Variables[Constants.Variables.System.TFServerUrl] = systemConnection.Url.AbsoluteUri; // Make sure SystemConnection Url and Endpoint Url match Config Url base for OnPremises server // System.ServerType will always be there after M133 if (!message.Variables.ContainsKey(Constants.Variables.System.ServerType) || string.Equals(message.Variables[Constants.Variables.System.ServerType]?.Value, "OnPremises", StringComparison.OrdinalIgnoreCase)) { ReplaceConfigUriBaseInJobRequestMessage(message); } // Setup the job server and job server queue. var jobServer = HostContext.GetService<IJobServer>(); VssCredentials jobServerCredential = VssUtil.GetVssCredential(systemConnection); Uri jobServerUrl = systemConnection.Url; Trace.Info($"Creating job server with URL: {jobServerUrl}"); // jobServerQueue is the throttling reporter. _jobServerQueue = HostContext.GetService<IJobServerQueue>(); VssConnection jobConnection = VssUtil.CreateConnection(jobServerUrl, jobServerCredential, new DelegatingHandler[] { new ThrottlingReportHandler(_jobServerQueue) }); await jobServer.ConnectAsync(jobConnection); _jobServerQueue.Start(message); HostContext.WritePerfCounter($"WorkerJobServerQueueStarted_{message.RequestId.ToString()}"); IExecutionContext jobContext = null; CancellationTokenRegistration? agentShutdownRegistration = null; try { // Create the job execution context. jobContext = HostContext.CreateService<IExecutionContext>(); jobContext.InitializeJob(message, jobRequestCancellationToken); Trace.Info("Starting the job execution context."); jobContext.Start(); jobContext.Section(StringUtil.Loc("StepStarting", message.JobDisplayName)); agentShutdownRegistration = HostContext.AgentShutdownToken.Register(() => { // log an issue, then agent get shutdown by Ctrl-C or Ctrl-Break. // the server will use Ctrl-Break to tells the agent that operating system is shutting down. string errorMessage; switch (HostContext.AgentShutdownReason) { case ShutdownReason.UserCancelled: errorMessage = StringUtil.Loc("UserShutdownAgent"); break; case ShutdownReason.OperatingSystemShutdown: errorMessage = StringUtil.Loc("OperatingSystemShutdown", Environment.MachineName); break; default: throw new ArgumentException(HostContext.AgentShutdownReason.ToString(), nameof(HostContext.AgentShutdownReason)); } jobContext.AddIssue(new Issue() { Type = IssueType.Error, Message = errorMessage }); }); // Validate directory permissions. string workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work); Trace.Info($"Validating directory permissions for: '{workDirectory}'"); try { Directory.CreateDirectory(workDirectory); IOUtil.ValidateExecutePermission(workDirectory); } catch (Exception ex) { Trace.Error(ex); jobContext.Error(ex); return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed); } // Set agent variables. AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings(); jobContext.SetVariable(Constants.Variables.Agent.Id, settings.AgentId.ToString(CultureInfo.InvariantCulture)); jobContext.SetVariable(Constants.Variables.Agent.HomeDirectory, HostContext.GetDirectory(WellKnownDirectory.Root), isFilePath: true); jobContext.SetVariable(Constants.Variables.Agent.JobName, message.JobDisplayName); jobContext.SetVariable(Constants.Variables.Agent.MachineName, Environment.MachineName); jobContext.SetVariable(Constants.Variables.Agent.Name, settings.AgentName); jobContext.SetVariable(Constants.Variables.Agent.OS, VarUtil.OS); jobContext.SetVariable(Constants.Variables.Agent.OSArchitecture, VarUtil.OSArchitecture); jobContext.SetVariable(Constants.Variables.Agent.RootDirectory, HostContext.GetDirectory(WellKnownDirectory.Work), isFilePath: true); if (PlatformUtil.RunningOnWindows) { jobContext.SetVariable(Constants.Variables.Agent.ServerOMDirectory, HostContext.GetDirectory(WellKnownDirectory.ServerOM), isFilePath: true); } if (!PlatformUtil.RunningOnWindows) { jobContext.SetVariable(Constants.Variables.Agent.AcceptTeeEula, settings.AcceptTeeEula.ToString()); } jobContext.SetVariable(Constants.Variables.Agent.WorkFolder, HostContext.GetDirectory(WellKnownDirectory.Work), isFilePath: true); jobContext.SetVariable(Constants.Variables.System.WorkFolder, HostContext.GetDirectory(WellKnownDirectory.Work), isFilePath: true); string toolsDirectory = HostContext.GetDirectory(WellKnownDirectory.Tools); Directory.CreateDirectory(toolsDirectory); jobContext.SetVariable(Constants.Variables.Agent.ToolsDirectory, toolsDirectory, isFilePath: true); if (AgentKnobs.DisableGitPrompt.GetValue(jobContext).AsBoolean()) { jobContext.SetVariable("GIT_TERMINAL_PROMPT", "0"); } // Setup TEMP directories _tempDirectoryManager = HostContext.GetService<ITempDirectoryManager>(); _tempDirectoryManager.InitializeTempDirectory(jobContext); // todo: task server can throw. try/catch and fail job gracefully. // prefer task definitions url, then TFS collection url, then TFS account url var taskServer = HostContext.GetService<ITaskServer>(); Uri taskServerUri = null; if (!string.IsNullOrEmpty(jobContext.Variables.System_TaskDefinitionsUri)) { taskServerUri = new Uri(jobContext.Variables.System_TaskDefinitionsUri); } else if (!string.IsNullOrEmpty(jobContext.Variables.System_TFCollectionUrl)) { taskServerUri = new Uri(jobContext.Variables.System_TFCollectionUrl); } var taskServerCredential = VssUtil.GetVssCredential(systemConnection); if (taskServerUri != null) { Trace.Info($"Creating task server with {taskServerUri}"); await taskServer.ConnectAsync(VssUtil.CreateConnection(taskServerUri, taskServerCredential)); } // for back compat TFS 2015 RTM/QU1, we may need to switch the task server url to agent config url if (!string.Equals(message?.Variables.GetValueOrDefault(Constants.Variables.System.ServerType)?.Value, "Hosted", StringComparison.OrdinalIgnoreCase)) { if (taskServerUri == null || !await taskServer.TaskDefinitionEndpointExist()) { Trace.Info($"Can't determine task download url from JobMessage or the endpoint doesn't exist."); var configStore = HostContext.GetService<IConfigurationStore>(); taskServerUri = new Uri(configStore.GetSettings().ServerUrl); Trace.Info($"Recreate task server with configuration server url: {taskServerUri}"); await taskServer.ConnectAsync(VssUtil.CreateConnection(taskServerUri, taskServerCredential)); } } // Expand the endpoint data values. foreach (ServiceEndpoint endpoint in jobContext.Endpoints) { jobContext.Variables.ExpandValues(target: endpoint.Data); VarUtil.ExpandEnvironmentVariables(HostContext, target: endpoint.Data); } // Expand the repository property values. foreach (var repository in jobContext.Repositories) { // expand checkout option var checkoutOptions = repository.Properties.Get<JToken>(Pipelines.RepositoryPropertyNames.CheckoutOptions); if (checkoutOptions != null) { checkoutOptions = jobContext.Variables.ExpandValues(target: checkoutOptions); checkoutOptions = VarUtil.ExpandEnvironmentVariables(HostContext, target: checkoutOptions); repository.Properties.Set<JToken>(Pipelines.RepositoryPropertyNames.CheckoutOptions, checkoutOptions); ; } // expand workspace mapping var mappings = repository.Properties.Get<JToken>(Pipelines.RepositoryPropertyNames.Mappings); if (mappings != null) { mappings = jobContext.Variables.ExpandValues(target: mappings); mappings = VarUtil.ExpandEnvironmentVariables(HostContext, target: mappings); repository.Properties.Set<JToken>(Pipelines.RepositoryPropertyNames.Mappings, mappings); } } // Expand container properties foreach (var container in jobContext.Containers) { this.ExpandProperties(container, jobContext.Variables); } foreach (var sidecar in jobContext.SidecarContainers) { this.ExpandProperties(sidecar, jobContext.Variables); } // Get the job extension. Trace.Info("Getting job extension."); var hostType = jobContext.Variables.System_HostType; var extensionManager = HostContext.GetService<IExtensionManager>(); // We should always have one job extension IJobExtension jobExtension = (extensionManager.GetExtensions<IJobExtension>() ?? new List<IJobExtension>()) .Where(x => x.HostType.HasFlag(hostType)) .FirstOrDefault(); ArgUtil.NotNull(jobExtension, nameof(jobExtension)); List<IStep> jobSteps = null; try { Trace.Info("Initialize job. Getting all job steps."); jobSteps = await jobExtension.InitializeJob(jobContext, message); } catch (OperationCanceledException ex) when (jobContext.CancellationToken.IsCancellationRequested) { // set the job to canceled // don't log error issue to job ExecutionContext, since server owns the job level issue Trace.Error($"Job is canceled during initialize."); Trace.Error($"Caught exception: {ex}"); return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Canceled); } catch (Exception ex) { // set the job to failed. // don't log error issue to job ExecutionContext, since server owns the job level issue Trace.Error($"Job initialize failed."); Trace.Error($"Caught exception from {nameof(jobExtension.InitializeJob)}: {ex}"); return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed); } // trace out all steps Trace.Info($"Total job steps: {jobSteps.Count}."); Trace.Verbose($"Job steps: '{string.Join(", ", jobSteps.Select(x => x.DisplayName))}'"); HostContext.WritePerfCounter($"WorkerJobInitialized_{message?.RequestId.ToString()}"); // Run all job steps Trace.Info("Run all job steps."); var stepsRunner = HostContext.GetService<IStepsRunner>(); try { await stepsRunner.RunAsync(jobContext, jobSteps); } catch (Exception ex) { // StepRunner should never throw exception out. // End up here mean there is a bug in StepRunner // Log the error and fail the job. Trace.Error($"Caught exception from job steps {nameof(StepsRunner)}: {ex}"); jobContext.Error(ex); return await CompleteJobAsync(jobServer, jobContext, message, TaskResult.Failed); } finally { Trace.Info("Finalize job."); await jobExtension.FinalizeJob(jobContext); } Trace.Info($"Job result after all job steps finish: {jobContext.Result ?? TaskResult.Succeeded}"); if (jobContext.Variables.GetBoolean(Constants.Variables.Agent.Diagnostic) ?? false) { Trace.Info("Support log upload starting."); IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>(); try { await diagnosticLogManager.UploadDiagnosticLogsAsync(executionContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc); Trace.Info("Support log upload complete."); } catch (Exception ex) { // Log the error but make sure we continue gracefully. Trace.Info("Error uploading support logs."); Trace.Error(ex); } } Trace.Info("Completing the job execution context."); return await CompleteJobAsync(jobServer, jobContext, message); } finally { if (agentShutdownRegistration != null) { agentShutdownRegistration.Value.Dispose(); agentShutdownRegistration = null; } await ShutdownQueue(throwOnFailure: false); } } public void UpdateMetadata(JobMetadataMessage message) { if (message.PostLinesFrequencyMillis.HasValue) { _jobServerQueue.UpdateWebConsoleLineRate(message.PostLinesFrequencyMillis.Value); } } public void ExpandProperties(ContainerInfo container, Variables variables) { if (container == null || variables == null) { return; } // Expand port mapping variables.ExpandValues(container.UserPortMappings); // Expand volume mounts variables.ExpandValues(container.UserMountVolumes); foreach (var volume in container.UserMountVolumes.Values) { // After mount volume variables are expanded, they are final container.MountVolumes.Add(new MountVolume(volume)); } // Expand env vars variables.ExpandValues(container.ContainerEnvironmentVariables); // Expand image and options strings container.ContainerImage = variables.ExpandValue(nameof(container.ContainerImage), container.ContainerImage); container.ContainerCreateOptions = variables.ExpandValue(nameof(container.ContainerCreateOptions), container.ContainerCreateOptions); } private async Task<TaskResult> CompleteJobAsync(IJobServer jobServer, IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, TaskResult? taskResult = null) { ArgUtil.NotNull(message, nameof(message)); jobContext.Section(StringUtil.Loc("StepFinishing", message.JobDisplayName)); TaskResult result = jobContext.Complete(taskResult); try { await ShutdownQueue(throwOnFailure: true); } catch (Exception ex) { Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}"); Trace.Error("This indicate a failure during publish output variables. Fail the job to prevent unexpected job outputs."); Trace.Error(ex); result = TaskResultUtil.MergeTaskResults(result, TaskResult.Failed); } // Clean TEMP after finish process jobserverqueue, since there might be a pending fileupload still use the TEMP dir. _tempDirectoryManager?.CleanupTempDirectory(); if (!jobContext.Features.HasFlag(PlanFeatures.JobCompletedPlanEvent)) { Trace.Info($"Skip raise job completed event call from worker because Plan version is {message.Plan.Version}"); return result; } Trace.Info("Raising job completed event."); var jobCompletedEvent = new JobCompletedEvent(message.RequestId, message.JobId, result, jobContext.Variables.Get(Constants.Variables.Agent.RunMode) == Constants.Agent.CommandLine.Flags.Once); var completeJobRetryLimit = 5; var exceptions = new List<Exception>(); while (completeJobRetryLimit-- > 0) { try { await jobServer.RaisePlanEventAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, jobCompletedEvent, default(CancellationToken)); return result; } catch (TaskOrchestrationPlanNotFoundException ex) { Trace.Error($"TaskOrchestrationPlanNotFoundException received, while attempting to raise JobCompletedEvent for job {message.JobId}."); Trace.Error(ex); return TaskResult.Failed; } catch (TaskOrchestrationPlanSecurityException ex) { Trace.Error($"TaskOrchestrationPlanSecurityException received, while attempting to raise JobCompletedEvent for job {message.JobId}."); Trace.Error(ex); return TaskResult.Failed; } catch (Exception ex) { Trace.Error($"Catch exception while attempting to raise JobCompletedEvent for job {message.JobId}, job request {message.RequestId}."); Trace.Error(ex); exceptions.Add(ex); } // delay 5 seconds before next retry. await Task.Delay(TimeSpan.FromSeconds(5)); } // rethrow exceptions from all attempts. throw new AggregateException(exceptions); } private async Task ShutdownQueue(bool throwOnFailure) { if (_jobServerQueue != null) { try { Trace.Info("Shutting down the job server queue."); await _jobServerQueue.ShutdownAsync(); } catch (Exception ex) when (!throwOnFailure) { Trace.Error($"Caught exception from {nameof(JobServerQueue)}.{nameof(_jobServerQueue.ShutdownAsync)}"); Trace.Error(ex); } finally { _jobServerQueue = null; // Prevent multiple attempts. } } } // the scheme://hostname:port (how the agent knows the server) is external to our server // in other words, an agent may have it's own way (DNS, hostname) of refering // to the server. it owns that. That's the scheme://hostname:port we will use. // Example: Server's notification url is http://tfsserver:8080/tfs // Agent config url is https://tfsserver.mycompany.com:9090/tfs private Uri ReplaceWithConfigUriBase(Uri messageUri) { AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings(); try { Uri result = null; Uri configUri = new Uri(settings.ServerUrl); if (Uri.TryCreate(new Uri(configUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)), messageUri.PathAndQuery, out result)) { //replace the schema and host portion of messageUri with the host from the //server URI (which was set at config time) return result; } } catch (InvalidOperationException ex) { //cannot parse the Uri - not a fatal error Trace.Error(ex); } catch (UriFormatException ex) { //cannot parse the Uri - not a fatal error Trace.Error(ex); } return messageUri; } private void ReplaceConfigUriBaseInJobRequestMessage(Pipelines.AgentJobRequestMessage message) { ServiceEndpoint systemConnection = message.Resources.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); Uri systemConnectionUrl = systemConnection.Url; // fixup any endpoint Url that match SystemConnection Url. foreach (var endpoint in message.Resources.Endpoints) { if (Uri.Compare(endpoint.Url, systemConnectionUrl, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0) { endpoint.Url = ReplaceWithConfigUriBase(endpoint.Url); Trace.Info($"Ensure endpoint url match config url base. {endpoint.Url}"); } } // fixup any repository Url that match SystemConnection Url. foreach (var repo in message.Resources.Repositories) { if (Uri.Compare(repo.Url, systemConnectionUrl, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0) { repo.Url = ReplaceWithConfigUriBase(repo.Url); Trace.Info($"Ensure repository url match config url base. {repo.Url}"); } } // fixup well known variables. (taskDefinitionsUrl, tfsServerUrl, tfsCollectionUrl) if (message.Variables.ContainsKey(WellKnownDistributedTaskVariables.TaskDefinitionsUrl)) { string taskDefinitionsUrl = message.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl].Value; message.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl] = ReplaceWithConfigUriBase(new Uri(taskDefinitionsUrl)).AbsoluteUri; Trace.Info($"Ensure System.TaskDefinitionsUrl match config url base. {message.Variables[WellKnownDistributedTaskVariables.TaskDefinitionsUrl].Value}"); } if (message.Variables.ContainsKey(WellKnownDistributedTaskVariables.TFCollectionUrl)) { string tfsCollectionUrl = message.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl].Value; message.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl] = ReplaceWithConfigUriBase(new Uri(tfsCollectionUrl)).AbsoluteUri; Trace.Info($"Ensure System.TFCollectionUrl match config url base. {message.Variables[WellKnownDistributedTaskVariables.TFCollectionUrl].Value}"); } if (message.Variables.ContainsKey(Constants.Variables.System.TFServerUrl)) { string tfsServerUrl = message.Variables[Constants.Variables.System.TFServerUrl].Value; message.Variables[Constants.Variables.System.TFServerUrl] = ReplaceWithConfigUriBase(new Uri(tfsServerUrl)).AbsoluteUri; Trace.Info($"Ensure System.TFServerUrl match config url base. {message.Variables[Constants.Variables.System.TFServerUrl].Value}"); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using VotingInfo.Database.Contracts; using System.Runtime.Serialization; using VotingInfo.Database.Contracts.Client; using VotingInfo.Database.Logic.Client; namespace VotingInfo.WebSite.Services.Client { /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// public abstract partial class CandidatesServiceBase : ServiceBase { public virtual bool Exists(string authId, string fldCandidateId) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_Exists) ? CandidatesLogic.ExistsNow((int)Convert.ChangeType(fldCandidateId,typeof(int))) : false; //cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.Exists ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SearchPx", Namespace = "SearchPx")] public class SearchPx { [DataMember] public string CandidateName; [DataMember] public string SourceUrl; } public virtual List<CandidatesContract> Search(string authId, SearchPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_Search) ? CandidatesLogic.SearchNow(px.CandidateName, px.SourceUrl) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.Search ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } public virtual List<CandidatesContract> SelectAll(string authId) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectAll) ? CandidatesLogic.SelectAllNow() : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectAll ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SelectBy_CandidateIdPx", Namespace = "SelectBy_CandidateIdPx")] public class SelectBy_CandidateIdPx { [DataMember] public int CandidateId; } public virtual List<CandidatesContract> SelectBy_CandidateId(string authId, SelectBy_CandidateIdPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_CandidateId) ? CandidatesLogic.SelectBy_CandidateIdNow(px.CandidateId) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_CandidateId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SelectBy_ContentInspectionIdPx", Namespace = "SelectBy_ContentInspectionIdPx")] public class SelectBy_ContentInspectionIdPx { [DataMember] public int ContentInspectionId; } public virtual List<CandidatesContract> SelectBy_ContentInspectionId(string authId, SelectBy_ContentInspectionIdPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_ContentInspectionId) ? CandidatesLogic.SelectBy_ContentInspectionIdNow(px.ContentInspectionId) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_ContentInspectionId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SelectBy_OrganizationIdPx", Namespace = "SelectBy_OrganizationIdPx")] public class SelectBy_OrganizationIdPx { [DataMember] public int OrganizationId; } public virtual List<CandidatesContract> SelectBy_OrganizationId(string authId, SelectBy_OrganizationIdPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_OrganizationId) ? CandidatesLogic.SelectBy_OrganizationIdNow(px.OrganizationId) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_OrganizationId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SelectBy_ProposedByUserIdPx", Namespace = "SelectBy_ProposedByUserIdPx")] public class SelectBy_ProposedByUserIdPx { [DataMember] public int ProposedByUserId; } public virtual List<CandidatesContract> SelectBy_ProposedByUserId(string authId, SelectBy_ProposedByUserIdPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_ProposedByUserId) ? CandidatesLogic.SelectBy_ProposedByUserIdNow(px.ProposedByUserId) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_ProposedByUserId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } [DataContract(Name = "SelectBy_ConfirmedByUserIdPx", Namespace = "SelectBy_ConfirmedByUserIdPx")] public class SelectBy_ConfirmedByUserIdPx { [DataMember] public int ConfirmedByUserId; } public virtual List<CandidatesContract> SelectBy_ConfirmedByUserId(string authId, SelectBy_ConfirmedByUserIdPx px) { try { return Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_ConfirmedByUserId) ? CandidatesLogic.SelectBy_ConfirmedByUserIdNow(px.ConfirmedByUserId) : null;//cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_ConfirmedByUserId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } public virtual CandidatesContract Get(string authId, string fldCandidateId) { try { if(Can(authId, (int)PermissionEnum.Client_Candidates_SelectBy_CandidateId)) { var results = CandidatesLogic.SelectBy_CandidateIdNow((int)Convert.ChangeType(fldCandidateId,typeof(int))); return results.Count == 0 ? null : results[0]; } return null; //cant } catch(Exception ex) { #if DEBUG Debug.WriteLine("------------------------------"); Debug.WriteLine("------ CandidatesServiceBase.SelectBy_CandidateId ERROR ------"); Debug.WriteLine("------------------------------"); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Debug.WriteLine("------------------------------"); #endif throw; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Diagnostics; using System.DirectoryServices.Interop; using System.ComponentModel; using System.Threading; using System.Reflection; using System.DirectoryServices.Design; using System.Globalization; using System.Net; namespace System.DirectoryServices { /// <devdoc> /// Encapsulates a node or an object in the Active Directory hierarchy. /// </devdoc> [ TypeConverterAttribute(typeof(DirectoryEntryConverter)) ] public class DirectoryEntry : Component { private string _path = ""; private UnsafeNativeMethods.IAds _adsObject; private bool _useCache = true; private bool _cacheFilled; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool propertiesAlreadyEnumerated = false; #pragma warning restore 0414 private bool _disposed = false; private AuthenticationTypes _authenticationType = AuthenticationTypes.Secure; private NetworkCredential _credentials; private readonly DirectoryEntryConfiguration _options; private PropertyCollection _propertyCollection = null; internal bool allowMultipleChange = false; private bool _userNameIsNull = false; private bool _passwordIsNull = false; private bool _objectSecurityInitialized = false; private bool _objectSecurityModified = false; private ActiveDirectorySecurity _objectSecurity = null; private const string SecurityDescriptorProperty = "ntSecurityDescriptor"; /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/>class. /// </devdoc> public DirectoryEntry() { _options = new DirectoryEntryConfiguration(this); } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind /// to the directory entry at <paramref name="path"/>. /// </devdoc> public DirectoryEntry(string path) : this() { Path = path; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class. /// </devdoc> public DirectoryEntry(string path, string username, string password) : this(path, username, password, AuthenticationTypes.Secure) { } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class. /// </devdoc> public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) : this(path) { _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; _authenticationType = authenticationType; } internal DirectoryEntry(string path, bool useCache, string username, string password, AuthenticationTypes authenticationType) { _path = path; _useCache = useCache; _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; _authenticationType = authenticationType; _options = new DirectoryEntryConfiguration(this); } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind /// to the native Active Directory object which is passed in. /// </devdoc> public DirectoryEntry(object adsObject) : this(adsObject, true, null, null, AuthenticationTypes.Secure, true) { } internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType) : this(adsObject, useCache, username, password, authenticationType, false) { } internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType, bool AdsObjIsExternal) { _adsObject = adsObject as UnsafeNativeMethods.IAds; if (_adsObject == null) throw new ArgumentException(SR.DSDoesNotImplementIADs); // GetInfo is not needed here. ADSI executes an implicit GetInfo when GetEx // is called on the PropertyValueCollection. 0x800704BC error might be returned // on some WinNT entries, when iterating through 'Users' group members. // if (forceBind) // this.adsObject.GetInfo(); _path = _adsObject.ADsPath; _useCache = useCache; _authenticationType = authenticationType; _credentials = new NetworkCredential(username, password); if (username == null) _userNameIsNull = true; if (password == null) _passwordIsNull = true; if (!useCache) CommitChanges(); _options = new DirectoryEntryConfiguration(this); // We are starting from an already bound connection so make sure the options are set properly. // If this is an externallly managed com object then we don't want to change it's current behavior if (!AdsObjIsExternal) { InitADsObjectOptions(); } } internal UnsafeNativeMethods.IAds AdsObject { get { Bind(); return _adsObject; } } [DefaultValue(AuthenticationTypes.Secure)] public AuthenticationTypes AuthenticationType { get => _authenticationType; set { if (_authenticationType == value) return; _authenticationType = value; Unbind(); } } private bool Bound => _adsObject != null; /// <devdoc> /// Gets a <see cref='System.DirectoryServices.DirectoryEntries'/> /// containing the child entries of this node in the Active /// Directory hierarchy. /// </devdoc> public DirectoryEntries Children => new DirectoryEntries(this); internal UnsafeNativeMethods.IAdsContainer ContainerObject { get { Bind(); return (UnsafeNativeMethods.IAdsContainer)_adsObject; } } /// <devdoc> /// Gets the globally unique identifier of the <see cref='System.DirectoryServices.DirectoryEntry'/>. /// </devdoc> public Guid Guid { get { string guid = NativeGuid; if (guid.Length == 32) { // oddly, the value comes back as a string with no dashes from LDAP byte[] intGuid = new byte[16]; for (int j = 0; j < 16; j++) { intGuid[j] = Convert.ToByte(new string(new char[] { guid[j * 2], guid[j * 2 + 1] }), 16); } return new Guid(intGuid); // return new Guid(guid.Substring(0, 8) + "-" + guid.Substring(8, 4) + "-" + guid.Substring(12, 4) + "-" + guid.Substring(16, 4) + "-" + guid.Substring(20)); } else return new Guid(guid); } } public ActiveDirectorySecurity ObjectSecurity { get { if (!_objectSecurityInitialized) { _objectSecurity = GetObjectSecurityFromCache(); _objectSecurityInitialized = true; } return _objectSecurity; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _objectSecurity = value; _objectSecurityInitialized = true; _objectSecurityModified = true; CommitIfNotCaching(); } } internal bool IsContainer { get { Bind(); return _adsObject is UnsafeNativeMethods.IAdsContainer; } } internal bool JustCreated { get; set; } /// <devdoc> /// Gets the relative name of the object as named with the underlying directory service. /// </devdoc> public string Name { get { Bind(); string tmpName = _adsObject.Name; GC.KeepAlive(this); return tmpName; } } public string NativeGuid { get { FillCache("GUID"); string tmpGuid = _adsObject.GUID; GC.KeepAlive(this); return tmpGuid; } } /// <devdoc> /// Gets the native Active Directory Services Interface (ADSI) object. /// </devdoc> public object NativeObject { get { Bind(); return _adsObject; } } /// <devdoc> /// Gets this entry's parent entry in the Active Directory hierarchy. /// </devdoc> public DirectoryEntry Parent { get { Bind(); return new DirectoryEntry(_adsObject.Parent, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } } /// <devdoc> /// Gets or sets the password to use when authenticating the client. /// </devdoc> [DefaultValue(null)] public string Password { set { if (value == GetPassword()) return; if (_credentials == null) { _credentials = new NetworkCredential(); // have not set it yet _userNameIsNull = true; } if (value == null) _passwordIsNull = true; else _passwordIsNull = false; _credentials.Password = value; Unbind(); } } /// <devdoc> /// Gets or sets the path for this <see cref='System.DirectoryServices.DirectoryEntry'/>. /// </devdoc> [ DefaultValue(""), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Path { get => _path; set { if (value == null) value = ""; if (System.DirectoryServices.ActiveDirectory.Utils.Compare(_path, value) == 0) return; _path = value; Unbind(); } } /// <devdoc> /// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object. /// </devdoc> public PropertyCollection Properties { get { if (_propertyCollection == null) { _propertyCollection = new PropertyCollection(this); } return _propertyCollection; } } /// <devdoc> /// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/> /// </devdoc> public string SchemaClassName { get { Bind(); string tmpClass = _adsObject.Class; GC.KeepAlive(this); return tmpClass; } } /// <devdoc> /// Gets the <see cref='System.DirectoryServices.DirectoryEntry'/> that holds schema information for this /// entry. An entry's <see cref='System.DirectoryServices.DirectoryEntry.SchemaClassName'/> /// determines what properties are valid for it. /// </devdoc> public DirectoryEntry SchemaEntry { get { Bind(); return new DirectoryEntry(_adsObject.Schema, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } } // By default changes to properties are done locally to // a cache and reading property values is cached after // the first read. Setting this to false will cause the // cache to be committed after each operation. // /// <devdoc> /// Gets a value indicating whether the cache should be committed after each /// operation. /// </devdoc> [DefaultValue(true)] public bool UsePropertyCache { get => _useCache; set { if (value == _useCache) return; // auto-commit when they set this to false. if (!value) CommitChanges(); _cacheFilled = false; // cache mode has been changed _useCache = value; } } /// <devdoc> /// Gets or sets the username to use when authenticating the client. /// </devdoc> [ DefaultValue(null), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Username { get { if (_credentials == null || _userNameIsNull) return null; return _credentials.UserName; } set { if (value == GetUsername()) return; if (_credentials == null) { _credentials = new NetworkCredential(); _passwordIsNull = true; } if (value == null) _userNameIsNull = true; else _userNameIsNull = false; _credentials.UserName = value; Unbind(); } } public DirectoryEntryConfiguration Options { get { // only LDAP provider supports IADsObjectOptions, so make the check here if (!(AdsObject is UnsafeNativeMethods.IAdsObjectOptions)) return null; return _options; } } internal void InitADsObjectOptions() { if (_adsObject is UnsafeNativeMethods.IAdsObjectOptions2) { //-------------------------------------------- // Check if ACCUMULATE_MODIFICATION is available //-------------------------------------------- object o = null; int unmanagedResult = 0; // check whether the new option is available // 8 is ADS_OPTION_ACCUMULATIVE_MODIFICATION unmanagedResult = ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).GetOption(8, out o); if (unmanagedResult != 0) { // rootdse does not support this option and invalid parameter due to without accumulative change fix in ADSI if ((unmanagedResult == unchecked((int)0x80004001)) || (unmanagedResult == unchecked((int)0x80005008))) { return; } else { throw COMExceptionHelper.CreateFormattedComException(unmanagedResult); } } // the new option is available, set it so we get the new PutEx behavior that will allow multiple changes Variant value = new Variant(); value.varType = 11; //VT_BOOL value.boolvalue = -1; ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).SetOption(8, value); allowMultipleChange = true; } } /// <devdoc> /// Binds to the ADs object (if not already bound). /// </devdoc> private void Bind() { Bind(true); } internal void Bind(bool throwIfFail) { //Cannot rebind after the object has been disposed, since finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); if (_adsObject == null) { string pathToUse = Path; if (pathToUse == null || pathToUse.Length == 0) { // get the default naming context. This should be the default root for the search. DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure); //SECREVIEW: Looking at the root of the DS will demand browse permissions // on "*" or "LDAP://RootDSE". string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0]; rootDSE.Dispose(); pathToUse = "LDAP://" + defaultNamingContext; } // Ensure we've got a thread model set, else CoInitialize() won't have been called. if (Thread.CurrentThread.GetApartmentState() == ApartmentState.Unknown) Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); Guid g = new Guid("00000000-0000-0000-c000-000000000046"); // IID_IUnknown object value = null; int hr = UnsafeNativeMethods.ADsOpenObject(pathToUse, GetUsername(), GetPassword(), (int)_authenticationType, ref g, out value); if (hr != 0) { if (throwIfFail) throw COMExceptionHelper.CreateFormattedComException(hr); } else { _adsObject = (UnsafeNativeMethods.IAds)value; } InitADsObjectOptions(); } } // Create new entry with the same data, but different IADs object, and grant it Browse Permission. internal DirectoryEntry CloneBrowsable() { DirectoryEntry newEntry = new DirectoryEntry(this.Path, this.UsePropertyCache, this.GetUsername(), this.GetPassword(), this.AuthenticationType); return newEntry; } /// <devdoc> /// Closes the <see cref='System.DirectoryServices.DirectoryEntry'/> /// and releases any system resources associated with this component. /// </devdoc> public void Close() { Unbind(); } /// <devdoc> /// Saves any changes to the entry in the directory store. /// </devdoc> public void CommitChanges() { if (JustCreated) { // Note: Permissions Demand is not necessary here, because entry has already been created with appr. permissions. // Write changes regardless of Caching mode to finish construction of a new entry. try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } JustCreated = false; _objectSecurityInitialized = false; _objectSecurityModified = false; // we need to refresh that properties table. _propertyCollection = null; return; } if (!_useCache) { // unless we have modified the existing security descriptor (in-place) through ObjectSecurity property // there is nothing to do if ((_objectSecurity == null) || (!_objectSecurity.IsModified())) { return; } } if (!Bound) return; try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); _objectSecurityInitialized = false; _objectSecurityModified = false; } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // we need to refresh that properties table. _propertyCollection = null; } internal void CommitIfNotCaching() { if (JustCreated) return; // Do not write changes, beacuse the entry is just under construction until CommitChanges() is called. if (_useCache) return; if (!Bound) return; try { // // Write the security descriptor to the cache // SetObjectSecurityInCache(); _adsObject.SetInfo(); _objectSecurityInitialized = false; _objectSecurityModified = false; } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // we need to refresh that properties table. _propertyCollection = null; } /// <devdoc> /// Creates a copy of this entry as a child of the given parent. /// </devdoc> public DirectoryEntry CopyTo(DirectoryEntry newParent) => CopyTo(newParent, null); /// <devdoc> /// Creates a copy of this entry as a child of the given parent and gives it a new name. /// </devdoc> public DirectoryEntry CopyTo(DirectoryEntry newParent, string newName) { if (!newParent.IsContainer) throw new InvalidOperationException(SR.Format(SR.DSNotAContainer, newParent.Path)); object copy = null; try { copy = newParent.ContainerObject.CopyHere(Path, newName); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } return new DirectoryEntry(copy, newParent.UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); } /// <devdoc> /// Deletes this entry and its entire subtree from the Active Directory hierarchy. /// </devdoc> public void DeleteTree() { if (!(AdsObject is UnsafeNativeMethods.IAdsDeleteOps)) throw new InvalidOperationException(SR.DSCannotDelete); UnsafeNativeMethods.IAdsDeleteOps entry = (UnsafeNativeMethods.IAdsDeleteOps)AdsObject; try { entry.DeleteObject(0); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } GC.KeepAlive(this); } protected override void Dispose(bool disposing) { // no managed object to free // free own state (unmanaged objects) if (!_disposed) { Unbind(); _disposed = true; } base.Dispose(disposing); } /// <devdoc> /// Searches the directory store at the given path to see whether an entry exists. /// </devdoc> public static bool Exists(string path) { DirectoryEntry entry = new DirectoryEntry(path); try { entry.Bind(true); // throws exceptions (possibly can break applications) return entry.Bound; } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode == unchecked((int)0x80072030) || e.ErrorCode == unchecked((int)0x80070003) || // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense) e.ErrorCode == unchecked((int)0x800708AC)) // Group name could not be found return false; throw; } finally { entry.Dispose(); } } /// <devdoc> /// If UsePropertyCache is true, calls GetInfo the first time it's necessary. /// If it's false, calls GetInfoEx on the given property name. /// </devdoc> internal void FillCache(string propertyName) { if (UsePropertyCache) { if (_cacheFilled) return; RefreshCache(); _cacheFilled = true; } else { Bind(); try { if (propertyName.Length > 0) _adsObject.GetInfoEx(new object[] { propertyName }, 0); else _adsObject.GetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } } } /// <devdoc> /// Calls a method on the native Active Directory. /// </devdoc> public object Invoke(string methodName, params object[] args) { object target = this.NativeObject; Type type = target.GetType(); object result = null; try { result = type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, target, args, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw; } if (result is UnsafeNativeMethods.IAds) return new DirectoryEntry(result, UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType); else return result; } /// <devdoc> /// Reads a property on the native Active Directory object. /// </devdoc> public object InvokeGet(string propertyName) { object target = this.NativeObject; Type type = target.GetType(); object result = null; try { result = type.InvokeMember(propertyName, BindingFlags.GetProperty, null, target, null, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw; } return result; } /// <devdoc> /// Sets a property on the native Active Directory object. /// </devdoc> public void InvokeSet(string propertyName, params object[] args) { object target = this.NativeObject; Type type = target.GetType(); try { type.InvokeMember(propertyName, BindingFlags.SetProperty, null, target, args, CultureInfo.InvariantCulture); GC.KeepAlive(this); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } catch (TargetInvocationException e) { if (e.InnerException != null) { if (e.InnerException is COMException) { COMException inner = (COMException)e.InnerException; throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } } throw; } } /// <devdoc> /// Moves this entry to the given parent. /// </devdoc> public void MoveTo(DirectoryEntry newParent) => MoveTo(newParent, null); /// <devdoc> /// Moves this entry to the given parent, and gives it a new name. /// </devdoc> public void MoveTo(DirectoryEntry newParent, string newName) { object newEntry = null; if (!(newParent.AdsObject is UnsafeNativeMethods.IAdsContainer)) throw new InvalidOperationException(SR.Format(SR.DSNotAContainer, newParent.Path)); try { if (AdsObject.ADsPath.StartsWith("WinNT:", StringComparison.Ordinal)) { // get the ADsPath instead of using Path as ADsPath for the case that "WinNT://computername" is passed in while we need "WinNT://domain/computer" string childPath = AdsObject.ADsPath; string parentPath = newParent.AdsObject.ADsPath; // we know ADsPath does not end with object type qualifier like ",computer" so it is fine to compare with whole newparent's adspath // for the case that child has different components from newparent in the aspects other than case, we don't do any processing, just let ADSI decide in case future adsi change if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length) == 0) { uint compareFlags = System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNORENONSPACE | System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREKANATYPE | System.DirectoryServices.ActiveDirectory.Utils.NORM_IGNOREWIDTH | System.DirectoryServices.ActiveDirectory.Utils.SORT_STRINGSORT; // work around the ADSI case sensitive if (System.DirectoryServices.ActiveDirectory.Utils.Compare(childPath, 0, parentPath.Length, parentPath, 0, parentPath.Length, compareFlags) != 0) { childPath = parentPath + childPath.Substring(parentPath.Length); } } newEntry = newParent.ContainerObject.MoveHere(childPath, newName); } else { newEntry = newParent.ContainerObject.MoveHere(Path, newName); } } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } if (Bound) System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); // release old handle _adsObject = (UnsafeNativeMethods.IAds)newEntry; _path = _adsObject.ADsPath; // Reset the options on the ADSI object since there were lost when the new object was created. InitADsObjectOptions(); if (!_useCache) CommitChanges(); else RefreshCache(); // in ADSI cache is lost after moving } /// <devdoc> /// Loads the property values for this directory entry into the property cache. /// </devdoc> public void RefreshCache() { Bind(); try { _adsObject.GetInfo(); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } _cacheFilled = true; // we need to refresh that properties table. _propertyCollection = null; // need to refresh the objectSecurity property _objectSecurityInitialized = false; _objectSecurityModified = false; } /// <devdoc> /// Loads the values of the specified properties into the property cache. /// </devdoc> public void RefreshCache(string[] propertyNames) { Bind(); //Consider there shouldn't be any marshaling issues //by just doing: AdsObject.GetInfoEx(object[]propertyNames, 0); object[] names = new object[propertyNames.Length]; for (int i = 0; i < propertyNames.Length; i++) names[i] = propertyNames[i]; try { AdsObject.GetInfoEx(names, 0); } catch (COMException e) { throw COMExceptionHelper.CreateFormattedComException(e); } // this is a half-lie, but oh well. Without it, this method is pointless. _cacheFilled = true; // we need to partially refresh that properties table. if (_propertyCollection != null && propertyNames != null) { for (int i = 0; i < propertyNames.Length; i++) { if (propertyNames[i] != null) { string name = propertyNames[i].ToLower(CultureInfo.InvariantCulture); _propertyCollection.valueTable.Remove(name); // also need to consider the range retrieval case string[] results = name.Split(new char[] { ';' }); if (results.Length != 1) { string rangeName = ""; for (int count = 0; count < results.Length; count++) { if (!results[count].StartsWith("range=", StringComparison.Ordinal)) { rangeName += results[count]; rangeName += ";"; } } // remove the last ';' character rangeName = rangeName.Remove(rangeName.Length - 1, 1); _propertyCollection.valueTable.Remove(rangeName); } // if this is "ntSecurityDescriptor" we should refresh the objectSecurity property if (string.Equals(propertyNames[i], SecurityDescriptorProperty, StringComparison.OrdinalIgnoreCase)) { _objectSecurityInitialized = false; _objectSecurityModified = false; } } } } } /// <devdoc> /// Changes the name of this entry. /// </devdoc> public void Rename(string newName) => MoveTo(Parent, newName); private void Unbind() { if (_adsObject != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(_adsObject); _adsObject = null; // we need to release that properties table. _propertyCollection = null; // need to refresh the objectSecurity property _objectSecurityInitialized = false; _objectSecurityModified = false; } internal string GetUsername() { if (_credentials == null || _userNameIsNull) return null; return _credentials.UserName; } internal string GetPassword() { if (_credentials == null || _passwordIsNull) return null; return _credentials.Password; } private ActiveDirectorySecurity GetObjectSecurityFromCache() { try { // // This property is the managed version of the "ntSecurityDescriptor" // attribute. In order to build an ActiveDirectorySecurity object from it // we need to get the binary form of the security descriptor. // If we use IADs::Get to get the IADsSecurityDescriptor interface and then // convert to raw form, there would be a performance overhead (because of // sid lookups and reverse lookups during conversion). // So to get the security descriptor in binary form, we use // IADsPropertyList::GetPropertyItem // // // GetPropertyItem does not implicitly fill the property cache // so we need to fill it explicitly (for an existing entry) // if (!JustCreated) { SecurityMasks securityMasksUsedInRetrieval; // // To ensure that we honor the security masks while retrieving // the security descriptor, we will retrieve the "ntSecurityDescriptor" each time // while initializing the ObjectSecurity property // securityMasksUsedInRetrieval = this.Options.SecurityMasks; RefreshCache(new string[] { SecurityDescriptorProperty }); // // Get the IAdsPropertyList interface // (Check that the IAdsPropertyList interface is supported) // if (!(NativeObject is UnsafeNativeMethods.IAdsPropertyList)) throw new NotSupportedException(SR.DSPropertyListUnsupported); UnsafeNativeMethods.IAdsPropertyList list = (UnsafeNativeMethods.IAdsPropertyList)NativeObject; UnsafeNativeMethods.IAdsPropertyEntry propertyEntry = (UnsafeNativeMethods.IAdsPropertyEntry)list.GetPropertyItem(SecurityDescriptorProperty, (int)AdsType.ADSTYPE_OCTET_STRING); GC.KeepAlive(this); // // Create a new ActiveDirectorySecurity object from the binary form // of the security descriptor // object[] values = (object[])propertyEntry.Values; // // This should never happen. It indicates that there is a problem in ADSI's property cache logic. // if (values.Length < 1) { Debug.Fail("ntSecurityDescriptor property exists in cache but has no values."); throw new InvalidOperationException(SR.DSSDNoValues); } // // Do not support more than one security descriptor // if (values.Length > 1) { throw new NotSupportedException(SR.DSMultipleSDNotSupported); } UnsafeNativeMethods.IAdsPropertyValue propertyValue = (UnsafeNativeMethods.IAdsPropertyValue)values[0]; return new ActiveDirectorySecurity((byte[])propertyValue.OctetString, securityMasksUsedInRetrieval); } else { // // Newly created directory entry // return null; } } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode == unchecked((int)0x8000500D)) // property not found exception return null; else throw; } } private void SetObjectSecurityInCache() { if ((_objectSecurity != null) && (_objectSecurityModified || _objectSecurity.IsModified())) { UnsafeNativeMethods.IAdsPropertyValue sDValue = (UnsafeNativeMethods.IAdsPropertyValue)new UnsafeNativeMethods.PropertyValue(); sDValue.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING; sDValue.OctetString = _objectSecurity.GetSecurityDescriptorBinaryForm(); UnsafeNativeMethods.IAdsPropertyEntry newSDEntry = (UnsafeNativeMethods.IAdsPropertyEntry)new UnsafeNativeMethods.PropertyEntry(); newSDEntry.Name = SecurityDescriptorProperty; newSDEntry.ADsType = (int)AdsType.ADSTYPE_OCTET_STRING; newSDEntry.ControlCode = (int)AdsPropertyOperation.Update; newSDEntry.Values = new object[] { sDValue }; ((UnsafeNativeMethods.IAdsPropertyList)NativeObject).PutPropertyItem(newSDEntry); } } } }
// Copyright (c) 2011-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) #if __MonoCS__ using System; using System.Runtime.InteropServices; using X11; using Mono.Unix; namespace X11.XKlavier { /// <summary> /// Provides access to the xklavier XKB keyboarding engine methods. /// </summary> /// <seealso href="https://developer.gnome.org/libxklavier/stable/libxklavier-xkl-engine.html"/> internal class XklEngine: IXklEngine { private struct XklState { public int Group; public int Indicators; } private string[] m_GroupNames; private string[] m_LocalizedGroupNames; public XklEngine(): this(X11Helper.GetDisplayConnection()) { } public XklEngine(IntPtr display) { Engine = xkl_engine_get_instance(display); Catalog.Init("xkeyboard-config", string.Empty); } public void Close() { } public IntPtr Engine { get; private set; } public string Name { get { var name = xkl_engine_get_backend_name(Engine); return Marshal.PtrToStringAuto(name); } } public int NumGroups { get { return xkl_engine_get_num_groups(Engine); } } /// <summary> /// Gets the non-localized, English names of the installed XKB keyboards /// </summary> public virtual string[] GroupNames { get { if (m_GroupNames == null) { int count = NumGroups; var names = xkl_engine_get_groups_names(Engine); var namePtrs = new IntPtr[count]; Marshal.Copy(names, namePtrs, 0, count); m_GroupNames = new string[count]; for (int i = 0; i < count; i++) { m_GroupNames[i] = Marshal.PtrToStringAuto(namePtrs[i]); } } return m_GroupNames; } } /// <summary> /// Gets the localized names of the installed XKB keyboards /// </summary> public virtual string[] LocalizedGroupNames { get { if (m_LocalizedGroupNames == null) { var count = GroupNames.Length; m_LocalizedGroupNames = new string[count]; for (int i = 0; i < count; i++) { m_LocalizedGroupNames[i] = Catalog.GetString(GroupNames[i]); } } return m_LocalizedGroupNames; } } public int NextGroup { get { return xkl_engine_get_next_group(Engine); } } public int PrevGroup { get { return xkl_engine_get_prev_group(Engine); } } public int CurrentWindowGroup { get { return xkl_engine_get_current_window_group(Engine); } } public int DefaultGroup { get { return xkl_engine_get_default_group(Engine); } set { xkl_engine_set_default_group(Engine, value); } } public void SetGroup(int grp) { xkl_engine_lock_group(Engine, grp); } public void SetToplevelWindowGroup(bool fGlobal) { xkl_engine_set_group_per_toplevel_window(Engine, fGlobal); } public bool IsToplevelWindowGroup { get { return xkl_engine_is_group_per_toplevel_window(Engine); } } public int CurrentState { get { var statePtr = xkl_engine_get_current_state(Engine); var state = (XklState)Marshal.PtrToStructure(statePtr, typeof(XklState)); return state.Group; } } public int CurrentWindowState { get { var window = xkl_engine_get_current_window(Engine); IntPtr statePtr; if (xkl_engine_get_state(Engine, window, out statePtr)) { var state = (XklState)Marshal.PtrToStructure(statePtr, typeof(XklState)); return state.Group; } return -1; } } public string LastError { get { var error = xkl_get_last_error(); return Marshal.PtrToStringAuto(error); } } // from libXKlavier [DllImport("libxklavier")] private extern static IntPtr xkl_engine_get_instance(IntPtr display); [DllImport("libxklavier")] private extern static IntPtr xkl_engine_get_backend_name(IntPtr engine); [DllImport("libxklavier")] private extern static int xkl_engine_get_num_groups(IntPtr engine); [DllImport("libxklavier")] private extern static IntPtr xkl_engine_get_groups_names(IntPtr engine); [DllImport("libxklavier")] private extern static int xkl_engine_get_next_group(IntPtr engine); [DllImport("libxklavier")] private extern static int xkl_engine_get_prev_group(IntPtr engine); [DllImport("libxklavier")] private extern static int xkl_engine_get_current_window_group(IntPtr engine); [DllImport("libxklavier")] private extern static void xkl_engine_lock_group(IntPtr engine, int grp); [DllImport("libxklavier")] private extern static int xkl_engine_get_default_group(IntPtr engine); [DllImport("libxklavier")] private extern static void xkl_engine_set_default_group(IntPtr engine, int grp); [DllImport("libxklavier")] private extern static void xkl_engine_set_group_per_toplevel_window(IntPtr engine, bool isGlobal); [DllImport("libxklavier")] private extern static bool xkl_engine_is_group_per_toplevel_window(IntPtr engine); [DllImport("libxklavier")] private extern static IntPtr xkl_engine_get_current_state(IntPtr engine); [DllImport("libxklavier")] private extern static IntPtr xkl_engine_get_current_window(IntPtr engine); [DllImport("libxklavier")] private extern static bool xkl_engine_get_state(IntPtr engine, IntPtr win, out IntPtr state_out); [DllImport("libxklavier")] private extern static IntPtr xkl_get_last_error(); } } #endif
namespace Volante { using System; using System.Collections; using System.Collections.Generic; public class TestTimeSeriesResult : TestResult { public TimeSpan InsertTime; public TimeSpan SearchTime1; public TimeSpan SearchTime2; public TimeSpan RemoveTime; } public class TestTimeSeries : ITest { public struct Quote : ITimeSeriesTick { public int timestamp; public float low; public float high; public float open; public float close; public int volume; public long Ticks { get { return getTicks(timestamp); } } } public static Random rand; public static Quote NewQuote(int timestamp) { Quote quote = new Quote(); quote.timestamp = timestamp; quote.open = (float)rand.Next(10000) / 100; quote.close = (float)rand.Next(10000) / 100; quote.high = Math.Max(quote.open, quote.close); quote.low = Math.Min(quote.open, quote.close); quote.volume = rand.Next(1000); return quote; } public const int N_ELEMS_PER_BLOCK = 100; class Stock : Persistent { public string name; public ITimeSeries<Quote> quotes; } public void Run(TestConfig config) { Stock stock; int i; int count = config.Count; var res = new TestTimeSeriesResult(); config.Result = res; var start = DateTime.Now; IDatabase db = config.GetDatabase(); IFieldIndex<string, Stock> stocks = (IFieldIndex<string, Stock>)db.Root; Tests.Assert(stocks == null); stocks = db.CreateFieldIndex<string, Stock>("name", IndexType.Unique); stock = new Stock(); stock.name = "BORL"; stock.quotes = db.CreateTimeSeries<Quote>(N_ELEMS_PER_BLOCK, N_ELEMS_PER_BLOCK * TICKS_PER_SECOND * 2); stocks.Put(stock); db.Root = stocks; Tests.Assert(!stock.quotes.IsReadOnly); rand = new Random(2004); int startTimeInSecs = getSeconds(start); int currTime = startTimeInSecs; for (i = 0; i < count; i++) { Quote quote = NewQuote(currTime++); stock.quotes.Add(quote); } Tests.Assert(stock.quotes.Count == count); db.Commit(); Tests.Assert(stock.quotes.Count == count); res.InsertTime = DateTime.Now - start; start = DateTime.Now; rand = new Random(2004); start = DateTime.Now; i = 0; foreach (Quote quote in stock.quotes) { Tests.Assert(quote.timestamp == startTimeInSecs + i); float open = (float)rand.Next(10000) / 100; Tests.Assert(quote.open == open); float close = (float)rand.Next(10000) / 100; Tests.Assert(quote.close == close); Tests.Assert(quote.high == Math.Max(quote.open, quote.close)); Tests.Assert(quote.low == Math.Min(quote.open, quote.close)); Tests.Assert(quote.volume == rand.Next(1000)); i += 1; } Tests.Assert(i == count); res.SearchTime1 = DateTime.Now - start; start = DateTime.Now; long from = getTicks(startTimeInSecs + count / 2); long till = getTicks(startTimeInSecs + count); i = 0; foreach (Quote quote in stock.quotes.Range(new DateTime(from), new DateTime(till), IterationOrder.DescentOrder)) { int expectedtimestamp = startTimeInSecs + count - i - 1; Tests.Assert(quote.timestamp == expectedtimestamp); i += 1; } res.SearchTime2 = DateTime.Now - start; start = DateTime.Now; // insert in the middle stock.quotes.Add(NewQuote(startTimeInSecs - count / 2)); long n = stock.quotes.Remove(stock.quotes.FirstTime, stock.quotes.LastTime); Tests.Assert(n == count + 1); Tests.Assert(stock.quotes.Count == 0); res.RemoveTime = DateTime.Now - start; Quote q; Quote qFirst = NewQuote(0); Quote qMiddle = NewQuote(0); Quote qEnd = NewQuote(0); for (i = 0; i < 10; i++) { q = NewQuote(startTimeInSecs + i); stock.quotes.Add(q); if (i == 0) qFirst = q; else if (i == 5) qMiddle = q; else if (i == 9) qEnd = q; } Tests.Assert(stock.quotes.Contains(qFirst)); Tests.Assert(stock.quotes.Contains(qEnd)); Tests.Assert(stock.quotes.Contains(qMiddle)); Tests.Assert(stock.quotes.Remove(qFirst)); Tests.Assert(!stock.quotes.Contains(qFirst)); Tests.Assert(stock.quotes.Remove(qEnd)); Tests.Assert(!stock.quotes.Contains(qEnd)); Tests.Assert(stock.quotes.Remove(qMiddle)); Tests.Assert(!stock.quotes.Contains(qMiddle)); Quote[] quotes = new Quote[10]; stock.quotes.CopyTo(quotes, 0); stock.quotes.Clear(); Tests.AssertDatabaseException( () => { long tmp = stock.quotes.FirstTime.Ticks; }, DatabaseException.ErrorCode.KEY_NOT_FOUND); Tests.AssertDatabaseException( () => { long tmp = stock.quotes.LastTime.Ticks; }, DatabaseException.ErrorCode.KEY_NOT_FOUND); for (i = 0; i < 10; i++) { q = NewQuote(startTimeInSecs + i); stock.quotes.Add(q); } IEnumerator e = stock.quotes.GetEnumerator(); i = 0; while (e.MoveNext()) { i++; } Tests.Assert(i == 10); Tests.Assert(!e.MoveNext()); Tests.AssertException<InvalidOperationException>( () => { object o = e.Current; }); e.Reset(); Tests.Assert(e.MoveNext()); e = stock.quotes.Reverse().GetEnumerator(); i = 0; while (e.MoveNext()) { i++; } Tests.Assert(i == 10); Tests.Assert(!e.MoveNext()); Tests.AssertException<InvalidOperationException>( () => { object o = e.Current; }); e.Reset(); Tests.Assert(e.MoveNext()); DateTime tStart = new DateTime(getTicks(startTimeInSecs)); DateTime tMiddle = new DateTime(getTicks(startTimeInSecs+5)); DateTime tEnd = new DateTime(getTicks(startTimeInSecs+9)); IEnumerator<Quote> e2 = stock.quotes.GetEnumerator(tStart, tMiddle); VerifyEnumerator(e2, tStart.Ticks, tMiddle.Ticks); e2 = stock.quotes.GetEnumerator(tStart, tMiddle, IterationOrder.DescentOrder); VerifyEnumerator(e2, tStart.Ticks, tMiddle.Ticks, IterationOrder.DescentOrder); e2 = stock.quotes.GetEnumerator(IterationOrder.DescentOrder); VerifyEnumerator(e2, tStart.Ticks, tEnd.Ticks, IterationOrder.DescentOrder); e2 = stock.quotes.Range(tMiddle, tEnd, IterationOrder.AscentOrder).GetEnumerator(); VerifyEnumerator(e2, tMiddle.Ticks, tEnd.Ticks, IterationOrder.AscentOrder); e2 = stock.quotes.Range(IterationOrder.DescentOrder).GetEnumerator(); VerifyEnumerator(e2, tStart.Ticks, tEnd.Ticks, IterationOrder.DescentOrder); e2 = stock.quotes.Till(tMiddle).GetEnumerator(); VerifyEnumerator(e2, tStart.Ticks, tMiddle.Ticks, IterationOrder.DescentOrder); e2 = stock.quotes.From(tMiddle).GetEnumerator(); VerifyEnumerator(e2, tMiddle.Ticks, tEnd.Ticks); e2 = stock.quotes.Reverse().GetEnumerator(); VerifyEnumerator(e2, tStart.Ticks, tEnd.Ticks, IterationOrder.DescentOrder); Tests.Assert(stock.quotes.FirstTime.Ticks == tStart.Ticks); Tests.Assert(stock.quotes.LastTime.Ticks == tEnd.Ticks); for (i = 0; i < 10; i++) { long ticks = getTicks(startTimeInSecs + i); Quote qTmp = stock.quotes[new DateTime(ticks)]; Tests.Assert(qTmp.Ticks == ticks); Tests.Assert(stock.quotes.Contains(new DateTime(ticks))); } Tests.Assert(!stock.quotes.Contains(new DateTime(0))); Tests.AssertDatabaseException( () => { Quote tmp = stock.quotes[new DateTime(0)]; }, DatabaseException.ErrorCode.KEY_NOT_FOUND); stock.quotes.RemoveFrom(new DateTime(getTicks(startTimeInSecs + 8))); stock.quotes.RemoveFrom(new DateTime(getTicks(startTimeInSecs + 2))); stock.quotes.RemoveAll(); db.Commit(); stock.quotes.Deallocate(); db.Commit(); db.Close(); } void VerifyEnumerator(IEnumerator<Quote> e, long tickStart, long tickEnd, IterationOrder order = IterationOrder.AscentOrder) { int n = 0; long tickCurr = 0; if (order == IterationOrder.DescentOrder) tickCurr = long.MaxValue; while (e.MoveNext()) { Quote q = e.Current; Tests.Assert(q.Ticks >= tickStart); Tests.Assert(q.Ticks <= tickEnd); // TODO: FAILED_TEST if (order == IterationOrder.AscentOrder) Tests.Assert(q.Ticks >= tickCurr); else Tests.Assert(q.Ticks <= tickCurr); tickCurr = q.Ticks; n++; } Tests.Assert(!e.MoveNext()); Tests.AssertException<InvalidOperationException>( () => { long ticks = e.Current.Ticks; }); e.Reset(); Tests.Assert(e.MoveNext()); } const long TICKS_PER_SECOND = 10000000L; static DateTime baseDate = new DateTime(1970, 1, 1); static int getSeconds(DateTime dt) { return (int)((dt.Ticks - baseDate.Ticks) / TICKS_PER_SECOND); } static long getTicks(int seconds) { return baseDate.Ticks + seconds * TICKS_PER_SECOND; } } }