context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.SceneManagement; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityTest { public interface ITestComponent : IComparable<ITestComponent> { void EnableTest(bool enable); bool IsTestGroup(); GameObject gameObject { get; } string Name { get; } ITestComponent GetTestGroup(); bool IsExceptionExpected(string exceptionType); bool ShouldSucceedOnException(); double GetTimeout(); bool IsIgnored(); bool ShouldSucceedOnAssertions(); bool IsExludedOnThisPlatform(); } public class TestComponent : MonoBehaviour, ITestComponent { public static ITestComponent NullTestComponent = new NullTestComponentImpl(); public float timeout = 5; public bool ignored = false; public bool succeedAfterAllAssertionsAreExecuted = false; public bool expectException = false; public string expectedExceptionList = ""; public bool succeedWhenExceptionIsThrown = false; public IncludedPlatforms includedPlatforms = (IncludedPlatforms) ~0L; public string[] platformsToIgnore = null; public bool dynamic; public string dynamicTypeName; public bool IsExludedOnThisPlatform() { return platformsToIgnore != null && platformsToIgnore.Any(platform => platform == Application.platform.ToString()); } static bool IsAssignableFrom(Type a, Type b) { #if !UNITY_METRO return a.IsAssignableFrom(b); #else return false; #endif } public bool IsExceptionExpected(string exception) { exception = exception.Trim(); if (!expectException) return false; if(string.IsNullOrEmpty(expectedExceptionList.Trim())) return true; foreach (var expectedException in expectedExceptionList.Split(',').Select(e => e.Trim())) { if (exception == expectedException) return true; var exceptionType = Type.GetType(exception) ?? GetTypeByName(exception); var expectedExceptionType = Type.GetType(expectedException) ?? GetTypeByName(expectedException); if (exceptionType != null && expectedExceptionType != null && IsAssignableFrom(expectedExceptionType, exceptionType)) return true; } return false; } public bool ShouldSucceedOnException() { return succeedWhenExceptionIsThrown; } public double GetTimeout() { return timeout; } public bool IsIgnored() { return ignored; } public bool ShouldSucceedOnAssertions() { return succeedAfterAllAssertionsAreExecuted; } private static Type GetTypeByName(string className) { #if !UNITY_METRO return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(type => type.Name == className); #else return null; #endif } public void OnValidate() { if (timeout < 0.01f) timeout = 0.01f; } // Legacy [Flags] public enum IncludedPlatforms { WindowsEditor = 1 << 0, OSXEditor = 1 << 1, WindowsPlayer = 1 << 2, OSXPlayer = 1 << 3, LinuxPlayer = 1 << 4, MetroPlayerX86 = 1 << 5, MetroPlayerX64 = 1 << 6, MetroPlayerARM = 1 << 7, WindowsWebPlayer = 1 << 8, OSXWebPlayer = 1 << 9, Android = 1 << 10, // ReSharper disable once InconsistentNaming IPhonePlayer = 1 << 11, TizenPlayer = 1 << 12, WP8Player = 1 << 13, BB10Player = 1 << 14, NaCl = 1 << 15, PS3 = 1 << 16, XBOX360 = 1 << 17, WiiPlayer = 1 << 18, PSP2 = 1 << 19, PS4 = 1 << 20, PSMPlayer = 1 << 21, XboxOne = 1 << 22, } #region ITestComponent implementation public void EnableTest(bool enable) { if (enable && dynamic) { Type t = Type.GetType(dynamicTypeName); var s = gameObject.GetComponent(t) as MonoBehaviour; if (s != null) DestroyImmediate(s); gameObject.AddComponent(t); } if (gameObject.activeSelf != enable) gameObject.SetActive(enable); } public int CompareTo(ITestComponent obj) { if (obj == NullTestComponent) return 1; var result = gameObject.name.CompareTo(obj.gameObject.name); if (result == 0) result = gameObject.GetInstanceID().CompareTo(obj.gameObject.GetInstanceID()); return result; } public bool IsTestGroup() { for (int i = 0; i < gameObject.transform.childCount; i++) { var childTc = gameObject.transform.GetChild(i).GetComponent(typeof(TestComponent)); if (childTc != null) return true; } return false; } public string Name { get { return gameObject == null ? "" : gameObject.name; } } public ITestComponent GetTestGroup() { var parent = gameObject.transform.parent; if (parent == null) return NullTestComponent; return parent.GetComponent<TestComponent>(); } public override bool Equals(object o) { if (o is TestComponent) return this == (o as TestComponent); return false; } public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==(TestComponent a, TestComponent b) { if (ReferenceEquals(a, b)) return true; if (((object)a == null) || ((object)b == null)) return false; if (a.dynamic && b.dynamic) return a.dynamicTypeName == b.dynamicTypeName; if (a.dynamic || b.dynamic) return false; return a.gameObject == b.gameObject; } public static bool operator !=(TestComponent a, TestComponent b) { return !(a == b); } #endregion #region Static helpers public static TestComponent CreateDynamicTest(Type type) { var go = CreateTest(type.Name); go.hideFlags |= HideFlags.DontSave; go.SetActive(false); var tc = go.GetComponent<TestComponent>(); tc.dynamic = true; tc.dynamicTypeName = type.AssemblyQualifiedName; #if !UNITY_METRO foreach (var typeAttribute in type.GetCustomAttributes(false)) { if (typeAttribute is IntegrationTest.TimeoutAttribute) tc.timeout = (typeAttribute as IntegrationTest.TimeoutAttribute).timeout; else if (typeAttribute is IntegrationTest.IgnoreAttribute) tc.ignored = true; else if (typeAttribute is IntegrationTest.SucceedWithAssertions) tc.succeedAfterAllAssertionsAreExecuted = true; else if (typeAttribute is IntegrationTest.ExcludePlatformAttribute) tc.platformsToIgnore = (typeAttribute as IntegrationTest.ExcludePlatformAttribute).platformsToExclude; else if (typeAttribute is IntegrationTest.ExpectExceptions) { var attribute = (typeAttribute as IntegrationTest.ExpectExceptions); tc.expectException = true; tc.expectedExceptionList = string.Join(",", attribute.exceptionTypeNames); tc.succeedWhenExceptionIsThrown = attribute.succeedOnException; } } go.AddComponent(type); #endif // if !UNITY_METRO return tc; } public static GameObject CreateTest() { return CreateTest("New Test"); } private static GameObject CreateTest(string name) { var go = new GameObject(name); go.AddComponent<TestComponent>(); #if UNITY_EDITOR Undo.RegisterCreatedObjectUndo(go, "Created test"); #endif return go; } public static List<TestComponent> FindAllTestsOnScene() { var tests = Resources.FindObjectsOfTypeAll (typeof(TestComponent)).Cast<TestComponent> (); #if UNITY_EDITOR tests = tests.Where( t => {var p = PrefabUtility.GetPrefabType(t); return p != PrefabType.Prefab && p != PrefabType.ModelPrefab;} ); #endif return tests.ToList (); } public static List<TestComponent> FindAllTopTestsOnScene() { return FindAllTestsOnScene().Where(component => component.gameObject.transform.parent == null).ToList(); } public static List<TestComponent> FindAllDynamicTestsOnScene() { return FindAllTestsOnScene().Where(t => t.dynamic).ToList(); } public static void DestroyAllDynamicTests() { foreach (var dynamicTestComponent in FindAllDynamicTestsOnScene()) DestroyImmediate(dynamicTestComponent.gameObject); } public static void DisableAllTests() { foreach (var t in FindAllTestsOnScene()) t.EnableTest(false); } public static bool AnyTestsOnScene() { return FindAllTestsOnScene().Any(); } public static bool AnyDynamicTestForCurrentScene() { #if UNITY_EDITOR return TestComponent.GetTypesWithHelpAttribute(SceneManager.GetActiveScene().name).Any(); #else return TestComponent.GetTypesWithHelpAttribute(SceneManager.GetActiveScene().name).Any(); #endif } #endregion private sealed class NullTestComponentImpl : ITestComponent { public int CompareTo(ITestComponent other) { if (other == this) return 0; return -1; } public void EnableTest(bool enable) { } public bool IsTestGroup() { throw new NotImplementedException(); } public GameObject gameObject { get; private set; } public string Name { get { return ""; } } public ITestComponent GetTestGroup() { return null; } public bool IsExceptionExpected(string exceptionType) { throw new NotImplementedException(); } public bool ShouldSucceedOnException() { throw new NotImplementedException(); } public double GetTimeout() { throw new NotImplementedException(); } public bool IsIgnored() { throw new NotImplementedException(); } public bool ShouldSucceedOnAssertions() { throw new NotImplementedException(); } public bool IsExludedOnThisPlatform() { throw new NotImplementedException(); } } public static IEnumerable<Type> GetTypesWithHelpAttribute(string sceneName) { #if !UNITY_METRO foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { Type[] types = null; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { Debug.LogError("Failed to load types from: " + assembly.FullName); foreach (Exception loadEx in ex.LoaderExceptions) Debug.LogException(loadEx); } if (types == null) continue; foreach (Type type in types) { var attributes = type.GetCustomAttributes(typeof(IntegrationTest.DynamicTestAttribute), true); if (attributes.Length == 1) { var a = attributes.Single() as IntegrationTest.DynamicTestAttribute; if (a.IncludeOnScene(sceneName)) yield return type; } } } #else // if !UNITY_METRO yield break; #endif // if !UNITY_METRO } } }
// 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 Xunit; namespace System.Collections.Tests { public static class DictionaryBaseTests { private static FooKey CreateKey(int i) => new FooKey(i, i.ToString()); private static FooValue CreateValue(int i) => new FooValue(i, i.ToString()); private static MyDictionary CreateDictionary(int count) { var dictionary = new MyDictionary(); for (int i = 0; i < count; i++) { dictionary.Add(CreateKey(i), CreateValue(i)); } return dictionary; } [Fact] public static void Add() { var dictBase = new MyDictionary(); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Add(key, CreateValue(i)); Assert.True(dictBase.Contains(key)); } Assert.Equal(100, dictBase.Count); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } FooKey nullKey = CreateKey(101); dictBase.Add(nullKey, null); Assert.Equal(null, dictBase[nullKey]); } [Fact] public static void Remove() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Remove(key); Assert.False(dictBase.Contains(key)); } Assert.Equal(0, dictBase.Count); dictBase.Remove(new FooKey()); // Doesn't exist, but doesn't throw } [Fact] public static void Contains() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.True(dictBase.Contains(CreateKey(i))); } Assert.False(dictBase.Contains(new FooKey())); } [Fact] public static void Keys() { MyDictionary dictBase = CreateDictionary(100); ICollection keys = dictBase.Keys; Assert.Equal(dictBase.Count, keys.Count); foreach (FooKey key in keys) { Assert.True(dictBase.Contains(key)); } } [Fact] public static void Values() { MyDictionary dictBase = CreateDictionary(100); ICollection values = dictBase.Values; Assert.Equal(dictBase.Count, values.Count); foreach (FooValue value in values) { FooKey key = CreateKey(value.IntValue); Assert.Equal(value, dictBase[key]); } } [Fact] public static void Item_Get() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } Assert.Equal(null, dictBase[new FooKey()]); } [Fact] public static void Item_Get_NullKey_ThrowsArgumentNullException() { var dictBase = new MyDictionary(); AssertExtensions.Throws<ArgumentNullException>("key", () => dictBase[null]); } [Fact] public static void Item_Set() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { FooKey key = CreateKey(i); FooValue value = CreateValue(dictBase.Count - i - 1); dictBase[key] = value; Assert.Equal(value, dictBase[key]); } FooKey nonExistentKey = CreateKey(101); dictBase[nonExistentKey] = null; Assert.Equal(101, dictBase.Count); // Should add a key/value pair if the key Assert.Equal(null, dictBase[nonExistentKey]); } [Fact] public static void Indexer_Set_NullKey_ThrowsArgumentNullException() { var dictBase = new MyDictionary(); AssertExtensions.Throws<ArgumentNullException>("key", () => dictBase[null] = new FooValue()); } [Fact] public static void Clear() { MyDictionary dictBase = CreateDictionary(100); dictBase.Clear(); Assert.Equal(0, dictBase.Count); } [Fact] public static void CopyTo() { MyDictionary dictBase = CreateDictionary(100); // Basic var entries = new DictionaryEntry[dictBase.Count]; dictBase.CopyTo(entries, 0); Assert.Equal(dictBase.Count, entries.Length); for (int i = 0; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } // With index entries = new DictionaryEntry[dictBase.Count * 2]; dictBase.CopyTo(entries, dictBase.Count); Assert.Equal(dictBase.Count * 2, entries.Length); for (int i = dictBase.Count; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } } [Fact] public static void CopyTo_Invalid() { MyDictionary dictBase = CreateDictionary(100); AssertExtensions.Throws<ArgumentNullException>("array", () => dictBase.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => dictBase.CopyTo(new object[100, 100], 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => dictBase.CopyTo(new DictionaryEntry[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>(null, () => dictBase.CopyTo(new DictionaryEntry[100], 100)); // Index >= count AssertExtensions.Throws<ArgumentException>(null, () => dictBase.CopyTo(new DictionaryEntry[100], 50)); // Index + array.Count >= count } [Fact] public static void GetEnumerator_IDictionaryEnumerator() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry1 = (DictionaryEntry)enumerator.Current; DictionaryEntry entry2 = enumerator.Entry; Assert.Equal(entry1.Key, entry2.Key); Assert.Equal(entry1.Value, entry2.Value); Assert.Equal(enumerator.Key, entry1.Key); Assert.Equal(enumerator.Value, entry1.Value); Assert.Equal(enumerator.Value, dictBase[(FooKey)enumerator.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void GetEnumerator_IDictionaryEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Index > dictionary.Count while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); } [Fact] public static void GetEnumerator_IEnumerator() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal((FooValue)entry.Value, dictBase[(FooKey)entry.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void GetEnumerator_IEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index >= dictionary.Count while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static void SyncRoot() { // SyncRoot should be the reference to the underlying dictionary, not to MyDictionary var dictBase = new MyDictionary(); object syncRoot = dictBase.SyncRoot; Assert.NotSame(syncRoot, dictBase); Assert.Same(dictBase.SyncRoot, dictBase.SyncRoot); } [Fact] public static void IDictionaryProperties() { var dictBase = new MyDictionary(); Assert.False(dictBase.IsFixedSize); Assert.False(dictBase.IsReadOnly); Assert.False(dictBase.IsSynchronized); } [Fact] public static void Add_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, "hello"); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnInsertCalled); Assert.True(dictBase.OnInsertCompleteCalled); Assert.True(dictBase.Contains(f)); } [Fact] public static void Add_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsert dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsertComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); } [Fact] public static void Remove_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateCalled = false; dictBase.Remove(f); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnRemoveCalled); Assert.True(dictBase.OnRemoveCompleteCalled); Assert.False(dictBase.Contains(f)); } [Fact] public static void Remove_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemove dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemoveComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); } [Fact] public static void Clear_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.Clear(); Assert.True(dictBase.OnClearCalled); Assert.True(dictBase.OnClearCompleteCalled); Assert.Equal(0, dictBase.Count); } [Fact] public static void Clear_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; dictBase.Clear(); Assert.Equal(0, dictBase.Count); // Throw OnClear dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(1, dictBase.Count); // Throw OnClearComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(0, dictBase.Count); } [Fact] public static void Set_New_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal(1, dictBase.Count); Assert.Equal("hello", dictBase[f]); } [Fact] public static void Set_New_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); } [Fact] public static void Set_Existing_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(new FooKey(), ""); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal("hello", dictBase[f]); } [Fact] public static void Set_Existing_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class MyDictionary : DictionaryBase { public void Add(FooKey key, FooValue value) => Dictionary.Add(key, value); public FooValue this[FooKey key] { get { return (FooValue)Dictionary[key]; } set { Dictionary[key] = value; } } public bool IsSynchronized { get { return Dictionary.IsSynchronized; } } public object SyncRoot { get { return Dictionary.SyncRoot; } } public bool Contains(FooKey key) => Dictionary.Contains(key); public void Remove(FooKey key) => Dictionary.Remove(key); public bool IsFixedSize { get { return Dictionary.IsFixedSize; } } public bool IsReadOnly { get { return Dictionary.IsReadOnly; } } public ICollection Keys { get { return Dictionary.Keys; } } public ICollection Values { get { return Dictionary.Values; } } } private class FooKey : IComparable { public FooKey() { } public FooKey(int i, string str) { IntValue = i; StringValue = str; } public int IntValue { get; set; } public string StringValue { get; set; } public override bool Equals(object obj) { FooKey foo = obj as FooKey; if (foo == null) return false; return foo.IntValue == IntValue && foo.StringValue == StringValue; } public override int GetHashCode() =>IntValue; public int CompareTo(object obj) { FooKey temp = (FooKey)obj; return IntValue.CompareTo(temp.IntValue); } } private class FooValue : IComparable { public FooValue() { } public FooValue(int intValue, string stringValue) { IntValue = intValue; StringValue = stringValue; } public int IntValue { get; set; } public string StringValue { get; set; } public override bool Equals(object obj) { FooValue foo = obj as FooValue; if (foo == null) return false; return foo.IntValue == IntValue && foo.StringValue == StringValue; } public override int GetHashCode() => IntValue; public int CompareTo(object obj) { FooValue temp = (FooValue)obj; return IntValue.CompareTo(temp.IntValue); } } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class OnMethodCalledDictionary : DictionaryBase { public bool OnValidateCalled; public bool OnSetCalled; public bool OnSetCompleteCalled; public bool OnInsertCalled; public bool OnInsertCompleteCalled; public bool OnClearCalled; public bool OnClearCompleteCalled; public bool OnRemoveCalled; public bool OnRemoveCompleteCalled; public bool OnValidateThrow; public bool OnSetThrow; public bool OnSetCompleteThrow; public bool OnInsertThrow; public bool OnInsertCompleteThrow; public bool OnClearThrow; public bool OnClearCompleteThrow; public bool OnRemoveThrow; public bool OnRemoveCompleteThrow; public void Add(FooKey key, string value) => Dictionary.Add(key, value); public string this[FooKey key] { get { return (string)Dictionary[key]; } set { Dictionary[key] = value; } } public bool Contains(FooKey key) => Dictionary.Contains(key); public void Remove(FooKey key) => Dictionary.Remove(key); protected override void OnSet(object key, object oldValue, object newValue) { Assert.True(OnValidateCalled); Assert.Equal(oldValue, this[(FooKey)key]); OnSetCalled = true; if (OnSetThrow) throw new Exception("OnSet"); } protected override void OnInsert(object key, object value) { Assert.True(OnValidateCalled); Assert.NotEqual(value, this[(FooKey)key]); OnInsertCalled = true; if (OnInsertThrow) throw new Exception("OnInsert"); } protected override void OnClear() { OnClearCalled = true; if (OnClearThrow) throw new Exception("OnClear"); } protected override void OnRemove(object key, object value) { Assert.True(OnValidateCalled); Assert.Equal(value, this[(FooKey)key]); OnRemoveCalled = true; if (OnRemoveThrow) throw new Exception("OnRemove"); } protected override void OnValidate(object key, object value) { OnValidateCalled = true; if (OnValidateThrow) throw new Exception("OnValidate"); } protected override void OnSetComplete(object key, object oldValue, object newValue) { Assert.True(OnSetCalled); Assert.Equal(newValue, this[(FooKey)key]); OnSetCompleteCalled = true; if (OnSetCompleteThrow) throw new Exception("OnSetComplete"); } protected override void OnInsertComplete(object key, object value) { Assert.True(OnInsertCalled); Assert.Equal(value, this[(FooKey)key]); OnInsertCompleteCalled = true; if (OnInsertCompleteThrow) throw new Exception("OnInsertComplete"); } protected override void OnClearComplete() { Assert.True(OnClearCalled); OnClearCompleteCalled = true; if (OnClearCompleteThrow) throw new Exception("OnClearComplete"); } protected override void OnRemoveComplete(object key, object value) { Assert.True(OnRemoveCalled); Assert.False(Contains((FooKey)key)); OnRemoveCompleteCalled = true; if (OnRemoveCompleteThrow) throw new Exception("OnRemoveComplete"); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace ClosedXML.Excel.CalcEngine.Functions { internal static class DateAndTime { public static void Register(CalcEngine ce) { ce.RegisterFunction("DATE", 3, Date); // Returns the serial number of a particular date ce.RegisterFunction("DATEVALUE", 1, Datevalue); // Converts a date in the form of text to a serial number ce.RegisterFunction("DAY", 1, Day); // Converts a serial number to a day of the month ce.RegisterFunction("DAYS", 2, Days); // Returns the number of days between two dates. ce.RegisterFunction("DAYS360", 2, 3, Days360); // Calculates the number of days between two dates based on a 360-day year ce.RegisterFunction("EDATE", 2, Edate); // Returns the serial number of the date that is the indicated number of months before or after the start date ce.RegisterFunction("EOMONTH", 2, Eomonth); // Returns the serial number of the last day of the month before or after a specified number of months ce.RegisterFunction("HOUR", 1, Hour); // Converts a serial number to an hour ce.RegisterFunction("ISOWEEKNUM", 1, IsoWeekNum); // Returns number of the ISO week number of the year for a given date. ce.RegisterFunction("MINUTE", 1, Minute); // Converts a serial number to a minute ce.RegisterFunction("MONTH", 1, Month); // Converts a serial number to a month ce.RegisterFunction("NETWORKDAYS", 2, 3, Networkdays); // Returns the number of whole workdays between two dates ce.RegisterFunction("NOW", 0, Now); // Returns the serial number of the current date and time ce.RegisterFunction("SECOND", 1, Second); // Converts a serial number to a second ce.RegisterFunction("TIME", 3, Time); // Returns the serial number of a particular time ce.RegisterFunction("TIMEVALUE", 1, Timevalue); // Converts a time in the form of text to a serial number ce.RegisterFunction("TODAY", 0, Today); // Returns the serial number of today's date ce.RegisterFunction("WEEKDAY", 1, 2, Weekday); // Converts a serial number to a day of the week ce.RegisterFunction("WEEKNUM", 1, 2, Weeknum); // Converts a serial number to a number representing where the week falls numerically with a year ce.RegisterFunction("WORKDAY", 2, 3, Workday); // Returns the serial number of the date before or after a specified number of workdays ce.RegisterFunction("YEAR", 1, Year); // Converts a serial number to a year ce.RegisterFunction("YEARFRAC", 2, 3, Yearfrac); // Returns the year fraction representing the number of whole days between start_date and end_date } /// <summary> /// Calculates number of business days, taking into account: /// - weekends (Saturdays and Sundays) /// - bank holidays in the middle of the week /// </summary> /// <param name="firstDay">First day in the time interval</param> /// <param name="lastDay">Last day in the time interval</param> /// <param name="bankHolidays">List of bank holidays excluding weekends</param> /// <returns>Number of business days during the 'span'</returns> private static int BusinessDaysUntil(DateTime firstDay, DateTime lastDay, IEnumerable<DateTime> bankHolidays) { firstDay = firstDay.Date; lastDay = lastDay.Date; if (firstDay > lastDay) return -BusinessDaysUntil(lastDay, firstDay, bankHolidays); TimeSpan span = lastDay - firstDay; int businessDays = span.Days + 1; int fullWeekCount = businessDays / 7; // find out if there are weekends during the time exceedng the full weeks if (businessDays > fullWeekCount * 7) { // we are here to find out if there is a 1-day or 2-days weekend // in the time interval remaining after subtracting the complete weeks var firstDayOfWeek = (int)firstDay.DayOfWeek; var lastDayOfWeek = (int)lastDay.DayOfWeek; if (lastDayOfWeek < firstDayOfWeek) lastDayOfWeek += 7; if (firstDayOfWeek <= 6) { if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval businessDays -= 2; else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval businessDays -= 1; } else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval businessDays -= 1; } // subtract the weekends during the full weeks in the interval businessDays -= fullWeekCount + fullWeekCount; // subtract the number of bank holidays during the time interval foreach (var bh in bankHolidays) { if (firstDay <= bh && bh <= lastDay) --businessDays; } return businessDays; } private static object Date(List<Expression> p) { var year = (int)p[0]; var month = (int)p[1]; var day = (int)p[2]; // Excel allows months and days outside the normal range, and adjusts the date accordingly if (month > 12 || month < 1) { year += (int)Math.Floor((double)(month - 1d) / 12.0); month -= (int)Math.Floor((double)(month - 1d) / 12.0) * 12; } int daysAdjustment = 0; if (day > DateTime.DaysInMonth(year, month)) { daysAdjustment = day - DateTime.DaysInMonth(year, month); day = DateTime.DaysInMonth(year, month); } else if (day < 1) { daysAdjustment = day - 1; day = 1; } return (int)Math.Floor(new DateTime(year, month, day).AddDays(daysAdjustment).ToOADate()); } private static object Datevalue(List<Expression> p) { var date = (string)p[0]; return (int)Math.Floor(DateTime.Parse(date).ToOADate()); } private static object Day(List<Expression> p) { var date = (DateTime)p[0]; return date.Day; } private static object Days(List<Expression> p) { Type type; int end_date; type = p[0]._token.Value.GetType(); if (type == typeof(string)) end_date = (int)Datevalue(new List<Expression>() { p[0] }); else end_date = (int)p[0]; int start_date; type = p[1]._token.Value.GetType(); if (type == typeof(string)) start_date = (int)Datevalue(new List<Expression>() { p[1] }); else start_date = (int)p[1]; return end_date - start_date; } private static object Days360(List<Expression> p) { var date1 = (DateTime)p[0]; var date2 = (DateTime)p[1]; var isEuropean = p.Count == 3 ? p[2] : false; return Days360(date1, date2, isEuropean); } private static Int32 Days360(DateTime date1, DateTime date2, Boolean isEuropean) { var d1 = date1.Day; var m1 = date1.Month; var y1 = date1.Year; var d2 = date2.Day; var m2 = date2.Month; var y2 = date2.Year; if (isEuropean) { if (d1 == 31) d1 = 30; if (d2 == 31) d2 = 30; } else { if (d1 == 31) d1 = 30; if (d2 == 31 && d1 == 30) d2 = 30; } return 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1); } private static object Edate(List<Expression> p) { var date = (DateTime)p[0]; var mod = (int)p[1]; var retDate = date.AddMonths(mod); return retDate; } private static object Eomonth(List<Expression> p) { var start_date = (DateTime)p[0]; var months = (int)p[1]; var retDate = start_date.AddMonths(months); return new DateTime(retDate.Year, retDate.Month, DateTime.DaysInMonth(retDate.Year, retDate.Month)); } private static Double GetYearAverage(DateTime date1, DateTime date2) { var daysInYears = new List<Int32>(); for (int year = date1.Year; year <= date2.Year; year++) daysInYears.Add(DateTime.IsLeapYear(year) ? 366 : 365); return daysInYears.Average(); } private static object Hour(List<Expression> p) { var date = (DateTime)p[0]; return date.Hour; } // http://stackoverflow.com/questions/11154673/get-the-correct-week-number-of-a-given-date private static object IsoWeekNum(List<Expression> p) { var date = (DateTime)p[0]; // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(date); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { date = date.AddDays(3); } // Return the week of our adjusted day return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } private static object Minute(List<Expression> p) { var date = (DateTime)p[0]; return date.Minute; } private static object Month(List<Expression> p) { var date = (DateTime)p[0]; return date.Month; } private static object Networkdays(List<Expression> p) { var date1 = (DateTime)p[0]; var date2 = (DateTime)p[1]; var bankHolidays = new List<DateTime>(); if (p.Count == 3) { var t = new Tally { p[2] }; bankHolidays.AddRange(t.Select(XLHelper.GetDate)); } return BusinessDaysUntil(date1, date2, bankHolidays); } private static object Now(List<Expression> p) { return DateTime.Now; } private static object Second(List<Expression> p) { var date = (DateTime)p[0]; return date.Second; } private static object Time(List<Expression> p) { var hour = (int)p[0]; var minute = (int)p[1]; var second = (int)p[2]; return new TimeSpan(0, hour, minute, second); } private static object Timevalue(List<Expression> p) { var date = (DateTime)p[0]; return (DateTime.MinValue + date.TimeOfDay).ToOADate(); } private static object Today(List<Expression> p) { return DateTime.Today; } private static object Weekday(List<Expression> p) { var dayOfWeek = (int)((DateTime)p[0]).DayOfWeek; var retType = p.Count == 2 ? (int)p[1] : 1; if (retType == 2) return dayOfWeek; if (retType == 1) return dayOfWeek + 1; return dayOfWeek - 1; } private static object Weeknum(List<Expression> p) { var date = (DateTime)p[0]; var retType = p.Count == 2 ? (int)p[1] : 1; DayOfWeek dayOfWeek = retType == 1 ? DayOfWeek.Sunday : DayOfWeek.Monday; var cal = new GregorianCalendar(GregorianCalendarTypes.Localized); var val = cal.GetWeekOfYear(date, CalendarWeekRule.FirstDay, dayOfWeek); return val; } private static object Workday(List<Expression> p) { var startDate = (DateTime)p[0]; var daysRequired = (int)p[1]; if (daysRequired == 0) return startDate; var bankHolidays = new List<DateTime>(); if (p.Count == 3) { var t = new Tally { p[2] }; bankHolidays.AddRange(t.Select(XLHelper.GetDate)); } var testDate = startDate.AddDays(((daysRequired / 7) + 2) * 7 * Math.Sign(daysRequired)); var return_date = Workday(startDate, testDate, daysRequired, bankHolidays); if (Math.Sign(daysRequired) == 1) return_date = return_date.NextWorkday(bankHolidays); else return_date = return_date.PreviousWorkDay(bankHolidays); return return_date; } private static DateTime Workday(DateTime startDate, DateTime testDate, int daysRequired, IEnumerable<DateTime> bankHolidays) { var businessDays = BusinessDaysUntil(startDate, testDate, bankHolidays); if (businessDays == daysRequired) return testDate; int days = businessDays > daysRequired ? -1 : 1; return Workday(startDate, testDate.AddDays(days), daysRequired, bankHolidays); } private static object Year(List<Expression> p) { var date = (DateTime)p[0]; return date.Year; } private static object Yearfrac(List<Expression> p) { var date1 = (DateTime)p[0]; var date2 = (DateTime)p[1]; var option = p.Count == 3 ? (int)p[2] : 0; if (option == 0) return Days360(date1, date2, false) / 360.0; if (option == 1) return Math.Floor((date2 - date1).TotalDays) / GetYearAverage(date1, date2); if (option == 2) return Math.Floor((date2 - date1).TotalDays) / 360.0; if (option == 3) return Math.Floor((date2 - date1).TotalDays) / 365.0; return Days360(date1, date2, true) / 360.0; } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.List.LastIndexOf(T item) /// </summary> public class ListLastIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = new int[1000]; for (int i = 0; i < 1000; i++) { iArray[i] = i; } List<int> listObject = new List<int>(iArray); int ob = this.GetInt32(0, 1000); int result = listObject.LastIndexOf(ob); if (result != ob) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "banana", "dog", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.LastIndexOf("dog"); if (result != 4) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[5] { myclass1, myclass2, myclass3, myclass3, myclass2 }; List<MyClass> listObject = new List<MyClass>(mc); int result = listObject.LastIndexOf(myclass3); if (result != 3) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value"); try { string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.LastIndexOf("banana"); if (result != 6) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element "); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.LastIndexOf(-10000); if (result != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: The argument is a null reference"); try { string[] strArray = { "apple", "banana", "chocolate" }; List<string> listObject = new List<string>(strArray); int result = listObject.LastIndexOf(null); if (result != -1) { TestLibrary.TestFramework.LogError("011", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { ListLastIndexOf1 test = new ListLastIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ListLastIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
using UnityEngine; using System.Collections.Generic; using tk2dRuntime.TileMap; [ExecuteInEditMode] [AddComponentMenu("2D Toolkit/TileMap/TileMap")] /// <summary> /// Tile Map /// </summary> public class tk2dTileMap : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { /// <summary> /// This is a link to the editor data object (tk2dTileMapEditorData). /// It contains presets, and other data which isn't really relevant in game. /// </summary> public string editorDataGUID = ""; /// <summary> /// Tile map data, stores shared parameters for tilemaps /// </summary> public tk2dTileMapData data; /// <summary> /// Tile map render and collider object /// </summary> public GameObject renderData; /// <summary> /// The sprite collection used by the tilemap /// </summary> [SerializeField] private tk2dSpriteCollectionData spriteCollection = null; public tk2dSpriteCollectionData Editor__SpriteCollection { get { return spriteCollection; } set { _spriteCollectionInst = null; spriteCollection = value; if (spriteCollection != null) _spriteCollectionInst = spriteCollection.inst; } } tk2dSpriteCollectionData _spriteCollectionInst = null; public tk2dSpriteCollectionData SpriteCollectionInst { get { if (_spriteCollectionInst == null && spriteCollection != null) _spriteCollectionInst = spriteCollection.inst; return _spriteCollectionInst; } } [SerializeField] int spriteCollectionKey; /// <summary>Width of the tilemap</summary> public int width = 128; /// <summary>Height of the tilemap</summary> public int height = 128; /// <summary>X axis partition size for this tilemap</summary> public int partitionSizeX = 32; /// <summary>Y axis partition size for this tilemap</summary> public int partitionSizeY = 32; [SerializeField] Layer[] layers; [SerializeField] ColorChannel colorChannel; public int buildKey; [SerializeField] bool _inEditMode = false; public bool AllowEdit { get { return _inEditMode; } } // do we need to retain meshes? public bool serializeRenderData = false; // holds a path to a serialized mesh, uses this to work out dump directory for meshes public string serializedMeshPath; void Awake() { if (spriteCollection != null) _spriteCollectionInst = spriteCollection.inst; bool spriteCollectionKeyMatch = true; if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey) spriteCollectionKeyMatch = false; if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor) { if ((Application.isPlaying && _inEditMode == true) || !spriteCollectionKeyMatch) { // Switched to edit mode while still in edit mode, rebuild Build(BuildFlags.ForceBuild); } } else { if (_inEditMode == true) { Debug.LogError("Tilemap " + name + " is still in edit mode. Please fix." + "Building overhead will be significant."); Build(BuildFlags.ForceBuild); } else if (!spriteCollectionKeyMatch) { Build(BuildFlags.ForceBuild); } } } [System.Flags] public enum BuildFlags { Default = 0, EditMode = 1, ForceBuild = 2 }; public void Build() { Build(BuildFlags.Default); } public void ForceBuild() { Build(BuildFlags.ForceBuild); } // Clears all spawned instances, but retains the renderData object void ClearSpawnedInstances() { if (layers == null) return; for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx) { Layer layer = layers[layerIdx]; for (int chunkIdx = 0; chunkIdx < layer.spriteChannel.chunks.Length; ++chunkIdx) { var chunk = layer.spriteChannel.chunks[chunkIdx]; if (chunk.gameObject == null) continue; var transform = chunk.gameObject.transform; List<Transform> children = new List<Transform>(); for (int i = 0; i < transform.GetChildCount(); ++i) children.Add(transform.GetChild(i)); for (int i = 0; i < children.Count; ++i) DestroyImmediate(children[i].gameObject); } } } public void Build(BuildFlags buildFlags) { if (spriteCollection != null) _spriteCollectionInst = spriteCollection.inst; #if UNITY_EDITOR || !UNITY_FLASH // Sanitize tilePrefabs input, to avoid branches later if (data != null) { if (data.tilePrefabs == null) data.tilePrefabs = new Object[SpriteCollectionInst.Count]; else if (data.tilePrefabs.Length != SpriteCollectionInst.Count) System.Array.Resize(ref data.tilePrefabs, SpriteCollectionInst.Count); // Fix up data if necessary BuilderUtil.InitDataStore(this); } else { return; } // Sanitize sprite collection material ids if (SpriteCollectionInst) SpriteCollectionInst.InitMaterialIds(); bool editMode = (buildFlags & BuildFlags.EditMode) != 0; bool forceBuild = (buildFlags & BuildFlags.ForceBuild) != 0; // When invalid, everything needs to be rebuilt if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey) forceBuild = true; if (forceBuild) ClearSpawnedInstances(); BuilderUtil.CreateRenderData(this, editMode); RenderMeshBuilder.Build(this, editMode, forceBuild); if (!editMode) { ColliderBuilder.Build(this, forceBuild); BuilderUtil.SpawnPrefabs(this); } // Clear dirty flag on everything foreach (var layer in layers) layer.ClearDirtyFlag(); if (colorChannel != null) colorChannel.ClearDirtyFlag(); // One random number to detect undo buildKey = Random.Range(0, int.MaxValue); // Update sprite collection key if (SpriteCollectionInst) spriteCollectionKey = SpriteCollectionInst.buildKey; #endif } /// <summary> /// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers /// Returns true if the position is within the tilemap bounds /// </summary> public bool GetTileAtPosition(Vector3 position, out int x, out int y) { float ox, oy; bool b = GetTileFracAtPosition(position, out ox, out oy); x = (int)ox; y = (int)oy; return b; } /// <summary> /// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers /// The fractional value returned is the fraction into the current tile /// Returns true if the position is within the tilemap bounds /// </summary> public bool GetTileFracAtPosition(Vector3 position, out float x, out float y) { switch (data.tileType) { case tk2dTileMapData.TileType.Rectangular: { Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position); x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x; y = (localPosition.y - data.tileOrigin.y) / data.tileSize.y; return (x >= 0 && x <= width && y >= 0 && y <= height); } case tk2dTileMapData.TileType.Isometric: { if (data.tileSize.x == 0.0f) break; float tileAngle = Mathf.Atan2(data.tileSize.y, data.tileSize.x / 2.0f); Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position); x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x; y = ((localPosition.y - data.tileOrigin.y) / (data.tileSize.y)); float fy = y * 0.5f; int iy = (int)fy; float fry = fy - iy; float frx = x % 1.0f; x = (int)x; y = iy * 2; if (frx > 0.5f) { if (fry > 0.5f && Mathf.Atan2(1.0f - fry, (frx - 0.5f) * 2) < tileAngle) y += 1; else if (fry < 0.5f && Mathf.Atan2(fry, (frx - 0.5f) * 2) < tileAngle) y -= 1; } else if (frx < 0.5f) { if (fry > 0.5f && Mathf.Atan2(fry - 0.5f, frx * 2) > tileAngle) { y += 1; x -= 1; } if (fry < 0.5f && Mathf.Atan2(fry, (0.5f - frx) * 2) < tileAngle) { y -= 1; x -= 1; } } return (x >= 0 && x <= width && y >= 0 && y <= height); } } x = 0.0f; y = 0.0f; return false; } /// <summary> /// Returns the tile position in world space /// </summary> public Vector3 GetTilePosition(int x, int y) { Vector3 localPosition = new Vector3( x * data.tileSize.x + data.tileOrigin.x, y * data.tileSize.y + data.tileOrigin.y, 0); return transform.localToWorldMatrix.MultiplyPoint(localPosition); } /// <summary> /// Gets the tile at position. This can be used to obtain tile data, etc /// -1 = no data or empty tile /// </summary> public int GetTileIdAtPosition(Vector3 position, int layer) { if (layer < 0 || layer >= layers.Length) return -1; int x, y; if (!GetTileAtPosition(position, out x, out y)) return -1; return layers[layer].GetTile(x, y); } /// <summary> /// Returns the tile info chunk for the tile. Use this to store additional metadata /// </summary> public tk2dRuntime.TileMap.TileInfo GetTileInfoForTileId(int tileId) { return data.GetTileInfoForSprite(tileId); } /// <summary> /// Gets the tile at position. This can be used to obtain tile data, etc /// -1 = no data or empty tile /// </summary> public Color GetInterpolatedColorAtPosition(Vector3 position) { Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position); int x = (int)((localPosition.x - data.tileOrigin.x) / data.tileSize.x); int y = (int)((localPosition.y - data.tileOrigin.y) / data.tileSize.y); if (colorChannel == null || colorChannel.IsEmpty) return Color.white; if (x < 0 || x >= width || y < 0 || y >= height) { return colorChannel.clearColor; } int offset; ColorChunk colorChunk = colorChannel.FindChunkAndCoordinate(x, y, out offset); if (colorChunk.Empty) { return colorChannel.clearColor; } else { int colorChunkRowOffset = partitionSizeX + 1; Color tileColorx0y0 = colorChunk.colors[offset]; Color tileColorx1y0 = colorChunk.colors[offset + 1]; Color tileColorx0y1 = colorChunk.colors[offset + colorChunkRowOffset]; Color tileColorx1y1 = colorChunk.colors[offset + colorChunkRowOffset + 1]; float wx = x * data.tileSize.x + data.tileOrigin.x; float wy = y * data.tileSize.y + data.tileOrigin.y; float ix = (localPosition.x - wx) / data.tileSize.x; float iy = (localPosition.y - wy) / data.tileSize.y; Color cy0 = Color.Lerp(tileColorx0y0, tileColorx1y0, ix); Color cy1 = Color.Lerp(tileColorx0y1, tileColorx1y1, ix); return Color.Lerp(cy0, cy1, iy); } } // ISpriteCollectionBuilder public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { return spriteCollection == this.spriteCollection || _spriteCollectionInst == spriteCollection; } #if UNITY_EDITOR public void BeginEditMode() { _inEditMode = true; // Destroy all children if (layers == null) return; ClearSpawnedInstances(); Build(BuildFlags.EditMode | BuildFlags.ForceBuild); } public void EndEditMode() { _inEditMode = false; Build(BuildFlags.ForceBuild); if (serializeRenderData && renderData != null) { #if (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4) Debug.LogError("Prefab needs to be updated"); #else GameObject go = UnityEditor.PrefabUtility.FindValidUploadPrefabInstanceRoot(renderData); Object obj = UnityEditor.PrefabUtility.GetPrefabParent(go); if (obj != null) UnityEditor.PrefabUtility.ReplacePrefab(go, obj, UnityEditor.ReplacePrefabOptions.ConnectToPrefab); #endif } } public bool AreSpritesInitialized() { return layers != null; } public bool HasColorChannel() { return (colorChannel != null && !colorChannel.IsEmpty); } public void CreateColorChannel() { colorChannel = new ColorChannel(width, height, partitionSizeX, partitionSizeY); colorChannel.Create(); } public void DeleteColorChannel() { colorChannel.Delete(); } public void DeleteSprites(int layerId, int x0, int y0, int x1, int y1) { int numTilesX = x1 - x0 + 1; int numTilesY = y1 - y0 + 1; var layer = layers[layerId]; for (int y = 0; y < numTilesY; ++y) { for (int x = 0; x < numTilesX; ++x) { layer.SetTile(x0 + x, y0 + y, -1); } } layer.OptimizeIncremental(); } #endif // used by util functions public Mesh GetOrCreateMesh() { #if UNITY_EDITOR Mesh mesh = new Mesh(); if (serializeRenderData && renderData) { if (serializedMeshPath == null) serializedMeshPath = ""; if (serializedMeshPath.Length == 0) { // find one serialized mesh MeshFilter[] meshFilters = renderData.gameObject.GetComponentsInChildren<MeshFilter>(); foreach (var v in meshFilters) { Mesh m = v.sharedMesh; serializedMeshPath = UnityEditor.AssetDatabase.GetAssetPath(m); if (serializedMeshPath.Length > 0) break; } } if (serializedMeshPath.Length == 0) { MeshCollider[] meshColliders = renderData.gameObject.GetComponentsInChildren<MeshCollider>(); foreach (var v in meshColliders) { Mesh m = v.sharedMesh; serializedMeshPath = UnityEditor.AssetDatabase.GetAssetPath(m); if (serializedMeshPath.Length > 0) break; } } if (serializedMeshPath.Length == 0) { Debug.LogError("Unable to serialize meshes - please resave."); serializeRenderData = false; } else { // save the mesh string path = UnityEditor.AssetDatabase.GenerateUniqueAssetPath(serializedMeshPath); UnityEditor.AssetDatabase.CreateAsset(mesh, path); } } return mesh; #else return new Mesh(); #endif } public void TouchMesh(Mesh mesh) { #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(mesh); #endif } public void DestroyMesh(Mesh mesh) { #if UNITY_EDITOR if (UnityEditor.AssetDatabase.GetAssetPath(mesh).Length != 0) { mesh.Clear(); UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(mesh)); } else { DestroyImmediate(mesh); } #else DestroyImmediate(mesh); #endif } public Layer[] Layers { get { return layers; } set { layers = value; } } public ColorChannel ColorChannel { get { return colorChannel; } set { colorChannel = value; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComProduct.STDCost.DS { public class STD_CostCenterRateMasterDS { public STD_CostCenterRateMasterDS() { } private const string THIS = "PCSComProduct.STDCost.DS.STD_CostCenterRateMasterDS"; public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { STD_CostCenterRateMasterVO objObject = (STD_CostCenterRateMasterVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO STD_CostCenterRateMaster(" + STD_CostCenterRateMasterTable.CCNID_FLD + "," + STD_CostCenterRateMasterTable.CODE_FLD + "," + STD_CostCenterRateMasterTable.NAME_FLD + ")" + "VALUES(?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CODE_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.NAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.NAME_FLD].Value = objObject.Name; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int AddAndReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddAndReturnID()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { STD_CostCenterRateMasterVO objObject = (STD_CostCenterRateMasterVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO STD_CostCenterRateMaster(" + STD_CostCenterRateMasterTable.CCNID_FLD + "," + STD_CostCenterRateMasterTable.CODE_FLD + "," + STD_CostCenterRateMasterTable.NAME_FLD + ")" + " VALUES(?,?,?)" + "; SELECT @@IDENTITY AS NEWID"; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CODE_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.NAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.NAME_FLD].Value = objObject.Name; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); return int.Parse(ocmdPCS.ExecuteScalar().ToString()); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + STD_CostCenterRateMasterTable.TABLE_NAME + " WHERE " + "CostCenterRateMasterID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Gets CostCenterRateMasterVO obejct from ID /// </summary> /// <param name="pintID">Master ID</param> /// <returns>CostCenterRateMasterVO</returns> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD + "," + STD_CostCenterRateMasterTable.CCNID_FLD + "," + STD_CostCenterRateMasterTable.CODE_FLD + "," + STD_CostCenterRateMasterTable.NAME_FLD + " FROM " + STD_CostCenterRateMasterTable.TABLE_NAME + " WHERE " + STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); STD_CostCenterRateMasterVO objObject = new STD_CostCenterRateMasterVO(); while (odrPCS.Read()) { objObject.CostCenterRateMasterID = int.Parse(odrPCS[STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[STD_CostCenterRateMasterTable.CCNID_FLD].ToString().Trim()); objObject.Code = odrPCS[STD_CostCenterRateMasterTable.CODE_FLD].ToString().Trim(); objObject.Name = odrPCS[STD_CostCenterRateMasterTable.NAME_FLD].ToString().Trim(); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; STD_CostCenterRateMasterVO objObject = (STD_CostCenterRateMasterVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE STD_CostCenterRateMaster SET " + STD_CostCenterRateMasterTable.CCNID_FLD + "= ?" + "," + STD_CostCenterRateMasterTable.CODE_FLD + "= ?" + "," + STD_CostCenterRateMasterTable.NAME_FLD + "= ?" + " WHERE " + STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.CODE_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.NAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD].Value = objObject.CostCenterRateMasterID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD + "," + STD_CostCenterRateMasterTable.CCNID_FLD + "," + STD_CostCenterRateMasterTable.CODE_FLD + "," + STD_CostCenterRateMasterTable.NAME_FLD + " FROM " + STD_CostCenterRateMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, STD_CostCenterRateMasterTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + STD_CostCenterRateMasterTable.COSTCENTERRATEMASTERID_FLD + "," + STD_CostCenterRateMasterTable.CCNID_FLD + "," + STD_CostCenterRateMasterTable.CODE_FLD + "," + STD_CostCenterRateMasterTable.NAME_FLD + " FROM " + STD_CostCenterRateMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, STD_CostCenterRateMasterTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get cost by item from cost center rate /// </summary> /// <param name="pintCCNID">CCN</param> /// <returns>DataTable</returns> public DataTable GetCostFromCostCenterRate(int pintCCNID) { const string METHOD_NAME = THIS + ".GetCostFromCostCenterRate()"; DataTable dtbPCS = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT ITM_Product.ProductID, ITM_Product.CostCenterRateMasterID, STD_CostElement.CostElementID," + " STD_CostCenterRateDetail.Cost" + " FROM ITM_Product JOIN STD_CostCenterRateMaster" + " ON ITM_Product.CostCenterRateMasterID = STD_CostCenterRateMaster.CostCenterRateMasterID" + " JOIN STD_CostCenterRateDetail" + " ON STD_CostCenterRateMaster.CostCenterRateMasterID = STD_CostCenterRateDetail.CostCenterRateMasterID" + " JOIN STD_CostElement" + " ON STD_CostCenterRateDetail.CostElementID = STD_CostElement.CostElementID" + " WHERE ITM_Product.CCNID = " + pintCCNID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbPCS); return dtbPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
/** * 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 Avro.IO; using System.IO; namespace Avro.Generic { public delegate T Reader<T>(); /// <summary> /// A general purpose reader of data from avro streams. This can optionally resolve if the reader's and writer's /// schemas are different. This class is a wrapper around DefaultReader and offers a little more type safety. The default reader /// has the flexibility to return any type of object for each read call because the Read() method is generic. This /// class on the other hand can only return a single type because the type is a parameter to the class. Any /// user defined extension should, however, be done to DefaultReader. This class is sealed. /// </summary> /// <typeparam name="T"></typeparam> public sealed class GenericReader<T> : DatumReader<T> { private readonly DefaultReader reader; /// <summary> /// Constructs a generic reader for the given schemas using the DefaultReader. If the /// reader's and writer's schemas are different this class performs the resolution. /// </summary> /// <param name="writerSchema">The schema used while generating the data</param> /// <param name="readerSchema">The schema desired by the reader</param> public GenericReader(Schema writerSchema, Schema readerSchema) : this(new DefaultReader(writerSchema, readerSchema)) { } /// <summary> /// Constructs a generic reader by directly using the given DefaultReader /// </summary> /// <param name="reader">The actual reader to use</param> public GenericReader(DefaultReader reader) { this.reader = reader; } public Schema WriterSchema { get { return reader.WriterSchema; } } public Schema ReaderSchema { get { return reader.ReaderSchema; } } public T Read(T reuse, Decoder d) { return reader.Read(reuse, d); } } /// <summary> /// The default implementation for the generic reader. It constructs new .NET objects for avro objects on the /// stream and returns the .NET object. Users can directly use this class or, if they want to customize the /// object types for differnt Avro schema types, can derive from this class. There are enough hooks in this /// class to allow customization. /// </summary> /// <remarks> /// <list type="table"> /// <listheader><term>Avro Type</term><description>.NET Type</description></listheader> /// <item><term>null</term><description>null reference</description></item> /// </list> /// </remarks> public class DefaultReader { public Schema ReaderSchema { get; private set; } public Schema WriterSchema { get; private set; } /// <summary> /// Constructs the default reader for the given schemas using the DefaultReader. If the /// reader's and writer's schemas are different this class performs the resolution. /// This default implemenation maps Avro types to .NET types as follows: /// </summary> /// <param name="writerSchema">The schema used while generating the data</param> /// <param name="readerSchema">The schema desired by the reader</param> public DefaultReader(Schema writerSchema, Schema readerSchema) { this.ReaderSchema = readerSchema; this.WriterSchema = writerSchema; } /// <summary> /// Reads an object off the stream. /// </summary> /// <typeparam name="T">The type of object to read. A single schema typically returns an object of a single .NET class. /// The only exception is UnionSchema, which can return a object of different types based on the branch selected. /// </typeparam> /// <param name="reuse">If not null, the implemenation will try to use to return the object</param> /// <param name="decoder">The decoder for deserialization</param> /// <returns></returns> public T Read<T>(T reuse, Decoder decoder) { if (!ReaderSchema.CanRead(WriterSchema)) throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema); return (T)Read(reuse, WriterSchema, ReaderSchema, decoder); } public object Read(object reuse, Schema writerSchema, Schema readerSchema, Decoder d) { if (readerSchema.Tag == Schema.Type.Union && writerSchema.Tag != Schema.Type.Union) { readerSchema = findBranch(readerSchema as UnionSchema, writerSchema); } /* if (!readerSchema.CanRead(writerSchema)) { throw new AvroException("Schema mismatch. Reader: " + readerSchema + ", writer: " + writerSchema); } */ switch (writerSchema.Tag) { case Schema.Type.Null: return ReadNull(readerSchema, d); case Schema.Type.Boolean: return Read<bool>(writerSchema.Tag, readerSchema, d.ReadBoolean); case Schema.Type.Int: { int i = Read<int>(writerSchema.Tag, readerSchema, d.ReadInt); switch (readerSchema.Tag) { case Schema.Type.Long: return (long)i; case Schema.Type.Float: return (float)i; case Schema.Type.Double: return (double)i; default: return i; } } case Schema.Type.Long: { long l = Read<long>(writerSchema.Tag, readerSchema, d.ReadLong); switch (readerSchema.Tag) { case Schema.Type.Float: return (float)l; case Schema.Type.Double: return (double)l; default: return l; } } case Schema.Type.Float: { float f = Read<float>(writerSchema.Tag, readerSchema, d.ReadFloat); switch (readerSchema.Tag) { case Schema.Type.Double: return (double)f; default: return f; } } case Schema.Type.Double: return Read<double>(writerSchema.Tag, readerSchema, d.ReadDouble); case Schema.Type.String: return Read<string>(writerSchema.Tag, readerSchema, d.ReadString); case Schema.Type.Bytes: return Read<byte[]>(writerSchema.Tag, readerSchema, d.ReadBytes); case Schema.Type.Error: case Schema.Type.Record: return ReadRecord(reuse, (RecordSchema)writerSchema, readerSchema, d); case Schema.Type.Enumeration: return ReadEnum(reuse, (EnumSchema)writerSchema, readerSchema, d); case Schema.Type.Fixed: return ReadFixed(reuse, (FixedSchema)writerSchema, readerSchema, d); case Schema.Type.Array: return ReadArray(reuse, (ArraySchema)writerSchema, readerSchema, d); case Schema.Type.Map: return ReadMap(reuse, (MapSchema)writerSchema, readerSchema, d); case Schema.Type.Union: return ReadUnion(reuse, (UnionSchema)writerSchema, readerSchema, d); default: throw new AvroException("Unknown schema type: " + writerSchema); } } /// <summary> /// Deserializes a null from the stream. /// </summary> /// <param name="readerSchema">Reader's schema, which should be a NullSchema</param> /// <param name="d">The decoder for deserialization</param> /// <returns></returns> protected virtual object ReadNull(Schema readerSchema, Decoder d) { d.ReadNull(); return null; } /// <summary> /// A generic function to read primitive types /// </summary> /// <typeparam name="S">The .NET type to read</typeparam> /// <param name="tag">The Avro type tag for the object on the stream</param> /// <param name="readerSchema">A schema compatible to the Avro type</param> /// <param name="reader">A function that can read the avro type from the stream</param> /// <returns>The primitive type just read</returns> protected S Read<S>(Schema.Type tag, Schema readerSchema, Reader<S> reader) { return reader(); } /// <summary> /// Deserializes a record from the stream. /// </summary> /// <param name="reuse">If not null, a record object that could be reused for returning the result</param> /// <param name="writerSchema">The writer's RecordSchema</param> /// <param name="readerSchema">The reader's schema, must be RecordSchema too.</param> /// <param name="dec">The decoder for deserialization</param> /// <returns>The record object just read</returns> protected virtual object ReadRecord(object reuse, RecordSchema writerSchema, Schema readerSchema, Decoder dec) { RecordSchema rs = (RecordSchema)readerSchema; object rec = CreateRecord(reuse, rs); foreach (Field wf in writerSchema) { try { Field rf; if (rs.TryGetFieldAlias(wf.Name, out rf)) { object obj = null; TryGetField(rec, wf.Name, rf.Pos, out obj); AddField(rec, wf.Name, rf.Pos, Read(obj, wf.Schema, rf.Schema, dec)); } else Skip(wf.Schema, dec); } catch (Exception ex) { throw new AvroException(ex.Message + " in field " + wf.Name); } } var defaultStream = new MemoryStream(); var defaultEncoder = new BinaryEncoder(defaultStream); var defaultDecoder = new BinaryDecoder(defaultStream); foreach (Field rf in rs) { if (writerSchema.Contains(rf.Name)) continue; defaultStream.Position = 0; // reset for writing Resolver.EncodeDefaultValue(defaultEncoder, rf.Schema, rf.DefaultValue); defaultStream.Flush(); defaultStream.Position = 0; // reset for reading object obj = null; TryGetField(rec, rf.Name, rf.Pos, out obj); AddField(rec, rf.Name, rf.Pos, Read(obj, rf.Schema, rf.Schema, defaultDecoder)); } return rec; } /// <summary> /// Creates a new record object. Derived classes can override this to return an object of their choice. /// </summary> /// <param name="reuse">If appropriate, will reuse this object instead of constructing a new one</param> /// <param name="readerSchema">The schema the reader is using</param> /// <returns></returns> protected virtual object CreateRecord(object reuse, RecordSchema readerSchema) { GenericRecord ru = (reuse == null || !(reuse is GenericRecord) || !(reuse as GenericRecord).Schema.Equals(readerSchema)) ? new GenericRecord(readerSchema) : reuse as GenericRecord; return ru; } /// <summary> /// Used by the default implementation of ReadRecord() to get the existing field of a record object. The derived /// classes can override this to make their own interpretation of the record object. /// </summary> /// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned /// by a previous call to CreateRecord.</param> /// <param name="fieldName">The name of the field to probe.</param> /// <param name="value">The value of the field, if found. Null otherwise.</param> /// <returns>True if and only if a field with the given name is found.</returns> protected virtual bool TryGetField(object record, string fieldName, int fieldPos, out object value) { return (record as GenericRecord).TryGetValue(fieldName, out value); } /// <summary> /// Used by the default implementation of ReadRecord() to add a field to a record object. The derived /// classes can override this to suit their own implementation of the record object. /// </summary> /// <param name="record">The record object to be probed into. This is guaranteed to be one that was returned /// by a previous call to CreateRecord.</param> /// <param name="fieldName">The name of the field to probe.</param> /// <param name="fieldValue">The value to be added for the field</param> protected virtual void AddField(object record, string fieldName, int fieldPos, object fieldValue) { (record as GenericRecord).Add(fieldName, fieldValue); } /// <summary> /// Deserializes a enum. Uses CreateEnum to construct the new enum object. /// </summary> /// <param name="reuse">If appropirate, uses this instead of creating a new enum object.</param> /// <param name="writerSchema">The schema the writer used while writing the enum</param> /// <param name="readerSchema">The schema the reader is using</param> /// <param name="d">The decoder for deserialization.</param> /// <returns>An enum object.</returns> protected virtual object ReadEnum(object reuse, EnumSchema writerSchema, Schema readerSchema, Decoder d) { EnumSchema es = readerSchema as EnumSchema; return CreateEnum(reuse, readerSchema as EnumSchema, writerSchema[d.ReadEnum()]); } /// <summary> /// Used by the default implementation of ReadEnum to construct a new enum object. /// </summary> /// <param name="reuse">If appropriate, use this enum object instead of a new one.</param> /// <param name="es">The enum schema used by the reader.</param> /// <param name="symbol">The symbol that needs to be used.</param> /// <returns>The default implemenation returns a GenericEnum.</returns> protected virtual object CreateEnum(object reuse, EnumSchema es, string symbol) { if (reuse is GenericEnum) { GenericEnum ge = reuse as GenericEnum; if (ge.Schema.Equals(es)) { ge.Value = symbol; return ge; } } return new GenericEnum(es, symbol); } /// <summary> /// Deserializes an array and returns an array object. It uses CreateArray() and works on it before returning it. /// It also uses GetArraySize(), ResizeArray(), SetArrayElement() and GetArrayElement() methods. Derived classes can /// override these methods to customize their behavior. /// </summary> /// <param name="reuse">If appropriate, uses this instead of creating a new array object.</param> /// <param name="writerSchema">The schema used by the writer.</param> /// <param name="readerSchema">The schema that the reader uses.</param> /// <param name="d">The decoder for deserialization.</param> /// <returns>The deserialized array object.</returns> protected virtual object ReadArray(object reuse, ArraySchema writerSchema, Schema readerSchema, Decoder d) { ArraySchema rs = (ArraySchema)readerSchema; object result = CreateArray(reuse, rs); int i = 0; for (int n = (int)d.ReadArrayStart(); n != 0; n = (int)d.ReadArrayNext()) { if (GetArraySize(result) < (i + n)) ResizeArray(ref result, i + n); for (int j = 0; j < n; j++, i++) { SetArrayElement(result, i, Read(GetArrayElement(result, i), writerSchema.ItemSchema, rs.ItemSchema, d)); } } if (GetArraySize(result) != i) ResizeArray(ref result, i); return result; } /// <summary> /// Creates a new array object. The initial size of the object could be anything. The users /// should use GetArraySize() to determine the size. The default implementation creates an <c>object[]</c>. /// </summary> /// <param name="reuse">If appropriate use this instead of creating a new one.</param> /// <returns>An object suitable to deserialize an avro array</returns> protected virtual object CreateArray(object reuse, ArraySchema rs) { return (reuse != null && reuse is object[]) ? (object[])reuse : new object[0]; } /// <summary> /// Returns the size of the given array object. /// </summary> /// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by /// a previous call to CreateArray().</param> /// <returns>The size of the array</returns> protected virtual int GetArraySize(object array) { return (array as object[]).Length; } /// <summary> /// Resizes the array to the new value. /// </summary> /// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by /// a previous call to CreateArray().</param> /// <param name="n">The new size.</param> protected virtual void ResizeArray(ref object array, int n) { object[] o = array as object[]; Array.Resize(ref o, n); array = o; } /// <summary> /// Assigns a new value to the object at the given index /// </summary> /// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by /// a previous call to CreateArray().</param> /// <param name="index">The index to reassign to.</param> /// <param name="value">The value to assign.</param> protected virtual void SetArrayElement(object array, int index, object value) { object[] a = array as object[]; a[index] = value; } /// <summary> /// Returns the element at the given index. /// </summary> /// <param name="array">Array object whose size is required. This is guaranteed to be somthing returned by /// a previous call to CreateArray().</param> /// <param name="index">The index to look into.</param> /// <returns>The object the given index. Null if no object has been assigned to that index.</returns> protected virtual object GetArrayElement(object array, int index) { return (array as object[])[index]; } /// <summary> /// Deserialized an avro map. The default implemenation creats a new map using CreateMap() and then /// adds elements to the map using AddMapEntry(). /// </summary> /// <param name="reuse">If appropriate, use this instead of creating a new map object.</param> /// <param name="writerSchema">The schema the writer used to write the map.</param> /// <param name="readerSchema">The schema the reader is using.</param> /// <param name="d">The decoder for serialization.</param> /// <returns>The deserialized map object.</returns> protected virtual object ReadMap(object reuse, MapSchema writerSchema, Schema readerSchema, Decoder d) { MapSchema rs = (MapSchema)readerSchema; object result = CreateMap(reuse, rs); for (int n = (int)d.ReadMapStart(); n != 0; n = (int)d.ReadMapNext()) { for (int j = 0; j < n; j++) { string k = d.ReadString(); AddMapEntry(result, k, Read(null, writerSchema.ValueSchema, rs.ValueSchema, d)); } } return result; } /// <summary> /// Used by the default implementation of ReadMap() to create a fresh map object. The default /// implementaion of this method returns a IDictionary<string, map>. /// </summary> /// <param name="reuse">If appropriate, use this map object instead of creating a new one.</param> /// <returns>An empty map object.</returns> protected virtual object CreateMap(object reuse, MapSchema ms) { if (reuse != null && reuse is IDictionary<string, object>) { IDictionary<string, object> result = reuse as IDictionary<string, object>; result.Clear(); return result; } return new Dictionary<string, object>(); } /// <summary> /// Adds an entry to the map. /// </summary> /// <param name="map">A map object, which is guaranteed to be one returned by a previous call to CreateMap().</param> /// <param name="key">The key to add.</param> /// <param name="value">The value to add.</param> protected virtual void AddMapEntry(object map, string key, object value) { (map as IDictionary<string, object>).Add(key, value); } /// <summary> /// Deserialized an object based on the writer's uninon schema. /// </summary> /// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param> /// <param name="writerSchema">The UnionSchema that the writer used.</param> /// <param name="readerSchema">The schema the reader uses.</param> /// <param name="d">The decoder for serialization.</param> /// <returns>The deserialized object.</returns> protected virtual object ReadUnion(object reuse, UnionSchema writerSchema, Schema readerSchema, Decoder d) { int index = d.ReadUnionIndex(); Schema ws = writerSchema[index]; if (readerSchema is UnionSchema) readerSchema = findBranch(readerSchema as UnionSchema, ws); else if (!readerSchema.CanRead(ws)) throw new AvroException("Schema mismatch. Reader: " + ReaderSchema + ", writer: " + WriterSchema); return Read(reuse, ws, readerSchema, d); } /// <summary> /// Deserializes a fixed object and returns the object. The default implementation uses CreateFixed() /// and GetFixedBuffer() and returns what CreateFixed() returned. /// </summary> /// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param> /// <param name="writerSchema">The FixedSchema the writer used during serialization.</param> /// <param name="readerSchema">The schema that the readr uses. Must be a FixedSchema with the same /// size as the writerSchema.</param> /// <param name="d">The decoder for deserialization.</param> /// <returns>The deserilized object.</returns> protected virtual object ReadFixed(object reuse, FixedSchema writerSchema, Schema readerSchema, Decoder d) { FixedSchema rs = (FixedSchema)readerSchema; if (rs.Size != writerSchema.Size) { throw new AvroException("Size mismatch between reader and writer fixed schemas. Writer: " + writerSchema + ", reader: " + readerSchema); } object ru = CreateFixed(reuse, rs); byte[] bb = GetFixedBuffer(ru); d.ReadFixed(bb); return ru; } /// <summary> /// Returns a fixed object. /// </summary> /// <param name="reuse">If appropriate, uses this object instead of creating a new one.</param> /// <param name="rs">The reader's FixedSchema.</param> /// <returns>A fixed object with an appropriate buffer.</returns> protected virtual object CreateFixed(object reuse, FixedSchema rs) { return (reuse != null && reuse is GenericFixed && (reuse as GenericFixed).Schema.Equals(rs)) ? (GenericFixed)reuse : new GenericFixed(rs); } /// <summary> /// Returns a buffer of appropriate size to read data into. /// </summary> /// <param name="f">The fixed object. It is guaranteed that this is something that has been previously /// returned by CreateFixed</param> /// <returns>A byte buffer of fixed's size.</returns> protected virtual byte[] GetFixedBuffer(object f) { return (f as GenericFixed).Value; } protected virtual void Skip(Schema writerSchema, Decoder d) { switch (writerSchema.Tag) { case Schema.Type.Null: d.SkipNull(); break; case Schema.Type.Boolean: d.SkipBoolean(); break; case Schema.Type.Int: d.SkipInt(); break; case Schema.Type.Long: d.SkipLong(); break; case Schema.Type.Float: d.SkipFloat(); break; case Schema.Type.Double: d.SkipDouble(); break; case Schema.Type.String: d.SkipString(); break; case Schema.Type.Bytes: d.SkipBytes(); break; case Schema.Type.Record: foreach (Field f in writerSchema as RecordSchema) Skip(f.Schema, d); break; case Schema.Type.Enumeration: d.SkipEnum(); break; case Schema.Type.Fixed: d.SkipFixed((writerSchema as FixedSchema).Size); break; case Schema.Type.Array: { Schema s = (writerSchema as ArraySchema).ItemSchema; for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext()) { for (long i = 0; i < n; i++) Skip(s, d); } } break; case Schema.Type.Map: { Schema s = (writerSchema as MapSchema).ValueSchema; for (long n = d.ReadMapStart(); n != 0; n = d.ReadMapNext()) { for (long i = 0; i < n; i++) { d.SkipString(); Skip(s, d); } } } break; case Schema.Type.Union: Skip((writerSchema as UnionSchema)[d.ReadUnionIndex()], d); break; default: throw new AvroException("Unknown schema type: " + writerSchema); } } protected static Schema findBranch(UnionSchema us, Schema s) { int index = us.MatchingBranch(s); if (index >= 0) return us[index]; throw new AvroException("No matching schema for " + s + " in " + us); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; #if ShowTargetFramework using Mono.Cecil; #endif class ListBinaryInfo { private static string[] netfxToolsPaths = { @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools", @"Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools", @"Microsoft SDKs\Windows\v7.0A\bin", }; private static string corflagsExe; private static string snExe; static void Main(string[] args) { FindCorflagsAndSn(); string patternList = "*.dll;*.exe"; bool recursive = true; var arguments = new HashSet<string>(args, StringComparer.OrdinalIgnoreCase); if (arguments.Contains("/nr")) { arguments.Remove("/nr"); recursive = false; } if (arguments.Count > 0) { if (arguments.Count == 1) { patternList = arguments.First(); if (patternList == "/?" || patternList == "-h" || patternList == "-help" || patternList == "help") { PrintUsage(); return; } } else { PrintUsage(); return; } } var files = new List<string>(); if (File.Exists(patternList)) { files.Add(Path.GetFullPath(patternList)); } else { var root = Environment.CurrentDirectory; var patterns = patternList.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var pattern in patterns) { files.AddRange(Directory.GetFiles(root, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)); } } foreach (var assemblyNameGroup in files.Select(f => FileInfo.Get(f)).GroupBy(f => f.AssemblyName).OrderBy(g => g.Key)) { Highlight(assemblyNameGroup.Key, ConsoleColor.Cyan); foreach (var shaGroup in assemblyNameGroup.GroupBy(f => f.Sha)) { var first = shaGroup.First(); Highlight(" SHA: " + shaGroup.Key, ConsoleColor.DarkGray, newLineAtEnd: false); Highlight(" " + shaGroup.First().FileSize.ToString("N0"), ConsoleColor.Gray, newLineAtEnd: false); if (first.AssemblyName != NotAManagedAssembly) { current = first; CheckSigned(first.FilePath); CheckPlatform(first.FilePath); var signedText = first.FullSigned; if (first.Signed != "Signed" && first.Signed != null) { signedText += "(" + first.Signed + ")"; } if (!string.IsNullOrEmpty(signedText)) { Highlight($" {signedText}", ConsoleColor.DarkGray, newLineAtEnd: false); } var platformText = first.Architecture; if (first.Platform != "32BITPREF : 0" && first.Platform != null) { platformText += "(" + first.Platform + ")"; } if (!string.IsNullOrEmpty(platformText)) { Highlight(" " + platformText, ConsoleColor.Gray, newLineAtEnd: false); } #if ShowTargetFramework var targetFramework = GetTargetFramework(first.FilePath); if (!string.IsNullOrEmpty(targetFramework)) { Highlight(" " + targetFramework, ConsoleColor.Blue, newLineAtEnd: false); } #endif } Console.WriteLine(); foreach (var file in shaGroup.OrderBy(f => f.FilePath)) { Highlight(" " + file.FilePath, ConsoleColor.White); } } } } #if ShowTargetFramework private static string GetTargetFramework(string filePath) { try { using (var module = ModuleDefinition.ReadModule(filePath)) { var targetFrameworkAttribute = module.GetCustomAttributes().FirstOrDefault(a => a.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute"); if (targetFrameworkAttribute != null) { var value = targetFrameworkAttribute.ConstructorArguments[0].Value; return ShortenTargetFramework(value.ToString()); } } } catch { } return null; } #endif private static readonly Dictionary<string, string> targetFrameworkNames = new Dictionary<string, string>() { { ".NETFramework,Version=v", "net" }, { ".NETCoreApp,Version=v", "netcoreapp" }, { ".NETStandard,Version=v", "netstandard" } }; private static string ShortenTargetFramework(string name) { foreach (var kvp in targetFrameworkNames) { if (name.StartsWith(kvp.Key)) { var shortened = name.Substring(kvp.Key.Length); if (kvp.Value == "net") { shortened = shortened.Replace(".", ""); } return kvp.Value + shortened; } } return name; } private static void FindCorflagsAndSn() { foreach (var netfxToolsPath in netfxToolsPaths) { var path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), netfxToolsPath, "corflags.exe"); if (corflagsExe == null && File.Exists(path)) { corflagsExe = path; } path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), netfxToolsPath, @"sn.exe"); if (snExe == null && File.Exists(path)) { snExe = path; } if (corflagsExe != null && snExe != null) { break; } } } public const string NotAManagedAssembly = "Not a managed assembly"; public class FileInfo { public string FilePath { get; set; } public string Sha { get; set; } public string AssemblyName { get; set; } public string FullSigned { get; set; } public string Platform { get; set; } public string Architecture { get; set; } public string Signed { get; set; } public long FileSize { get; set; } public static FileInfo Get(string filePath) { var fileInfo = new FileInfo { FilePath = filePath, AssemblyName = GetAssemblyName(filePath), Sha = Utilities.SHA1Hash(filePath), FileSize = new System.IO.FileInfo(filePath).Length }; return fileInfo; } } private static FileInfo current; private static void PrintUsage() { Console.WriteLine(@"Usage: ListBinaryInfo.exe [<pattern>] [/nr] /nr: non-recursive (current directory only). Recursive by default. Examples: ListBinaryInfo foo.dll ListBinaryInfo *.exe /nr ListBinaryInfo"); } private static string GetAssemblyName(string file) { try { var name = AssemblyName.GetAssemblyName(file); return name.ToString(); } catch { return NotAManagedAssembly; } } private static void CheckPlatform(string file) { if (!File.Exists(corflagsExe)) { return; } file = QuoteIfNecessary(file); StartProcess(corflagsExe, "/nologo " + file); } private static void CheckSigned(string file) { if (!File.Exists(snExe)) { return; } file = QuoteIfNecessary(file); StartProcess(snExe, "-vf " + file); } private static void StartProcess(string executableFilePath, string arguments) { if (!File.Exists(executableFilePath)) { return; } executableFilePath = QuoteIfNecessary(executableFilePath); var psi = new ProcessStartInfo(executableFilePath, arguments); psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; var process = Process.Start(psi); process.OutputDataReceived += Process_DataReceived; process.ErrorDataReceived += Process_DataReceived; process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } private static string QuoteIfNecessary(string filePath) { if (filePath.Contains(' ')) { filePath = "\"" + filePath + "\""; } return filePath; } private static void Process_DataReceived(object sender, DataReceivedEventArgs e) { if (e == null || string.IsNullOrEmpty(e.Data)) { return; } string text = e.Data; if (text.Contains("32BITPREF")) { current.Platform = text; return; } if (text.Contains("Copyright") || text.Contains("(R)") || text.Contains("Version ") || text.Contains("CLR Header") || text.Contains("PE ") || text.Contains("ILONLY ") || text.Contains("CorFlags") || text.Contains("does not represent") || text.Contains("is verified with a key other than the identity key")) { return; } if (text.Contains("The specified file does not have a valid managed header")) { current.AssemblyName = "Native"; return; } if (text.Contains("is valid")) { current.FullSigned = "Full-signed"; return; } if (text.Contains("is a delay-signed or test-signed")) { current.FullSigned = "Delay-signed or test-signed"; return; } if (text.Contains("32BITREQ : 1")) { current.Architecture = "x86"; return; } if (text.Contains("32BITREQ : 0")) { current.Architecture = "Any CPU"; return; } if (text.Contains("Signed : 1")) { current.Signed = "Signed"; return; } if (text.Contains("Signed : 0")) { current.Signed = "Unsigned"; return; } if (text.Contains("Failed to verify assembly -- Strong name validation failed.")) { current.FullSigned = "Strong name validation failed"; return; } Console.WriteLine(text); } private static void Highlight(string message, ConsoleColor color = ConsoleColor.Cyan, bool newLineAtEnd = true) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.Write(message); if (newLineAtEnd) { Console.WriteLine(); } Console.ForegroundColor = oldColor; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new GenericNamePartiallyWrittenSignatureHelpProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void NestedGenericUnterminated() { var markup = @" class G<T> { }; class C { void Foo() { G<G<int>$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WorkItem(544088)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void DeclaringGenericTypeWith1ParameterUnterminated() { var markup = @" class G<T> { }; class C { void Foo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void CallingGenericAsyncMethod() { var markup = @" using System.Threading.Tasks; class Program { void Main(string[] args) { Foo<$$ } Task<int> Foo<T>() { return Foo<T>(); } } "; var documentation = $@" {WorkspacesResources.Usage} int x = await Foo();"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpEditorResources.Awaitable}) Task<int> Program.Foo<T>()", documentation, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericMethod_BrowsableAlways() { var markup = @" class Program { void M() { new C().Foo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Foo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericMethod_BrowsableNever() { var markup = @" class Program { void M() { new C().Foo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Foo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new C().Foo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public void Foo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_GenericMethod_BrowsableMixed() { var markup = @" class Program { void M() { new C().Foo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Foo<T>(T x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Foo<T, U>(T x, U y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void GenericExtensionMethod() { var markup = @" interface IFoo { void Bar<T>(); } static class FooExtensions { public static void Bar<T1, T2>(this IFoo foo) { } } class Program { static void Main() { IFoo f = null; f.[|Bar<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpEditorResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0), }; // Extension methods are supported in Interactive/Script (yet). Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(544088)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokingGenericMethodWith1ParameterUnterminated() { var markup = @" class C { /// <summary> /// Method Foo /// </summary> /// <typeparam name=""T"">Method type parameter</typeparam> void Foo<T>() { } void Bar() { [|Foo<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()", "Method Foo", "Method type parameter", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerBracket() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<int,$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(1067933)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // foo<$$"; Test(markup); } } }
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace Neo4j.Driver { /// <summary> /// Provides a way to generate a <see cref="Config"/> instance fluently. /// </summary> public sealed class ConfigBuilder { private readonly Config _config; internal ConfigBuilder(Config config) { _config = config; } /// <summary> /// Builds the <see cref="Config"/> instance based on the previously internal set values. /// </summary> /// <remarks>> /// If no value was internal set for a property the defaults specified in <see cref="Config"/> will be used. /// </remarks> /// <returns>A <see cref="Config"/> instance.</returns> internal Config Build() { return _config; } /// <summary> /// Sets the <see cref="Config"/> to use TLS if <paramref name="level"/> is <c>Encrypted</c>. /// </summary> /// <param name="level"><see cref="EncryptionLevel.Encrypted"/> enables TLS for the connection, <see cref="EncryptionLevel.None"/> otherwise. See <see cref="EncryptionLevel"/> for more info</param>. /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithEncryptionLevel(EncryptionLevel level) { _config.NullableEncryptionLevel = level; return this; } /// <summary> /// Sets the <see cref="TrustManager"/> to use while establishing trust via TLS. /// The <paramref name="manager"/> will not take effect if <see cref="Config.EncryptionLevel"/> decides to use no TLS /// encryption on the connections. /// </summary> /// <param name="manager">A <see cref="TrustManager"/> instance.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> /// <remarks>We recommend using WithCertificateTrustPaths or WithCertificates</remarks> public ConfigBuilder WithTrustManager(TrustManager manager) { _config.TrustManager = manager; return this; } /// <summary> /// Sets the <see cref="Config"/> to use a given <see cref="ILogger"/> instance. /// </summary> /// <param name="logger">The <see cref="ILogger"/> instance to use, if <c>null</c> no logging will occur.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithLogger(ILogger logger) { _config.Logger = logger; return this; } /// <summary> /// Sets the size of the idle connection pool. /// </summary> /// <param name="size">The size of the <see cref="Config.MaxIdleConnectionPoolSize"/>, /// internal set to 0 will disable connection pooling.</param>. /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithMaxIdleConnectionPoolSize(int size) { _config.MaxIdleConnectionPoolSize = size; return this; } /// <summary> /// Sets the size of the connection pool. /// </summary> /// <param name="size">The size of the <see cref="Config.MaxConnectionPoolSize"/></param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithMaxConnectionPoolSize(int size) { _config.MaxConnectionPoolSize = size; return this; } /// <summary> /// Sets the maximum connection acquisition timeout for waiting for a connection to become available in idle connection pool /// when <see cref="Config.MaxConnectionPoolSize"/> is reached. /// </summary> /// <param name="timeSpan">The connection acquisition timeout.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithConnectionAcquisitionTimeout(TimeSpan timeSpan) { _config.ConnectionAcquisitionTimeout = timeSpan; return this; } /// <summary> /// Specify socket connection timeout. /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, or <see cref="Config.InfiniteInterval"/> to wait indefinitely. /// </summary> /// <param name="timeSpan">Represents the number of milliseconds to wait or <see cref="Config.InfiniteInterval"/> to wait indefinitely.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithConnectionTimeout(TimeSpan timeSpan) { _config.ConnectionTimeout = timeSpan; return this; } /// <summary> /// Enable socket to send keep alive pings on TCP level to prevent pooled socket connections from getting killed after leaving client idle for a long time. /// The interval of keep alive pings are internal set via your OS system. /// </summary> /// <param name="enable"></param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithSocketKeepAliveEnabled(bool enable) { _config.SocketKeepAlive = enable; return this; } /// <summary> /// Specify the maximum time transactions are allowed to retry via transaction functions. /// /// These methods will retry the given unit of work on <see cref="SessionExpiredException"/>, /// <see cref="TransientException"/> and <see cref="ServiceUnavailableException"/> /// with exponential backoff using initial delay of 1 second. /// Default value is 30 seconds. /// </summary> /// <param name="time">Specify the maximum retry time. </param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithMaxTransactionRetryTime(TimeSpan time) { _config.MaxTransactionRetryTime = time; return this; } /// <summary> /// Specify the connection idle timeout. /// The connection that has been idled in pool for longer than specified timeout will not be reused but closed. /// </summary> /// <param name="timeSpan">The max timespan that a connection can be reused after has been idle for.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithConnectionIdleTimeout(TimeSpan timeSpan) { _config.ConnectionIdleTimeout = timeSpan; return this; } /// <summary> /// Specify the maximum connection life time. /// The connection that has been created for longer than specified time will not be reused but closed. /// </summary> /// <param name="timeSpan">The max timespan that a connection can be reused after has been created for.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithMaxConnectionLifetime(TimeSpan timeSpan) { _config.MaxConnectionLifetime = timeSpan; return this; } /// <summary> /// Setting this option to true will enable ipv6 on socket connections. /// </summary> /// <param name="enable">true to enable ipv6, false to only support ipv4 addresses.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithIpv6Enabled(bool enable) { _config.Ipv6Enabled = enable; return this; } /// <summary> /// Gets or internal sets a custom server address resolver used by the routing driver to resolve the initial address used to create the driver. /// Such resolution happens: 1) during the very first rediscovery when driver is created. /// 2) when all the known routers from the current routing table have failed and driver needs to fallback to the initial address. /// </summary> /// <param name="resolver">The resolver, default to a resolver that simply pass the initial server address as it is.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithResolver(IServerAddressResolver resolver) { _config.Resolver = resolver; return this; } /// <summary> /// Specify the default read buffer size which the driver allocates for its internal buffers. /// </summary> /// <param name="defaultReadBufferSize">the buffer size</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithDefaultReadBufferSize(int defaultReadBufferSize) { _config.DefaultReadBufferSize = defaultReadBufferSize; return this; } /// <summary> /// Specify the size when internal read buffers reach, will be released for garbage collection. /// </summary> /// <param name="maxReadBufferSize">the buffer size</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> /// <remarks>If reading large records (nodes, relationships or paths) and experiencing too much garbage collection /// consider increasing this size to a reasonable amount depending on your data.</remarks> public ConfigBuilder WithMaxReadBufferSize(int maxReadBufferSize) { _config.MaxReadBufferSize = maxReadBufferSize; return this; } /// <summary> /// Specify the default write buffer size which the driver allocates for its internal buffers. /// </summary> /// <param name="defaultWriteBufferSize">the buffer size</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithDefaultWriteBufferSize(int defaultWriteBufferSize) { _config.DefaultWriteBufferSize = defaultWriteBufferSize; return this; } /// <summary> /// Specify the size when internal write buffers reach, will be released for garbage collection. /// </summary> /// <param name="maxWriteBufferSize">the buffer size</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> /// <remarks>If writing large values and experiencing too much garbage collection /// consider increasing this size to a reasonable amount depending on your data.</remarks> public ConfigBuilder WithMaxWriteBufferSize(int maxWriteBufferSize) { _config.MaxWriteBufferSize = maxWriteBufferSize; return this; } /// <summary> /// Sets the default fetch size. /// Since Bolt v4 (Neo4j 4.0+), the query running result (records) are pulled from server in batches. /// This fetch size defines how many records to pull in each batch. /// Use <see cref="Config.Infinite"/> to disable batching and always pull all records in one batch instead. /// </summary> /// <param name="size">The fetch size.</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithFetchSize(long size) { _config.FetchSize = size; return this; } internal ConfigBuilder WithMetricsEnabled(bool enabled) { _config.MetricsEnabled = enabled; return this; } /// <summary> /// Sets the userAgent. /// Used to get and set the User Agent string. If not used the default will be "neo4j-dotnet/x.y" /// where x is the major version and y is the minor version. /// </summary> /// <param name="userAgent">The user agent string</param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> public ConfigBuilder WithUserAgent(string userAgent) { _config.UserAgent = userAgent; return this; } /// <summary> /// Sets the rule for which Certificate Authority(CA) certificates to use when building trust with a server certificate. /// </summary> /// <param name="certificateTrustRule">The rule for validating server certificates when using encryption.</param> /// <param name="trustedCaCertificates"> /// Optional list of certificates to use to validate a server certificate. /// should only be set when <paramref name="certificateTrustRule"/> is <c>CertificateTrustRule.TrustList</c></param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> /// <remarks>Used in conjunction with <see cref="WithEncryptionLevel"/>. Not to be used when using a non-basic Uri Scheme(+s, +ssc) on <see cref="GraphDatabase"/></remarks> /// <exception cref="ArgumentException">Thrown when mismatch between certificateTrustRule and trustedCaCertificates.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when certificateTrustRule is not an expected enum.</exception> public ConfigBuilder WithCertificateTrustRule(CertificateTrustRule certificateTrustRule, IReadOnlyList<X509Certificate2> trustedCaCertificates = null) { _config.TrustManager = certificateTrustRule switch { CertificateTrustRule.TrustSystem when trustedCaCertificates != null => throw new ArgumentException($"{nameof(trustedCaCertificates)} is not valid when {nameof(certificateTrustRule)} is {nameof(CertificateTrustRule.TrustSystem)}"), CertificateTrustRule.TrustAny when trustedCaCertificates != null => throw new ArgumentException($"{nameof(trustedCaCertificates)} is not valid when {nameof(certificateTrustRule)} is {nameof(CertificateTrustRule.TrustAny)}"), CertificateTrustRule.TrustList when trustedCaCertificates == null || trustedCaCertificates.Count == 0 => throw new ArgumentException($"{nameof(trustedCaCertificates)} must not be null or empty when {nameof(certificateTrustRule)} is {nameof(CertificateTrustRule.TrustList)}"), CertificateTrustRule.TrustSystem => TrustManager.CreateChainTrust(), CertificateTrustRule.TrustList => TrustManager.CreateCertTrust(trustedCaCertificates), CertificateTrustRule.TrustAny => TrustManager.CreateInsecure(), _ => throw new ArgumentOutOfRangeException($"{certificateTrustRule} is not implemented in {nameof(ConfigBuilder)}.{nameof(WithCertificateTrustRule)}") }; return this; } /// <summary> /// Sets the rule for which Certificate Authority(CA) certificates to use when building trust with a server certificate. /// </summary> /// <param name="certificateTrustRule">The rule for validating server certificates when using encryption.</param> /// <param name="trustedCaCertificateFileNames"> /// Optional list of paths to certificates to use to validate a server certificate. /// should only be set when using <code>CertificateTrustRule.TrustList</code></param> /// <returns>An <see cref="ConfigBuilder"/> instance for further configuration options.</returns> /// <remarks>Used in conjunction with <see cref="WithEncryptionLevel"/>. Not to be used when using a non-basic Uri Scheme(+s, +ssc) on <see cref="GraphDatabase"/></remarks> /// <exception cref="ArgumentException">Thrown when mismatch between certificateTrustRule and trustedCaCertificateFileNames.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when certificateTrustRule is not an expected enum.</exception> public ConfigBuilder WithCertificateTrustRule(CertificateTrustRule certificateTrustRule, IReadOnlyList<string> trustedCaCertificateFileNames = null) { var certs = trustedCaCertificateFileNames?.Select(x => new X509Certificate2(x)).ToList(); return WithCertificateTrustRule(certificateTrustRule, certs); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.AccessControl; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32; using NuGet; using Splat; using Squirrel.Shell; namespace Squirrel { public sealed partial class UpdateManager : IUpdateManager, IEnableLogger { readonly string rootAppDirectory; readonly string applicationName; readonly IFileDownloader urlDownloader; readonly string updateUrlOrPath; IDisposable updateLock; public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); this.urlDownloader = urlDownloader ?? new FileDownloader(); if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName); return; } this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName); } public async Task<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, Action<int> progress = null) { var checkForUpdate = new CheckForUpdateImpl(rootAppDirectory); await acquireUpdateLock(); return await checkForUpdate.CheckForUpdate(Utility.LocalReleaseFileForAppDir(rootAppDirectory), updateUrlOrPath, ignoreDeltaUpdates, progress, urlDownloader); } public async Task DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null) { var downloadReleases = new DownloadReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await downloadReleases.DownloadReleases(updateUrlOrPath, releasesToDownload, progress, urlDownloader); } public async Task<string> ApplyReleases(UpdateInfo updateInfo, Action<int> progress = null) { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); return await applyReleases.ApplyReleases(updateInfo, false, false, progress); } public async Task FullInstall(bool silentInstall = false, Action<int> progress = null) { var updateInfo = await CheckForUpdate(); await DownloadReleases(updateInfo.ReleasesToApply); var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await applyReleases.ApplyReleases(updateInfo, silentInstall, true, progress); } public async Task FullUninstall() { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); this.KillAllExecutablesBelongingToPackage(); await applyReleases.FullUninstall(); } public Task<RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch) { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(uninstallCmd, quietSwitch); } public Task<RegistryKey> CreateUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(); } public void RemoveUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); installHelpers.RemoveUninstallerRegistryEntry(); } public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly, string programArguments = null, string icon = null) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.CreateShortcutsForExecutable(exeName, locations, updateOnly, programArguments, icon); } public Dictionary<ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments = null) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); return installHelpers.GetShortcutsForExecutable(exeName, locations, programArguments); } public void RemoveShortcutsForExecutable(string exeName, ShortcutLocation locations) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.RemoveShortcutsForExecutable(exeName, locations); } public SemanticVersion CurrentlyInstalledVersion(string executable = null) { executable = executable ?? Path.GetDirectoryName(typeof(UpdateManager).Assembly.Location); if (!executable.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase)) { return null; } var appDirName = executable.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) .FirstOrDefault(x => x.StartsWith("app-", StringComparison.OrdinalIgnoreCase)); if (appDirName == null) return null; return appDirName.ToSemanticVersion(); } public void KillAllExecutablesBelongingToPackage() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); installHelpers.KillAllProcessesBelongingToPackage(); } public string ApplicationName { get { return applicationName; } } public string RootAppDirectory { get { return rootAppDirectory; } } public bool IsInstalledApp { get { return Assembly.GetExecutingAssembly().Location.StartsWith(RootAppDirectory, StringComparison.OrdinalIgnoreCase); } } public void Dispose() { var disp = Interlocked.Exchange(ref updateLock, null); if (disp != null) { disp.Dispose(); } } static bool exiting = false; public static void RestartApp(string exeToStart = null, string arguments = null) { // NB: Here's how this method works: // // 1. We're going to pass the *name* of our EXE and the params to // Update.exe // 2. Update.exe is going to grab our PID (via getting its parent), // then wait for us to exit. // 3. We exit cleanly, dropping any single-instance mutexes or // whatever. // 4. Update.exe unblocks, then we launch the app again, possibly // launching a different version than we started with (this is why // we take the app's *name* rather than a full path) exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location); var argsArg = arguments != null ? String.Format("-a \"{0}\"", arguments) : ""; exiting = true; Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg)); // NB: We have to give update.exe some time to grab our PID, but // we can't use WaitForInputIdle because we probably don't have // whatever WaitForInputIdle considers a message loop. Thread.Sleep(500); Environment.Exit(0); } public static async Task<Process> RestartAppWhenExited(string exeToStart = null, string arguments = null) { // NB: Here's how this method works: // // 1. We're going to pass the *name* of our EXE and the params to // Update.exe // 2. Update.exe is going to grab our PID (via getting its parent), // then wait for us to exit. // 3. Return control and new Process back to caller and allow them to Exit as desired. // 4. After our process exits, Update.exe unblocks, then we launch the app again, possibly // launching a different version than we started with (this is why // we take the app's *name* rather than a full path) exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location); var argsArg = arguments != null ? String.Format("-a \"{0}\"", arguments) : ""; exiting = true; var updateProcess = Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg)); await Task.Delay(500); return updateProcess; } public static string GetLocalAppDataDirectory(string assemblyLocation = null) { // Try to divine our our own install location via reading tea leaves // // * We're Update.exe, running in the app's install folder // * We're Update.exe, running on initial install from SquirrelTemp // * We're a C# EXE with Squirrel linked in var assembly = Assembly.GetEntryAssembly(); if (assemblyLocation == null && assembly == null) { // dunno lol return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } assemblyLocation = assemblyLocation ?? assembly.Location; if (Path.GetFileName(assemblyLocation).Equals("update.exe", StringComparison.OrdinalIgnoreCase)) { // NB: Both the "SquirrelTemp" case and the "App's folder" case // mean that the root app dir is one up var oneFolderUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), ".."); return Path.GetFullPath(oneFolderUpFromAppFolder); } var twoFoldersUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..\\.."); return Path.GetFullPath(twoFoldersUpFromAppFolder); } ~UpdateManager() { if (updateLock != null && !exiting) { throw new Exception("You must dispose UpdateManager!"); } } Task<IDisposable> acquireUpdateLock() { if (updateLock != null) return Task.FromResult(updateLock); return Task.Run(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); IDisposable theLock; try { theLock = ModeDetector.InUnitTestRunner() ? Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000)); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; }); } static string getApplicationName() { var fi = new FileInfo(getUpdateExe()); return fi.Directory.Name; } static string getUpdateExe() { var assembly = Assembly.GetEntryAssembly(); // Are we update.exe? if (assembly != null && Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) && assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 && assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) { return Path.GetFullPath(assembly.Location); } assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe"); var target = new FileInfo(updateDotExe); if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?"); return target.FullName; } } }
#region License // Copyright (C) 2011-2016 Kazunori Sakamoto // // 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.Drawing; using System.Drawing.Imaging; using Paraiba.Drawing.Surfaces; using Paraiba.Wrap; namespace Paraiba.Drawing { public static class BitmapExtensionMethod { public static Bitmap ChangePixelFormat( this Bitmap bmp, PixelFormat format) { return bmp.Clone(new Rectangle(Point.Empty, bmp.Size), format); } public static Bitmap ChangePixelFormat( this Bitmap bmp, PixelFormat format, PixelFormat formatIfNotHasAlpha) { if ((bmp.Flags & (int)ImageFlags.HasAlpha) == 0) { return bmp.Clone(new Rectangle(Point.Empty, bmp.Size), format); } return bmp.Clone( new Rectangle(Point.Empty, bmp.Size), formatIfNotHasAlpha); } public static Bitmap Clone(this Bitmap bmp, PixelFormat format) { return bmp.Clone(new Rectangle(Point.Empty, bmp.Size), format); } public static void MakeTransparent( this Bitmap bmp, Point transparentColorPoint) { var x = transparentColorPoint.X; var y = transparentColorPoint.Y; bmp.MakeTransparent(bmp.GetPixel(x, y)); } public static bool TryMakeTransparent( this Bitmap bmp, Point transparentColorPoint) { var x = transparentColorPoint.X; var y = transparentColorPoint.Y; if (0 <= x && x < bmp.Width && 0 <= y && y < bmp.Height) { bmp.MakeTransparent(bmp.GetPixel(x, y)); return true; } return false; } public static void SetResolution(this Bitmap bmp) { bmp.SetResolution(96, 96); } public static T[] SplitTo<T>( this Image image, int chipWidth, int chipHeight, int maxCount, Func<Rectangle, T> createTFunc) { int imageWidth = image.Width; int nWidth = imageWidth / chipWidth; int nHeight = image.Height / chipHeight; var chips = new T[Math.Min(maxCount, nWidth * nHeight)]; imageWidth = chipWidth * nWidth; for (int i = 0, x = 0, y = 0; i < chips.Length; i++) { chips[i] = createTFunc(new Rectangle(x, y, chipWidth, chipHeight)); if (x < imageWidth) { x += chipWidth; } else { x = 0; y += chipHeight; } } return chips; } public static T[] SplitTo<T>( this Image image, int chipWidth, int chipHeight, Func<Rectangle, T> createTFunc) { int nWidth = image.Width / chipWidth; int nHeight = image.Height / chipHeight; var chips = new T[nWidth * nHeight]; for (int y = 0; y < nHeight; y++) { for (int x = 0; x < nWidth; x++) { chips[y * nWidth + x] = createTFunc( new Rectangle( x * chipWidth, y * chipHeight, chipWidth, chipHeight)); } } return chips; } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, int chipWidth, int chipHeight) { return bmp.SplitTo( chipWidth, chipHeight, rect => bmp.Clone(rect, bmp.PixelFormat)); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, int chipWidth, int chipHeight, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip; }); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => bmp.Clone(rect, bmp.PixelFormat)); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip; }); } public static Bitmap[] SplitToBitmaps(this Bitmap bmp, Size chipSize) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => bmp.Clone(rect, bmp.PixelFormat)); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, Size chipSize, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip; }); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, Size chipSize, int maxCount) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => bmp.Clone(rect, bmp.PixelFormat)); } public static Bitmap[] SplitToBitmaps( this Bitmap bmp, Size chipSize, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip; }); } public static Image[] SplitToImages( this Bitmap bmp, int chipWidth, int chipHeight) { return bmp.SplitTo( chipWidth, chipHeight, rect => (Image)bmp.Clone(rect, bmp.PixelFormat)); } public static Image[] SplitToImages( this Bitmap bmp, int chipWidth, int chipHeight, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return (Image)chip; }); } public static Image[] SplitToImages( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => (Image)bmp.Clone(rect, bmp.PixelFormat)); } public static Image[] SplitToImages( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return (Image)chip; }); } public static Image[] SplitToImages(this Bitmap bmp, Size chipSize) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => (Image)bmp.Clone(rect, bmp.PixelFormat)); } public static Image[] SplitToImages( this Bitmap bmp, Size chipSize, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return (Image)chip; }); } public static Image[] SplitToImages( this Bitmap bmp, Size chipSize, int maxCount) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => (Image)bmp.Clone(rect, bmp.PixelFormat)); } public static Image[] SplitToImages( this Bitmap bmp, Size chipSize, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return (Image)chip; }); } public static Surface[] SplitToSurfaces( this Bitmap bmp, int chipWidth, int chipHeight) { return bmp.SplitTo( chipWidth, chipHeight, rect => bmp.Clone(rect, bmp.PixelFormat).ToSurface()); } public static Surface[] SplitToSurfaces( this Bitmap bmp, int chipWidth, int chipHeight, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip.ToSurface(); }); } public static Surface[] SplitToSurfaces( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => bmp.Clone(rect, bmp.PixelFormat).ToSurface()); } public static Surface[] SplitToSurfaces( this Bitmap bmp, int chipWidth, int chipHeight, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipWidth, chipHeight, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip.ToSurface(); }); } public static Surface[] SplitToSurfaces(this Bitmap bmp, Size chipSize) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => bmp.Clone(rect, bmp.PixelFormat).ToSurface()); } public static Surface[] SplitToSurfaces( this Bitmap bmp, Size chipSize, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip.ToSurface(); }); } public static Surface[] SplitToSurfaces( this Bitmap bmp, Size chipSize, int maxCount) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => bmp.Clone(rect, bmp.PixelFormat).ToSurface()); } public static Surface[] SplitToSurfaces( this Bitmap bmp, Size chipSize, int maxCount, Point transparentColorPoint) { return bmp.SplitTo( chipSize.Width, chipSize.Height, maxCount, rect => { var chip = bmp.Clone(rect, bmp.PixelFormat); chip.TryMakeTransparent(transparentColorPoint); return chip.ToSurface(); }); } public static Surface ToSurface(this Bitmap bmp) { return new BitmapSurface(bmp); } public static Surface ToSurface(this Wrap<Bitmap> bmp) { return new BitmapSurface(bmp); } } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.BodyIndexFrameSource // public sealed partial class BodyIndexFrameSource : Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal BodyIndexFrameSource(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_BodyIndexFrameSource_AddRefObject(ref _pNative); } ~BodyIndexFrameSource() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_BodyIndexFrameSource_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_BodyIndexFrameSource_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<BodyIndexFrameSource>(_pNative); Windows_Kinect_BodyIndexFrameSource_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_BodyIndexFrameSource_get_FrameDescription(RootSystem.IntPtr pNative); public Windows.Kinect.FrameDescription FrameDescription { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("BodyIndexFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_BodyIndexFrameSource_get_FrameDescription(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Windows_Kinect_BodyIndexFrameSource_get_IsActive(RootSystem.IntPtr pNative); public bool IsActive { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("BodyIndexFrameSource"); } return Windows_Kinect_BodyIndexFrameSource_get_IsActive(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_BodyIndexFrameSource_get_KinectSensor(RootSystem.IntPtr pNative); public Windows.Kinect.KinectSensor KinectSensor { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("BodyIndexFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_BodyIndexFrameSource_get_KinectSensor(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.KinectSensor>(objectPointer, n => new Windows.Kinect.KinectSensor(n)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Kinect_FrameCapturedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>>> Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_FrameCapturedEventArgs_Delegate))] private static void Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs>> callbackList = null; Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<BodyIndexFrameSource>(pNative); var args = new Windows.Kinect.FrameCapturedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_BodyIndexFrameSource_add_FrameCaptured(RootSystem.IntPtr pNative, _Windows_Kinect_FrameCapturedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Kinect.FrameCapturedEventArgs> FrameCaptured { add { Helper.EventPump.EnsureInitialized(); Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Kinect_FrameCapturedEventArgs_Delegate(Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler); _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_BodyIndexFrameSource_add_FrameCaptured(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_BodyIndexFrameSource_add_FrameCaptured(_pNative, Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler, true); _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<BodyIndexFrameSource>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_BodyIndexFrameSource_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_BodyIndexFrameSource_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_BodyIndexFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_BodyIndexFrameSource_OpenReader(RootSystem.IntPtr pNative); public Windows.Kinect.BodyIndexFrameReader OpenReader() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("BodyIndexFrameSource"); } RootSystem.IntPtr objectPointer = Windows_Kinect_BodyIndexFrameSource_OpenReader(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyIndexFrameReader>(objectPointer, n => new Windows.Kinect.BodyIndexFrameReader(n)); } private void __EventCleanup() { { Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_FrameCapturedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_BodyIndexFrameSource_add_FrameCaptured(_pNative, Windows_Kinect_FrameCapturedEventArgs_Delegate_Handler, true); } _Windows_Kinect_FrameCapturedEventArgs_Delegate_Handle.Free(); } } } { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_BodyIndexFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
using System; using System.Linq; using Content.Client.UserInterface.Stylesheets; using Content.Shared.Preferences.Appearance; using JetBrains.Annotations; using Robust.Client.GameObjects.Components.UserInterface; using Robust.Client.ResourceManagement; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Shared.GameObjects.Components.Renderable; using Robust.Shared.GameObjects.Components.UserInterface; using Robust.Shared.Localization; using Robust.Shared.Maths; using static Content.Shared.GameObjects.Components.SharedMagicMirrorComponent; using static Content.Client.StaticIoC; namespace Content.Client.GameObjects.Components { [UsedImplicitly] public class MagicMirrorBoundUserInterface : BoundUserInterface { private MagicMirrorWindow _window; public MagicMirrorBoundUserInterface(ClientUserInterfaceComponent owner, object uiKey) : base(owner, uiKey) { } protected override void Open() { base.Open(); _window = new MagicMirrorWindow(this); _window.OnClose += Close; _window.Open(); } protected override void ReceiveMessage(BoundUserInterfaceMessage message) { switch (message) { case MagicMirrorInitialDataMessage initialData: _window.SetInitialData(initialData); break; } } internal void HairSelected(string name, bool isFacialHair) { SendMessage(new HairSelectedMessage(name, isFacialHair)); } internal void HairColorSelected(Color color, bool isFacialHair) { SendMessage(new HairColorSelectedMessage((color.RByte, color.GByte, color.BByte), isFacialHair)); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _window.Dispose(); } } } public class FacialHairStylePicker : HairStylePicker { public override void Populate() { var humanFacialHairRSIPath = SharedSpriteComponent.TextureRoot / "Mobs/Customization/human_facial_hair.rsi"; var humanFacialHairRSI = ResC.GetResource<RSIResource>(humanFacialHairRSIPath).RSI; var styles = HairStyles.FacialHairStylesMap.ToList(); styles.Sort(HairStyles.FacialHairStyleComparer); foreach (var (styleName, styleState) in HairStyles.FacialHairStylesMap) { Items.AddItem(styleName, humanFacialHairRSI[styleState].Frame0); } } } public class HairStylePicker : Control { public event Action<Color> OnHairColorPicked; public event Action<string> OnHairStylePicked; protected readonly ItemList Items; private readonly ColorSlider _colorSliderR; private readonly ColorSlider _colorSliderG; private readonly ColorSlider _colorSliderB; private Color _lastColor; public void SetData(Color color, string styleName) { _lastColor = color; _colorSliderR.ColorValue = color.RByte; _colorSliderG.ColorValue = color.GByte; _colorSliderB.ColorValue = color.BByte; foreach (var item in Items) { item.Selected = item.Text == styleName; } UpdateStylePickerColor(); } private void UpdateStylePickerColor() { foreach (var item in Items) { item.IconModulate = _lastColor; } } public HairStylePicker() { var vBox = new VBoxContainer(); AddChild(vBox); vBox.AddChild(_colorSliderR = new ColorSlider(StyleNano.StyleClassSliderRed)); vBox.AddChild(_colorSliderG = new ColorSlider(StyleNano.StyleClassSliderGreen)); vBox.AddChild(_colorSliderB = new ColorSlider(StyleNano.StyleClassSliderBlue)); Action colorValueChanged = ColorValueChanged; _colorSliderR.OnValueChanged += colorValueChanged; _colorSliderG.OnValueChanged += colorValueChanged; _colorSliderB.OnValueChanged += colorValueChanged; Items = new ItemList { SizeFlagsVertical = SizeFlags.FillExpand, CustomMinimumSize = (300, 250) }; vBox.AddChild(Items); Items.OnItemSelected += ItemSelected; } private void ColorValueChanged() { var newColor = new Color( _colorSliderR.ColorValue, _colorSliderG.ColorValue, _colorSliderB.ColorValue ); OnHairColorPicked?.Invoke(newColor); _lastColor = newColor; UpdateStylePickerColor(); } public virtual void Populate() { var humanHairRSIPath = SharedSpriteComponent.TextureRoot / "Mobs/Customization/human_hair.rsi"; var humanHairRSI = ResC.GetResource<RSIResource>(humanHairRSIPath).RSI; var styles = HairStyles.HairStylesMap.ToList(); styles.Sort(HairStyles.HairStyleComparer); foreach (var (styleName, styleState) in styles) { Items.AddItem(styleName, humanHairRSI[styleState].Frame0); } } private void ItemSelected(ItemList.ItemListSelectedEventArgs args) { OnHairStylePicked?.Invoke(Items[args.ItemIndex].Text); } private sealed class ColorSlider : Control { private readonly Slider _slider; private readonly LineEdit _textBox; private byte _colorValue; private bool _ignoreEvents; public event Action OnValueChanged; public byte ColorValue { get => _colorValue; set { _ignoreEvents = true; _colorValue = value; _slider.Value = value; _textBox.Text = value.ToString(); _ignoreEvents = false; } } public ColorSlider(string styleClass) { _slider = new Slider { StyleClasses = {styleClass}, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsVertical = SizeFlags.ShrinkCenter, MaxValue = byte.MaxValue }; _textBox = new LineEdit { CustomMinimumSize = (50, 0) }; AddChild(new HBoxContainer { Children = { _slider, _textBox } }); _slider.OnValueChanged += _ => { if (_ignoreEvents) { return; } _colorValue = (byte) _slider.Value; _textBox.Text = _colorValue.ToString(); OnValueChanged?.Invoke(); }; _textBox.OnTextChanged += ev => { if (_ignoreEvents) { return; } if (int.TryParse(ev.Text, out var result)) { result = MathHelper.Clamp(result, 0, byte.MaxValue); _ignoreEvents = true; _colorValue = (byte) result; _slider.Value = result; _ignoreEvents = false; OnValueChanged?.Invoke(); } }; } } } public class MagicMirrorWindow : SS14Window { private readonly HairStylePicker _hairStylePicker; private readonly FacialHairStylePicker _facialHairStylePicker; protected override Vector2? CustomSize => (500, 360); public MagicMirrorWindow(MagicMirrorBoundUserInterface owner) { Title = Loc.GetString("Magic Mirror"); _hairStylePicker = new HairStylePicker {SizeFlagsHorizontal = SizeFlags.FillExpand}; _hairStylePicker.Populate(); _hairStylePicker.OnHairStylePicked += newStyle => owner.HairSelected(newStyle, false); _hairStylePicker.OnHairColorPicked += newColor => owner.HairColorSelected(newColor, false); _facialHairStylePicker = new FacialHairStylePicker {SizeFlagsHorizontal = SizeFlags.FillExpand}; _facialHairStylePicker.Populate(); _facialHairStylePicker.OnHairStylePicked += newStyle => owner.HairSelected(newStyle, true); _facialHairStylePicker.OnHairColorPicked += newColor => owner.HairColorSelected(newColor, true); Contents.AddChild(new HBoxContainer { SeparationOverride = 8, Children = {_hairStylePicker, _facialHairStylePicker} }); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _hairStylePicker.Dispose(); _facialHairStylePicker.Dispose(); } } public void SetInitialData(MagicMirrorInitialDataMessage initialData) { _facialHairStylePicker.SetData(initialData.FacialHairColor, initialData.FacialHairName); _hairStylePicker.SetData(initialData.HairColor, initialData.HairName); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; using tk2dEditor.SpriteCollectionEditor; namespace tk2dEditor.SpriteCollectionEditor { public interface IEditorHost { void OnSpriteCollectionChanged(bool retainSelection); void OnSpriteCollectionSortChanged(); Texture2D GetTextureForSprite(int spriteId); SpriteCollectionProxy SpriteCollection { get; } int InspectorWidth { get; } SpriteView SpriteView { get; } void SelectSpritesFromList(int[] indices); void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds); void Commit(); } public class SpriteCollectionEditorEntry { public enum Type { None, Sprite, SpriteSheet, Font, MaxValue } public string name; public int index; public Type type; public bool selected = false; // list management public int listIndex; // index into the currently active list public int selectionKey; // a timestamp of when the entry was selected, to decide the last selected one } } public class tk2dSpriteCollectionEditorPopup : EditorWindow, IEditorHost { tk2dSpriteCollection _spriteCollection; // internal tmp var SpriteView spriteView; SettingsView settingsView; FontView fontView; SpriteSheetView spriteSheetView; // sprite collection we're editing SpriteCollectionProxy spriteCollectionProxy = null; public SpriteCollectionProxy SpriteCollection { get { return spriteCollectionProxy; } } public SpriteView SpriteView { get { return spriteView; } } // This lists all entries List<SpriteCollectionEditorEntry> entries = new List<SpriteCollectionEditorEntry>(); // This lists all selected entries List<SpriteCollectionEditorEntry> selectedEntries = new List<SpriteCollectionEditorEntry>(); // Callback when a sprite collection is changed and the selection needs to be refreshed public void OnSpriteCollectionChanged(bool retainSelection) { var oldSelection = selectedEntries.ToArray(); PopulateEntries(); if (retainSelection) { searchFilter = ""; // name may have changed foreach (var selection in oldSelection) { foreach (var entry in entries) { if (entry.type == selection.type && entry.index == selection.index) { entry.selected = true; break; } } } UpdateSelection(); } } public void SelectSpritesFromList(int[] indices) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); // Clear selection foreach (var entry in entries) entry.selected = false; // Create new selection foreach (var index in indices) { foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == index) { entry.selected = true; selectedEntries.Add(entry); break; } } } } public void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); foreach (var entry in entries) { entry.selected = (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == spriteSheetId); if (entry.selected) { spriteSheetView.Select(spriteCollectionProxy.spriteSheets[spriteSheetId], spriteIds); } } UpdateSelection(); } void UpdateSelection() { // clear settings view if its selected settingsView.show = false; selectedEntries = (from entry in entries where entry.selected == true orderby entry.selectionKey select entry).ToList(); } void ClearSelection() { entries.ForEach((a) => a.selected = false); UpdateSelection(); } // Callback when a sprite collection needs resorting public static bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; } // Callback when a sort criteria is changed public void OnSpriteCollectionSortChanged() { if (searchFilter.Length > 0) { // re-sort list entries = (from entry in entries where Contains(entry.name, searchFilter) select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } else { // re-sort list entries = (from entry in entries select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } for (int i = 0; i < entries.Count; ++i) entries[i].listIndex = i; } public int InspectorWidth { get { return tk2dPreferences.inst.spriteCollectionInspectorWidth; } } // populate the entries struct for display in the listbox void PopulateEntries() { entries = new List<SpriteCollectionEditorEntry>(); selectedEntries = new List<SpriteCollectionEditorEntry>(); if (spriteCollectionProxy == null) return; for (int spriteIndex = 0; spriteIndex < spriteCollectionProxy.textureParams.Count; ++spriteIndex) { var sprite = spriteCollectionProxy.textureParams[spriteIndex]; var spriteSourceTexture = sprite.texture; if (spriteSourceTexture == null && sprite.name.Length == 0) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = sprite.name; if (sprite.texture == null) { newEntry.name += " (missing)"; } newEntry.index = spriteIndex; newEntry.type = SpriteCollectionEditorEntry.Type.Sprite; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.spriteSheets.Count; ++i) { var spriteSheet = spriteCollectionProxy.spriteSheets[i]; if (!spriteSheet.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = spriteSheet.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.SpriteSheet; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.fonts.Count; ++i) { var font = spriteCollectionProxy.fonts[i]; if (!font.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = font.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.Font; entries.Add(newEntry); } OnSpriteCollectionSortChanged(); selectedEntries = new List<SpriteCollectionEditorEntry>(); } public void SetGenerator(tk2dSpriteCollection spriteCollection) { this._spriteCollection = spriteCollection; this.firstRun = true; spriteCollectionProxy = new SpriteCollectionProxy(spriteCollection); PopulateEntries(); } public void SetGeneratorAndSelectedSprite(tk2dSpriteCollection spriteCollection, int selectedSprite) { searchFilter = ""; SetGenerator(spriteCollection); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == selectedSprite) { entry.selected = true; break; } } UpdateSelection(); } int cachedSpriteId = -1; Texture2D cachedSpriteTexture = null; // Returns a texture for a given sprite, if the sprite is a region sprite, a new texture is returned public Texture2D GetTextureForSprite(int spriteId) { var param = spriteCollectionProxy.textureParams[spriteId]; if (spriteId != cachedSpriteId) { ClearTextureCache(); cachedSpriteId = spriteId; } if (param.extractRegion) { if (cachedSpriteTexture == null) { var tex = param.texture; cachedSpriteTexture = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { cachedSpriteTexture.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } cachedSpriteTexture.Apply(); } return cachedSpriteTexture; } else { return param.texture; } } void ClearTextureCache() { if (cachedSpriteId != -1) cachedSpriteId = -1; if (cachedSpriteTexture != null) { DestroyImmediate(cachedSpriteTexture); cachedSpriteTexture = null; } } void OnEnable() { if (_spriteCollection != null) { SetGenerator(_spriteCollection); } spriteView = new SpriteView(this); settingsView = new SettingsView(this); fontView = new FontView(this); spriteSheetView = new SpriteSheetView(this); } void OnDisable() { ClearTextureCache(); _spriteCollection = null; } void OnDestroy() { tk2dSpriteThumbnailCache.Done(); tk2dEditorSkin.Done(); } string searchFilter = ""; void DrawToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); // LHS GUILayout.BeginHorizontal(GUILayout.Width(leftBarWidth - 6)); // Create Button GUIContent createButton = new GUIContent("Create"); Rect createButtonRect = GUILayoutUtility.GetRect(createButton, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false)); if (GUI.Button(createButtonRect, createButton, EditorStyles.toolbarDropDown)) { GUIUtility.hotControl = 0; GUIContent[] menuItems = new GUIContent[] { new GUIContent("Sprite Sheet"), new GUIContent("Font") }; EditorUtility.DisplayCustomMenu(createButtonRect, menuItems, -1, delegate(object userData, string[] options, int selected) { switch (selected) { case 0: int addedSpriteSheetIndex = spriteCollectionProxy.FindOrCreateEmptySpriteSheetSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == addedSpriteSheetIndex) entry.selected = true; } UpdateSelection(); break; case 1: if (SpriteCollection.allowMultipleAtlases) { EditorUtility.DisplayDialog("Create Font", "Adding fonts to sprite collections isn't allowed when multi atlas spanning is enabled. " + "Please disable it and try again.", "Ok"); } else { int addedFontIndex = spriteCollectionProxy.FindOrCreateEmptyFontSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Font && entry.index == addedFontIndex) entry.selected = true; } UpdateSelection(); } break; } } , null); } // Filter box GUILayout.Space(8); string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.ExpandWidth(true)); if (newSearchFilter != searchFilter) { searchFilter = newSearchFilter; PopulateEntries(); } if (searchFilter.Length > 0) { if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false))) { searchFilter = ""; PopulateEntries(); } } else { GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap); } GUILayout.EndHorizontal(); // Label if (_spriteCollection != null) GUILayout.Label(_spriteCollection.name); // RHS GUILayout.FlexibleSpace(); // Always in settings view when empty if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { GUILayout.Toggle(true, "Settings", EditorStyles.toolbarButton); } else { bool newSettingsView = GUILayout.Toggle(settingsView.show, "Settings", EditorStyles.toolbarButton); if (newSettingsView != settingsView.show) { ClearSelection(); settingsView.show = newSettingsView; } } if (GUILayout.Button("Revert", EditorStyles.toolbarButton) && spriteCollectionProxy != null && EditorUtility.DisplayDialog("Revert sprite collection", "Are you sure you want to revert changes made to this sprite collection?", "Yes", "Cancel")) { spriteCollectionProxy.CopyFromSource(); OnSpriteCollectionChanged(false); } if (GUILayout.Button("Commit", EditorStyles.toolbarButton) && spriteCollectionProxy != null) Commit(); GUILayout.EndHorizontal(); } public void Commit() { spriteCollectionProxy.DeleteUnusedData(); spriteCollectionProxy.CopyToTarget(); tk2dSpriteCollectionBuilder.ResetCurrentBuild(); if (!tk2dSpriteCollectionBuilder.Rebuild(_spriteCollection)) { EditorUtility.DisplayDialog("Failed to commit sprite collection", "Please check the console for more details.", "Ok"); } spriteCollectionProxy.CopyFromSource(); } void HandleListKeyboardShortcuts(int controlId) { Event ev = Event.current; if (ev.type == EventType.KeyDown && (GUIUtility.keyboardControl == controlId || GUIUtility.keyboardControl == 0) && entries != null && entries.Count > 0) { int selectedIndex = 0; foreach (var e in entries) { if (e.selected) break; selectedIndex++; } int newSelectedIndex = selectedIndex; switch (ev.keyCode) { case KeyCode.Home: newSelectedIndex = 0; break; case KeyCode.End: newSelectedIndex = entries.Count - 1; break; case KeyCode.UpArrow: newSelectedIndex = Mathf.Max(selectedIndex - 1, 0); break; case KeyCode.DownArrow: newSelectedIndex = Mathf.Min(selectedIndex + 1, entries.Count - 1); break; case KeyCode.PageUp: newSelectedIndex = Mathf.Max(selectedIndex - 10, 0); break; case KeyCode.PageDown: newSelectedIndex = Mathf.Min(selectedIndex + 10, entries.Count - 1); break; } if (newSelectedIndex != selectedIndex) { for (int i = 0; i < entries.Count; ++i) entries[i].selected = (i == newSelectedIndex); UpdateSelection(); Repaint(); ev.Use(); } } } Vector2 spriteListScroll = Vector2.zero; int spriteListSelectionKey = 0; void DrawSpriteList() { if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { DrawDropZone(); return; } int spriteListControlId = GUIUtility.GetControlID("tk2d.SpriteList".GetHashCode(), FocusType.Keyboard); HandleListKeyboardShortcuts(spriteListControlId); spriteListScroll = GUILayout.BeginScrollView(spriteListScroll, GUILayout.Width(leftBarWidth)); bool multiSelectKey = (Application.platform == RuntimePlatform.OSXEditor)?Event.current.command:Event.current.control; bool shiftSelectKey = Event.current.shift; bool selectionChanged = false; SpriteCollectionEditorEntry.Type lastType = SpriteCollectionEditorEntry.Type.None; // Run through the list, measure total height // Its significantly faster with loads of sprites in there. int height = 0; int labelHeight = (int)tk2dEditorSkin.SC_ListBoxSectionHeader.CalcHeight(GUIContent.none, 100); int itemHeight = (int)tk2dEditorSkin.SC_ListBoxItem.CalcHeight(GUIContent.none, 100); int spacing = 8; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) height += spacing; height += labelHeight; lastType = entry.type; } height += itemHeight; } Rect rect = GUILayoutUtility.GetRect(1, height, GUILayout.ExpandWidth(true)); int width = Mathf.Max((int)rect.width, 100); int y = 0; // Second pass, just draw what is visible // Don't care about the section labels, theres only a max of 4 of those. lastType = SpriteCollectionEditorEntry.Type.None; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) y += spacing; else GUI.SetNextControlName("firstLabel"); GUI.Label(new Rect(0, y, width, labelHeight), GetEntryTypeString(entry.type), tk2dEditorSkin.SC_ListBoxSectionHeader); y += labelHeight; lastType = entry.type; } bool newSelected = entry.selected; float realY = y - spriteListScroll.y + itemHeight; if (realY > 0 && realY < Screen.height) { // screen.height is wrong, but is conservative newSelected = GUI.Toggle(new Rect(0, y, width, itemHeight), entry.selected, entry.name, tk2dEditorSkin.SC_ListBoxItem); } y += itemHeight; if (newSelected != entry.selected) { GUI.FocusControl("firstLabel"); entry.selectionKey = spriteListSelectionKey++; if (multiSelectKey) { // Only allow multiselection with sprites bool selectionAllowed = entry.type == SpriteCollectionEditorEntry.Type.Sprite; foreach (var e in entries) { if (e != entry && e.selected && e.type != entry.type) { selectionAllowed = false; break; } } if (selectionAllowed) { entry.selected = newSelected; selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } else if (shiftSelectKey) { // find first selected entry in list int firstSelection = int.MaxValue; foreach (var e in entries) { if (e.selected && e.listIndex < firstSelection) { firstSelection = e.listIndex; } } int lastSelection = entry.listIndex; if (lastSelection < firstSelection) { lastSelection = firstSelection; firstSelection = entry.listIndex; } // Filter for multiselection if (entry.type == SpriteCollectionEditorEntry.Type.Sprite) { for (int i = firstSelection; i <= lastSelection; ++i) { if (entries[i].type != entry.type) { firstSelection = entry.listIndex; lastSelection = entry.listIndex; } } } else { firstSelection = lastSelection = entry.listIndex; } foreach (var e in entries) { e.selected = (e.listIndex >= firstSelection && e.listIndex <= lastSelection); } selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } } if (selectionChanged) { GUIUtility.keyboardControl = spriteListControlId; UpdateSelection(); Repaint(); } GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); tk2dPreferences.inst.spriteCollectionListWidth = (int)tk2dGuiUtility.DragableHandle(4819283, viewRect, tk2dPreferences.inst.spriteCollectionListWidth, tk2dGuiUtility.DragDirection.Horizontal); } bool IsValidDragPayload() { int idx = 0; foreach (var v in DragAndDrop.objectReferences) { var type = v.GetType(); if (type == typeof(Texture2D)) { return true; } #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7) else if (type == typeof(UnityEngine.Object) && System.IO.Directory.Exists(DragAndDrop.paths[idx])) #else else if (type == typeof(UnityEditor.DefaultAsset) && System.IO.Directory.Exists(DragAndDrop.paths[idx])) #endif { return true; } ++idx; } return false; } string GetEntryTypeString(SpriteCollectionEditorEntry.Type kind) { switch (kind) { case SpriteCollectionEditorEntry.Type.Sprite: return "Sprites"; case SpriteCollectionEditorEntry.Type.SpriteSheet: return "Sprite Sheets"; case SpriteCollectionEditorEntry.Type.Font: return "Fonts"; } Debug.LogError("Unhandled type"); return ""; } bool PromptImportDuplicate(string title, string message) { return EditorUtility.DisplayDialog(title, message, "Ignore", "Create Copy"); } void HandleDroppedPayload(Object[] objects) { bool hasDuplicates = false; foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if (tex != null) { if (spriteCollectionProxy.FindSpriteBySource(tex) != -1) { hasDuplicates = true; } } } bool cloneDuplicates = false; if (hasDuplicates && EditorUtility.DisplayDialog("Duplicate textures detected.", "One or more textures is already in the collection. What do you want to do with the duplicates?", "Clone", "Ignore")) { cloneDuplicates = true; } List<int> addedIndices = new List<int>(); foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if ((tex != null) && (cloneDuplicates || spriteCollectionProxy.FindSpriteBySource(tex) == -1)) { string name = spriteCollectionProxy.FindUniqueTextureName(tex.name); int slot = spriteCollectionProxy.FindOrCreateEmptySpriteSlot(); spriteCollectionProxy.textureParams[slot].name = name; spriteCollectionProxy.textureParams[slot].colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; spriteCollectionProxy.textureParams[slot].texture = (Texture2D)obj; addedIndices.Add(slot); } } // And now select them searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && addedIndices.IndexOf(entry.index) != -1) entry.selected = true; } UpdateSelection(); } // recursively find textures in path List<Object> AddTexturesInPath(string path) { List<Object> localObjects = new List<Object>(); foreach (var q in System.IO.Directory.GetFiles(path)) { string f = q.Replace('\\', '/'); System.IO.FileInfo fi = new System.IO.FileInfo(f); if (fi.Extension.ToLower() == ".meta") continue; Object obj = AssetDatabase.LoadAssetAtPath(f, typeof(Texture2D)); if (obj != null) localObjects.Add(obj); } foreach (var q in System.IO.Directory.GetDirectories(path)) { string d = q.Replace('\\', '/'); localObjects.AddRange(AddTexturesInPath(d)); } return localObjects; } int leftBarWidth { get { return tk2dPreferences.inst.spriteCollectionListWidth; } } Object[] deferredDroppedObjects; void DrawDropZone() { GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.Width(leftBarWidth), GUILayout.ExpandHeight(true)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (DragAndDrop.objectReferences.Length == 0 && !SpriteCollection.Empty) GUILayout.Label("Drop sprite here", tk2dEditorSkin.SC_DropBox); else GUILayout.Label("Drop sprites here", tk2dEditorSkin.SC_DropBox); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); Rect rect = new Rect(0, 0, leftBarWidth, Screen.height); if (rect.Contains(Event.current.mousePosition)) { switch (Event.current.type) { case EventType.DragUpdated: if (IsValidDragPayload()) DragAndDrop.visualMode = DragAndDropVisualMode.Copy; else DragAndDrop.visualMode = DragAndDropVisualMode.None; break; case EventType.DragPerform: var droppedObjectsList = new List<Object>(); for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i) { var type = DragAndDrop.objectReferences[i].GetType(); if (type == typeof(Texture2D)) { droppedObjectsList.Add(DragAndDrop.objectReferences[i]); } #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9) else if (type == typeof(UnityEngine.Object) && System.IO.Directory.Exists(DragAndDrop.paths[i])) #else else if (type == typeof(UnityEditor.DefaultAsset) && System.IO.Directory.Exists(DragAndDrop.paths[i])) #endif { droppedObjectsList.AddRange(AddTexturesInPath(DragAndDrop.paths[i])); } } deferredDroppedObjects = droppedObjectsList.ToArray(); Repaint(); break; } } } bool dragging = false; bool currentDraggingValue = false; bool firstRun = true; List<UnityEngine.Object> assetsInResources = new List<UnityEngine.Object>(); bool InResources(UnityEngine.Object obj) { return AssetDatabase.GetAssetPath(obj).ToLower().IndexOf("/resources/") != -1; } void CheckForAssetsInResources() { assetsInResources.Clear(); foreach (tk2dSpriteCollectionDefinition tex in SpriteCollection.textureParams) { if (tex.texture == null) continue; if (InResources(tex.texture) && assetsInResources.IndexOf(tex.texture) == -1) assetsInResources.Add(tex.texture); } foreach (tk2dSpriteCollectionFont font in SpriteCollection.fonts) { if (font.texture != null && InResources(font.texture) && assetsInResources.IndexOf(font.texture) == -1) assetsInResources.Add(font.texture); if (font.bmFont != null && InResources(font.bmFont) && assetsInResources.IndexOf(font.bmFont) == -1) assetsInResources.Add(font.bmFont); } } Vector2 assetWarningScroll = Vector2.zero; bool HandleAssetsInResources() { if (firstRun && SpriteCollection != null) { CheckForAssetsInResources(); firstRun = false; } if (assetsInResources.Count > 0) { tk2dGuiUtility.InfoBox("Warning: The following assets are in one or more resources directories.\n" + "These files will be included in the build.", tk2dGuiUtility.WarningLevel.Warning); assetWarningScroll = GUILayout.BeginScrollView(assetWarningScroll, GUILayout.ExpandWidth(true)); foreach (UnityEngine.Object obj in assetsInResources) { EditorGUILayout.ObjectField(obj, typeof(UnityEngine.Object), false); } GUILayout.EndScrollView(); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Ok", GUILayout.MinWidth(100))) { assetsInResources.Clear(); Repaint(); } GUILayout.EndHorizontal(); return true; } return false; } void OnGUI() { if (Event.current.type == EventType.DragUpdated) { if (IsValidDragPayload()) dragging = true; } else if (Event.current.type == EventType.DragExited) { dragging = false; Repaint(); } else { if (currentDraggingValue != dragging) { currentDraggingValue = dragging; } } if (Event.current.type == EventType.Layout && deferredDroppedObjects != null) { HandleDroppedPayload(deferredDroppedObjects); deferredDroppedObjects = null; } if (HandleAssetsInResources()) return; GUILayout.BeginVertical(); DrawToolbar(); GUILayout.BeginHorizontal(); if (currentDraggingValue) DrawDropZone(); else DrawSpriteList(); if (settingsView.show || (spriteCollectionProxy != null && spriteCollectionProxy.Empty)) settingsView.Draw(); else if (fontView.Draw(selectedEntries)) { } else if (spriteSheetView.Draw(selectedEntries)) { } else spriteView.Draw(selectedEntries); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
// --------------------------------------------------------------------------- // <copyright file="TimeZoneTransition.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the TimeZoneTransition class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents the base class for all time zone transitions. /// </summary> internal class TimeZoneTransition : ComplexProperty { private const string PeriodTarget = "Period"; private const string GroupTarget = "Group"; private TimeZoneDefinition timeZoneDefinition; private TimeZonePeriod targetPeriod; private TimeZoneTransitionGroup targetGroup; /// <summary> /// Creates a time zone period transition of the appropriate type given an XML element name. /// </summary> /// <param name="timeZoneDefinition">The time zone definition to which the transition will belong.</param> /// <param name="xmlElementName">The XML element name.</param> /// <returns>A TimeZonePeriodTransition instance.</returns> internal static TimeZoneTransition Create(TimeZoneDefinition timeZoneDefinition, string xmlElementName) { switch (xmlElementName) { case XmlElementNames.AbsoluteDateTransition: return new AbsoluteDateTransition(timeZoneDefinition); case XmlElementNames.RecurringDayTransition: return new RelativeDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.RecurringDateTransition: return new AbsoluteDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.Transition: return new TimeZoneTransition(timeZoneDefinition); default: throw new ServiceLocalException( string.Format( Strings.UnknownTimeZonePeriodTransitionType, xmlElementName)); } } /// <summary> /// Creates a time zone transition based on the specified transition time. /// </summary> /// <param name="timeZoneDefinition">The time zone definition that will own the transition.</param> /// <param name="targetPeriod">The period the transition will target.</param> /// <param name="transitionTime">The transition time to initialize from.</param> /// <returns>A TimeZoneTransition.</returns> internal static TimeZoneTransition CreateTimeZoneTransition( TimeZoneDefinition timeZoneDefinition, TimeZonePeriod targetPeriod, TimeZoneInfo.TransitionTime transitionTime) { TimeZoneTransition transition; if (transitionTime.IsFixedDateRule) { transition = new AbsoluteDayOfMonthTransition(timeZoneDefinition, targetPeriod); } else { transition = new RelativeDayOfMonthTransition(timeZoneDefinition, targetPeriod); } transition.InitializeFromTransitionTime(transitionTime); return transition; } /// <summary> /// Gets the XML element name associated with the transition. /// </summary> /// <returns>The XML element name associated with the transition.</returns> internal virtual string GetXmlElementName() { return XmlElementNames.Transition; } /// <summary> /// Creates a time zone transition time. /// </summary> /// <returns>A TimeZoneInfo.TransitionTime.</returns> internal virtual TimeZoneInfo.TransitionTime CreateTransitionTime() { throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition); } /// <summary> /// Initializes this transition based on the specified transition time. /// </summary> /// <param name="transitionTime">The transition time to initialize from.</param> internal virtual void InitializeFromTransitionTime(TimeZoneInfo.TransitionTime transitionTime) { } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.To: string targetKind = reader.ReadAttributeValue(XmlAttributeNames.Kind); string targetId = reader.ReadElementValue(); switch (targetKind) { case TimeZoneTransition.PeriodTarget: if (!this.timeZoneDefinition.Periods.TryGetValue(targetId, out this.targetPeriod)) { throw new ServiceLocalException( string.Format( Strings.PeriodNotFound, targetId)); } break; case TimeZoneTransition.GroupTarget: if (!this.timeZoneDefinition.TransitionGroups.TryGetValue(targetId, out this.targetGroup)) { throw new ServiceLocalException( string.Format( Strings.TransitionGroupNotFound, targetId)); } break; default: throw new ServiceLocalException(Strings.UnsupportedTimeZonePeriodTransitionTarget); } return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { base.LoadFromJson(jsonProperty, service); foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.To: string targetKind = jsonProperty.ReadAsJsonObject(key).ReadAsString(XmlAttributeNames.Kind); string targetId = jsonProperty.ReadAsJsonObject(key).ReadAsString(XmlElementNames.Value); switch (targetKind) { case TimeZoneTransition.PeriodTarget: if (!this.timeZoneDefinition.Periods.TryGetValue(targetId, out this.targetPeriod)) { throw new ServiceLocalException( string.Format( Strings.PeriodNotFound, targetId)); } break; case TimeZoneTransition.GroupTarget: if (!this.timeZoneDefinition.TransitionGroups.TryGetValue(targetId, out this.targetGroup)) { throw new ServiceLocalException( string.Format( Strings.TransitionGroupNotFound, targetId)); } break; default: throw new ServiceLocalException(Strings.UnsupportedTimeZonePeriodTransitionTarget); } break; } } } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonTimeZoneTransition = new JsonObject(); JsonObject jsonToElement = new JsonObject(); jsonTimeZoneTransition.Add(XmlElementNames.To, jsonToElement); if (this.targetPeriod != null) { jsonToElement.Add(XmlAttributeNames.Kind, PeriodTarget); jsonToElement.Add(XmlElementNames.Value, this.targetPeriod.Id); } else { jsonToElement.Add(XmlAttributeNames.Kind, GroupTarget); jsonToElement.Add(XmlElementNames.Value, this.targetGroup.Id); } return jsonTimeZoneTransition; } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.To); if (this.targetPeriod != null) { writer.WriteAttributeValue(XmlAttributeNames.Kind, PeriodTarget); writer.WriteValue(this.targetPeriod.Id, XmlElementNames.To); } else { writer.WriteAttributeValue(XmlAttributeNames.Kind, GroupTarget); writer.WriteValue(this.targetGroup.Id, XmlElementNames.To); } writer.WriteEndElement(); // To } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> internal void LoadFromXml(EwsServiceXmlReader reader) { this.LoadFromXml(reader, this.GetXmlElementName()); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXml(EwsServiceXmlWriter writer) { this.WriteToXml(writer, this.GetXmlElementName()); } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition) : base() { this.timeZoneDefinition = timeZoneDefinition; } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> /// <param name="targetGroup">The transition group the transition will target.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition, TimeZoneTransitionGroup targetGroup) : this(timeZoneDefinition) { this.targetGroup = targetGroup; } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> /// <param name="targetPeriod">The period the transition will target.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition, TimeZonePeriod targetPeriod) : this(timeZoneDefinition) { this.targetPeriod = targetPeriod; } /// <summary> /// Gets the target period of the transition. /// </summary> internal TimeZonePeriod TargetPeriod { get { return this.targetPeriod; } } /// <summary> /// Gets the target transition group of the transition. /// </summary> internal TimeZoneTransitionGroup TargetGroup { get { return this.targetGroup; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; using Microsoft.DocAsCode.DataContracts.ManagedReference; using System.Globalization; public class TripleSlashCommentModel { private const string idSelector = @"((?![0-9])[\w_])+[\w\(\)\.\{\}\[\]\|\*\^~#@!`,_<>:]*"; private static Regex CommentIdRegex = new Regex(@"^(?<type>N|T|M|P|F|E|Overload):(?<id>" + idSelector + ")$", RegexOptions.Compiled); private static Regex LineBreakRegex = new Regex(@"\r?\n", RegexOptions.Compiled); private static Regex CodeElementRegex = new Regex(@"<code[^>]*>([\s\S]*?)</code>", RegexOptions.Compiled); private static Regex RegionRegex = new Regex(@"^\s*#region\s*(.*)$"); private static Regex EndRegionRegex = new Regex(@"^\s*#endregion\s*.*$"); private readonly ITripleSlashCommentParserContext _context; public string Summary { get; private set; } public string Remarks { get; private set; } public string Returns { get; private set; } public List<ExceptionInfo> Exceptions { get; private set; } public List<LinkInfo> Sees { get; private set; } public List<LinkInfo> SeeAlsos { get; private set; } public List<string> Examples { get; private set; } public Dictionary<string, string> Parameters { get; private set; } public Dictionary<string, string> TypeParameters { get; private set; } public bool IsInheritDoc { get; private set; } private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context) { // Transform triple slash comment XDocument doc = TripleSlashCommentTransformer.Transform(xml, language); _context = context; if (!context.PreserveRawInlineComments) { ResolveSeeCref(doc, context.AddReferenceDelegate); ResolveSeeAlsoCref(doc, context.AddReferenceDelegate); } ResolveCodeSource(doc, context); var nav = doc.CreateNavigator(); Summary = GetSummary(nav, context); Remarks = GetRemarks(nav, context); Returns = GetReturns(nav, context); Exceptions = GetExceptions(nav, context); Sees = GetSees(nav, context); SeeAlsos = GetSeeAlsos(nav, context); Examples = GetExamples(nav, context); Parameters = GetParameters(nav, context); TypeParameters = GetTypeParameters(nav, context); IsInheritDoc = GetIsInheritDoc(nav, context); } public static TripleSlashCommentModel CreateModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(xml)) return null; // Quick turnaround for badly formed XML comment if (xml.StartsWith("<!-- Badly formed XML comment ignored for member ")) { Logger.LogWarning($"Invalid triple slash comment is ignored: {xml}"); return null; } try { var model = new TripleSlashCommentModel(xml, language, context); return model; } catch (XmlException) { return null; } } public void CopyInheritedData(TripleSlashCommentModel src) { if (src == null) { throw new ArgumentNullException(nameof(src)); } Summary = Summary ?? src.Summary; Remarks = Remarks ?? src.Remarks; Returns = Returns ?? src.Returns; if (Exceptions == null && src.Exceptions != null) { Exceptions = src.Exceptions.Select(e => e.Clone()).ToList(); } if (Sees == null && src.Sees != null) { Sees = src.Sees.Select(s => s.Clone()).ToList(); } if (SeeAlsos == null && src.SeeAlsos != null) { SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList(); } if (Examples == null && src.Examples != null) { Examples = new List<string>(src.Examples); } if (Parameters == null && src.Parameters != null) { Parameters = new Dictionary<string, string>(src.Parameters); } if (TypeParameters == null && src.TypeParameters != null) { TypeParameters = new Dictionary<string, string>(src.TypeParameters); } } public string GetParameter(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } return GetValue(name, Parameters); } public string GetTypeParameter(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } return GetValue(name, TypeParameters); } private static string GetValue(string name, Dictionary<string, string> dictionary) { if (dictionary == null) { return null; } if (dictionary.TryGetValue(name, out string description)) { return description; } return null; } /// <summary> /// Get summary node out from triple slash comments /// </summary> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> /// <example> /// <code> <see cref="Hello"/></code> /// </example> private string GetSummary(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> string selector = "/member/summary"; return GetSingleNodeValue(nav, selector); } /// <summary> /// Get remarks node out from triple slash comments /// </summary> /// <remarks> /// <para>This is a sample of exception node</para> /// </remarks> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> private string GetRemarks(XPathNavigator nav, ITripleSlashCommentParserContext context) { string selector = "/member/remarks"; return GetSingleNodeValue(nav, selector); } private string GetReturns(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> string selector = "/member/returns"; return GetSingleNodeValue(nav, selector); } /// <summary> /// Get exceptions nodes out from triple slash comments /// </summary> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> /// <exception cref="XmlException">This is a sample of exception node</exception> private List<ExceptionInfo> GetExceptions(XPathNavigator nav, ITripleSlashCommentParserContext context) { string selector = "/member/exception"; var result = GetMulitpleCrefInfo(nav, selector).ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `see` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <see cref="SpecIdHelper"/> /// <see cref="SourceSwitch"/> private List<LinkInfo> GetSees(XPathNavigator nav, ITripleSlashCommentParserContext context) { var result = GetMultipleLinkInfo(nav, "/member/see").ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `seealso` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <seealso cref="WaitForChangedResult"/> /// <seealso cref="http://google.com">ABCS</seealso> private List<LinkInfo> GetSeeAlsos(XPathNavigator nav, ITripleSlashCommentParserContext context) { var result = GetMultipleLinkInfo(nav, "/member/seealso").ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `example` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <example> /// This sample shows how to call the <see cref="GetExceptions(string, ITripleSlashCommentParserContext)"/> method. /// <code> /// class TestClass /// { /// static int Main() /// { /// return GetExceptions(null, null).Count(); /// } /// } /// </code> /// </example> private List<string> GetExamples(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> return GetMultipleExampleNodes(nav, "/member/example").ToList(); } private bool GetIsInheritDoc(XPathNavigator nav, ITripleSlashCommentParserContext context) { var node = nav.SelectSingleNode("/member/inheritdoc"); if (node == null) { return false; } if (node.HasAttributes) { //The Sandcastle implementation of <inheritdoc /> supports two attributes: 'cref' and 'select'. //These attributes allow changing the source of the inherited doc and controlling what is inherited. //Until these attributes are supported, ignoring inheritdoc elements with attributes, so as not to misinterpret them. Logger.LogWarning("Attributes on <inheritdoc /> elements are not supported; inheritdoc element will be ignored."); return false; } return true; } private void ResolveCodeSource(XDocument doc, ITripleSlashCommentParserContext context) { foreach (XElement node in doc.XPathSelectElements("//code")) { var source = node.Attribute("source"); if (source == null || string.IsNullOrEmpty(source.Value)) { continue; } if (context.Source == null || string.IsNullOrEmpty(context.Source.Path)) { Logger.LogWarning($"Unable to get source file path for {node.ToString()}"); return; } var region = node.Attribute("region"); var path = source.Value; if (!Path.IsPathRooted(path)) { string currentFilePath = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path; var directory = Path.GetDirectoryName(currentFilePath); path = Path.Combine(directory, path); } ResolveCodeSource(node, path, region.Value); } } private void ResolveCodeSource(XElement element, string source, string region) { if (!File.Exists(source)) { Logger.LogWarning($"Source file '{source}' not found."); return; } var builder = new StringBuilder(); var regionCount = 0; foreach (var line in File.ReadLines(source)) { var match = RegionRegex.Match(line); if (match.Success) { var name = match.Groups[1].Value.Trim(); if (name == region) { ++regionCount; continue; } else if (regionCount > 0) { ++regionCount; } } else if (regionCount > 0 && EndRegionRegex.IsMatch(line)) { --regionCount; if (regionCount == 0) { break; } } if (string.IsNullOrEmpty(region) || regionCount > 0) { builder.AppendLine(line); } } element.SetValue(builder.ToString()); } private Dictionary<string, string> GetListContent(XPathNavigator navigator, string xpath, string contentType, ITripleSlashCommentParserContext context) { var iterator = navigator.Select(xpath); var result = new Dictionary<string, string>(); if (iterator == null) { return result; } foreach (XPathNavigator nav in iterator) { string name = nav.GetAttribute("name", string.Empty); string description = GetXmlValue(nav); if (!string.IsNullOrEmpty(name)) { if (result.ContainsKey(name)) { string path = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path; Logger.LogWarning($"Duplicate {contentType} '{name}' found in comments, the latter one is ignored.", file: StringExtension.ToDisplayPath(path), line: context.Source.StartLine.ToString()); } else { result.Add(name, description); } } } return result; } private Dictionary<string, string> GetParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context) { return GetListContent(navigator, "/member/param", "parameter", context); } private Dictionary<string, string> GetTypeParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context) { return GetListContent(navigator, "/member/typeparam", "type parameter", context); } private void ResolveSeeAlsoCref(XNode node, Action<string, string> addReference) { // Resolve <see cref> to <xref> ResolveCrefLink(node, "//seealso[@cref]", addReference); } private void ResolveSeeCref(XNode node, Action<string, string> addReference) { // Resolve <see cref> to <xref> ResolveCrefLink(node, "//see[@cref]", addReference); } private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, string> addReference) { if (node == null || string.IsNullOrEmpty(nodeSelector)) { return; } try { var nodes = node.XPathSelectElements(nodeSelector + "[@cref]").ToList(); foreach (var item in nodes) { var cref = item.Attribute("cref").Value; // Strict check is needed as value could be an invalid href, // e.g. !:Dictionary&lt;TKey, string&gt; when user manually changed the intellisensed generic type var match = CommentIdRegex.Match(cref); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "Overload") { id += '*'; } // When see and seealso are top level nodes in triple slash comments, do not convert it into xref node if (item.Parent?.Parent != null) { var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(id)}\" data-throw-if-not-resolved=\"false\"></xref>"); item.ReplaceWith(replacement); } addReference?.Invoke(id, cref); } else { var detailedInfo = new StringBuilder(); if (_context != null && _context.Source != null) { if (!string.IsNullOrEmpty(_context.Source.Name)) { detailedInfo.Append(" for "); detailedInfo.Append(_context.Source.Name); } if (!string.IsNullOrEmpty(_context.Source.Path)) { detailedInfo.Append(" defined in "); detailedInfo.Append(_context.Source.Path); detailedInfo.Append(" Line "); detailedInfo.Append(_context.Source.StartLine); } } Logger.Log(LogLevel.Warning, $"Invalid cref value \"{cref}\" found in triple-slash-comments{detailedInfo}, ignored."); } } } catch { } } private IEnumerable<string> GetMultipleExampleNodes(XPathNavigator navigator, string selector) { var iterator = navigator.Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string description = GetXmlValue(nav); yield return description; } } private IEnumerable<ExceptionInfo> GetMulitpleCrefInfo(XPathNavigator navigator, string selector) { var iterator = navigator.Clone().Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string description = GetXmlValue(nav); string commentId = nav.GetAttribute("cref", string.Empty); if (!string.IsNullOrEmpty(commentId)) { // Check if exception type is valid and trim prefix var match = CommentIdRegex.Match(commentId); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "T") { if (string.IsNullOrEmpty(description)) { description = null; } yield return new ExceptionInfo { Description = description, Type = id, CommentId = commentId }; } } } } } private IEnumerable<LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector) { var iterator = navigator.Clone().Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string altText = GetXmlValue(nav); if (string.IsNullOrEmpty(altText)) { altText = null; } string commentId = nav.GetAttribute("cref", string.Empty); string url = nav.GetAttribute("href", string.Empty); if (!string.IsNullOrEmpty(commentId)) { // Check if cref type is valid and trim prefix var match = CommentIdRegex.Match(commentId); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "Overload") { id += '*'; } yield return new LinkInfo { AltText = altText, LinkId = id, CommentId = commentId, LinkType = LinkType.CRef }; } } else if (!string.IsNullOrEmpty(url)) { yield return new LinkInfo { AltText = altText ?? url, LinkId = url, LinkType = LinkType.HRef }; } } } private string GetSingleNodeValue(XPathNavigator nav, string selector) { var node = nav.Clone().SelectSingleNode(selector); if (node == null) { // throw new ArgumentException(selector + " is not found"); return null; } else { return GetXmlValue(node); } } private string GetXmlValue(XPathNavigator node) { // NOTE: use node.InnerXml instead of node.Value, to keep decorative nodes, // e.g. // <remarks><para>Value</para></remarks> // decode InnerXml as it encodes // IXmlLineInfo.LinePosition starts from 1 and it would ignore '<' // e.g. // <summary/> the LinePosition is the column number of 's', so it should be minus 2 var lineInfo = node as IXmlLineInfo; int column = lineInfo.HasLineInfo() ? lineInfo.LinePosition - 2 : 0; return NormalizeXml(RemoveLeadingSpaces(GetInnerXml(node)), column); } /// <summary> /// Remove least common whitespces in each line of xml /// </summary> /// <param name="xml"></param> /// <returns>xml after removing least common whitespaces</returns> private static string RemoveLeadingSpaces(string xml) { var lines = LineBreakRegex.Split(xml); var normalized = new List<string>(); var preIndex = 0; var leadingSpaces = from line in lines where !string.IsNullOrWhiteSpace(line) select line.TakeWhile(char.IsWhiteSpace).Count(); if (leadingSpaces.Any()) { preIndex = leadingSpaces.Min(); } if (preIndex == 0) { return xml; } foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line)) { normalized.Add(string.Empty); } else { normalized.Add(line.Substring(preIndex)); } } return string.Join("\n", normalized); } /// <summary> /// Split xml into lines. Trim meaningless whitespaces. /// if a line starts with xml node, all leading whitespaces would be trimmed /// otherwise text node start position always aligns with the start position of its parent line(the last previous line that starts with xml node) /// Trim newline character for code element. /// </summary> /// <param name="xml"></param> /// <param name="parentIndex">the start position of the last previous line that starts with xml node</param> /// <returns>normalized xml</returns> private static string NormalizeXml(string xml, int parentIndex) { var lines = LineBreakRegex.Split(xml); var normalized = new List<string>(); foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line)) { normalized.Add(string.Empty); } else { // TO-DO: special logic for TAB case int index = line.TakeWhile(char.IsWhiteSpace).Count(); if (line[index] == '<') { parentIndex = index; } normalized.Add(line.Substring(Math.Min(parentIndex, index))); } } // trim newline character for code element return CodeElementRegex.Replace( string.Join("\n", normalized), m => { var group = m.Groups[1]; if (group.Length == 0) { return m.Value; } return m.Value.Replace(group.ToString(), group.ToString().Trim('\n')); }); } /// <summary> /// `>` is always encoded to `&gt;` in XML, when triple-slash-comments is considered as Markdown content, `>` is considered as blockquote /// Decode `>` to enable the Markdown syntax considering `>` is not a Must-Encode in Text XElement /// </summary> /// <param name="node"></param> /// <returns></returns> private static string GetInnerXml(XPathNavigator node) { using (var sw = new StringWriter(CultureInfo.InvariantCulture)) { using (var tw = new XmlWriterWithGtDecoded(sw)) { if (node.MoveToFirstChild()) { do { tw.WriteNode(node, true); } while (node.MoveToNext()); node.MoveToParent(); } } return sw.ToString(); } } private sealed class XmlWriterWithGtDecoded : XmlTextWriter { public XmlWriterWithGtDecoded(TextWriter tw) : base(tw) { } public XmlWriterWithGtDecoded(Stream w, Encoding encoding) : base(w, encoding) { } public override void WriteString(string text) { var encoded = text.Replace("&", "&amp;").Replace("<", "&lt;").Replace("'", "&apos;").Replace("\"", "&quot;"); WriteRaw(encoded); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public partial class ExecutionContextFlowTest : FileCleanupTestBase { [Theory] [InlineData(false)] [InlineData(true)] public async Task SocketAsyncEventArgs_ExecutionContextFlowsAcrossAcceptAsyncOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); saea.Completed += (s, e) => { e.AcceptSocket.Dispose(); tcs.SetResult(asyncLocal.Value); }; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { Assert.True(listener.AcceptAsync(saea)); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; client.Connect(listener.LocalEndPoint); Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task APM_ExecutionContextFlowsAcrossBeginAcceptOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { listener.BeginAccept(iar => { listener.EndAccept(iar).Dispose(); tcs.SetResult(asyncLocal.Value); }, null); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; client.Connect(listener.LocalEndPoint); Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task SocketAsyncEventArgs_ExecutionContextFlowsAcrossConnectAsyncOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); saea.Completed += (s, e) => tcs.SetResult(asyncLocal.Value); saea.RemoteEndPoint = listener.LocalEndPoint; bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = client.ConnectAsync(saea); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task APM_ExecutionContextFlowsAcrossBeginConnectOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = !client.BeginConnect(listener.LocalEndPoint, iar => { client.EndConnect(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously; } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task SocketAsyncEventArgs_ExecutionContextFlowsAcrossDisconnectAsyncOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); saea.Completed += (s, e) => tcs.SetResult(asyncLocal.Value); bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = client.DisconnectAsync(saea); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task APM_ExecutionContextFlowsAcrossBeginDisconnectOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = !client.BeginDisconnect(reuseSocket: false, iar => { client.EndDisconnect(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously; } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } } [Theory] [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public async Task SocketAsyncEventArgs_ExecutionContextFlowsAcrossReceiveAsyncOperation(bool suppressContext, bool receiveFrom) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); saea.Completed += (s, e) => tcs.SetResult(asyncLocal.Value); saea.SetBuffer(new byte[1], 0, 1); saea.RemoteEndPoint = server.LocalEndPoint; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { Assert.True(receiveFrom ? client.ReceiveFromAsync(saea) : client.ReceiveAsync(saea)); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; server.Send(new byte[] { 18 }); Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } [Theory] [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public async Task APM_ExecutionContextFlowsAcrossBeginReceiveOperation(bool suppressContext, bool receiveFrom) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { EndPoint ep = server.LocalEndPoint; Assert.False(receiveFrom ? client.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref ep, iar => { client.EndReceiveFrom(iar, ref ep); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously : client.BeginReceive(new byte[1], 0, 1, SocketFlags.None, iar => { client.EndReceive(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; server.Send(new byte[] { 18 }); Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } [Theory] [InlineData(false, 0)] [InlineData(true, 0)] [InlineData(false, 1)] [InlineData(true, 1)] [InlineData(false, 2)] [InlineData(true, 2)] public async Task SocketAsyncEventArgs_ExecutionContextFlowsAcrossSendAsyncOperation(bool suppressContext, int sendMode) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { byte[] buffer = new byte[10_000_000]; var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); saea.Completed += (s, e) => tcs.SetResult(asyncLocal.Value); saea.SetBuffer(buffer, 0, buffer.Length); saea.RemoteEndPoint = server.LocalEndPoint; saea.SendPacketsElements = new[] { new SendPacketsElement(buffer) }; bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = sendMode == 0 ? client.SendAsync(saea) : sendMode == 1 ? client.SendToAsync(saea) : client.SendPacketsAsync(saea); } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; int totalReceived = 0; while (totalReceived < buffer.Length) { totalReceived += server.Receive(buffer); } if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } } [Theory] [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public async Task APM_ExecutionContextFlowsAcrossBeginSendOperation(bool suppressContext, bool sendTo) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { byte[] buffer = new byte[10_000_000]; var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = sendTo ? !client.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, server.LocalEndPoint, iar => { client.EndSendTo(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously : !client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, iar => { client.EndSend(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously; } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; int totalReceived = 0; while (totalReceived < buffer.Length) { totalReceived += server.Receive(buffer); } if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task APM_ExecutionContextFlowsAcrossBeginSendFileOperation(bool suppressContext) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); client.Connect(listener.LocalEndPoint); using (Socket server = listener.Accept()) { string filePath = GetTestFilePath(); using (FileStream fs = File.Create(filePath)) { fs.WriteByte(18); } var asyncLocal = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); bool pending; asyncLocal.Value = 42; if (suppressContext) ExecutionContext.SuppressFlow(); try { pending = !client.BeginSendFile(filePath, iar => { client.EndSendFile(iar); tcs.SetResult(asyncLocal.Value); }, null).CompletedSynchronously; } finally { if (suppressContext) ExecutionContext.RestoreFlow(); } asyncLocal.Value = 0; if (pending) { Assert.Equal(suppressContext ? 0 : 42, await tcs.Task); } } } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.Text; namespace Mono.Cecil.Rocks { public class DocCommentId { StringBuilder id; DocCommentId () { id = new StringBuilder (); } void WriteField (FieldDefinition field) { WriteDefinition ('F', field); } void WriteEvent (EventDefinition @event) { WriteDefinition ('E', @event); } void WriteType (TypeDefinition type) { id.Append ('T').Append (':'); WriteTypeFullName (type); } void WriteMethod (MethodDefinition method) { WriteDefinition ('M', method); if (method.HasGenericParameters) { id.Append ('`').Append ('`'); id.Append (method.GenericParameters.Count); } if (method.HasParameters) WriteParameters (method.Parameters); if (IsConversionOperator (method)) WriteReturnType (method); } static bool IsConversionOperator (MethodDefinition self) { if (self == null) throw new ArgumentNullException ("self"); return self.IsSpecialName && (self.Name == "op_Explicit" || self.Name == "op_Implicit"); } void WriteReturnType (MethodDefinition method) { id.Append ('~'); WriteTypeSignature (method.ReturnType); } void WriteProperty (PropertyDefinition property) { WriteDefinition ('P', property); if (property.HasParameters) WriteParameters (property.Parameters); } void WriteParameters (IList<ParameterDefinition> parameters) { id.Append ('('); WriteList (parameters, p => WriteTypeSignature (p.ParameterType)); id.Append (')'); } void WriteTypeSignature (TypeReference type) { switch (type.MetadataType) { case MetadataType.Array: WriteArrayTypeSignature ((ArrayType) type); break; case MetadataType.ByReference: WriteTypeSignature (((ByReferenceType) type).ElementType); id.Append ('@'); break; case MetadataType.FunctionPointer: WriteFunctionPointerTypeSignature ((FunctionPointerType) type); break; case MetadataType.GenericInstance: WriteGenericInstanceTypeSignature ((GenericInstanceType) type); break; case MetadataType.Var: id.Append ('`'); id.Append (((GenericParameter) type).Position); break; case MetadataType.MVar: id.Append ('`').Append ('`'); id.Append (((GenericParameter) type).Position); break; case MetadataType.OptionalModifier: WriteModiferTypeSignature ((OptionalModifierType) type, '!'); break; case MetadataType.RequiredModifier: WriteModiferTypeSignature ((RequiredModifierType) type, '|'); break; case MetadataType.Pointer: WriteTypeSignature (((PointerType) type).ElementType); id.Append ('*'); break; default: WriteTypeFullName (type); break; } } void WriteGenericInstanceTypeSignature (GenericInstanceType type) { if (type.ElementType.IsTypeSpecification ()) throw new NotSupportedException (); WriteTypeFullName (type.ElementType, stripGenericArity: true); id.Append ('{'); WriteList (type.GenericArguments, WriteTypeSignature); id.Append ('}'); } void WriteList<T> (IList<T> list, Action<T> action) { for (int i = 0; i < list.Count; i++) { if (i > 0) id.Append (','); action (list [i]); } } void WriteModiferTypeSignature (IModifierType type, char id) { WriteTypeSignature (type.ElementType); this.id.Append (id); WriteTypeSignature (type.ModifierType); } void WriteFunctionPointerTypeSignature (FunctionPointerType type) { id.Append ("=FUNC:"); WriteTypeSignature (type.ReturnType); if (type.HasParameters) WriteParameters (type.Parameters); } void WriteArrayTypeSignature (ArrayType type) { WriteTypeSignature (type.ElementType); if (type.IsVector) { id.Append ("[]"); return; } id.Append ("["); WriteList (type.Dimensions, dimension => { if (dimension.LowerBound.HasValue) id.Append (dimension.LowerBound.Value); id.Append (':'); if (dimension.UpperBound.HasValue) id.Append (dimension.UpperBound.Value - (dimension.LowerBound.GetValueOrDefault () + 1)); }); id.Append ("]"); } void WriteDefinition (char id, IMemberDefinition member) { this.id.Append (id) .Append (':'); WriteTypeFullName (member.DeclaringType); this.id.Append ('.'); WriteItemName (member.Name); } void WriteTypeFullName (TypeReference type, bool stripGenericArity = false) { if (type.DeclaringType != null) { WriteTypeFullName (type.DeclaringType); id.Append ('.'); } if (!string.IsNullOrEmpty (type.Namespace)) { id.Append (type.Namespace); id.Append ('.'); } var name = type.Name; if (stripGenericArity) { var index = name.LastIndexOf ('`'); if (index > 0) name = name.Substring (0, index); } id.Append (name); } void WriteItemName (string name) { id.Append (name.Replace ('.', '#').Replace('<', '{').Replace('>', '}')); } public override string ToString () { return id.ToString (); } public static string GetDocCommentId (IMemberDefinition member) { if (member == null) throw new ArgumentNullException ("member"); var documentId = new DocCommentId (); switch (member.MetadataToken.TokenType) { case TokenType.Field: documentId.WriteField ((FieldDefinition) member); break; case TokenType.Method: documentId.WriteMethod ((MethodDefinition) member); break; case TokenType.TypeDef: documentId.WriteType ((TypeDefinition) member); break; case TokenType.Event: documentId.WriteEvent ((EventDefinition) member); break; case TokenType.Property: documentId.WriteProperty ((PropertyDefinition) member); break; default: throw new NotSupportedException (member.FullName); } return documentId.ToString (); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using NUnit.Framework; namespace NUnit.TestData.OneTimeSetUpTearDownData { [TestFixture] public class SetUpAndTearDownFixture { public int SetUpCount = 0; public int TearDownCount = 0; public bool ThrowInBaseSetUp = false; [OneTimeSetUp] public virtual void Init() { SetUpCount++; if (ThrowInBaseSetUp) throw new Exception("Error in base OneTimeSetUp"); } [OneTimeTearDown] public virtual void Destroy() { TearDownCount++; } [Test] public void Success() { } [Test] public void EvenMoreSuccess() { } } [TestFixture] public class SetUpAndTearDownFixtureWithTestCases { public int SetUpCount = 0; public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { TearDownCount++; } [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] public void Success(int i) { Assert.Pass("Passed with test case {0}", i); } } [TestFixture] public class SetUpAndTearDownFixtureWithTheories { public int SetUpCount = 0; public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { TearDownCount++; } public struct Data { public int Id { get; set; } } [DatapointSource] public IEnumerable<Data> FetchAllRows() { yield return new Data { Id = 1 }; yield return new Data { Id = 2 }; yield return new Data { Id = 3 }; yield return new Data { Id = 4 }; } [Theory] public void TheoryTest(Data entry) { Assert.Pass("Passed with theory id {0}", entry.Id); } } [TestFixture, Explicit] public class ExplicitSetUpAndTearDownFixture { public int SetUpCount = 0; public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { TearDownCount++; } [Test] public void Success() { } [Test] public void EvenMoreSuccess() { } } [TestFixture] public class InheritSetUpAndTearDown : SetUpAndTearDownFixture { [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class OverrideSetUpAndTearDown : SetUpAndTearDownFixture { public int DerivedSetUpCount; public int DerivedTearDownCount; [OneTimeSetUp] public override void Init() { DerivedSetUpCount++; } [OneTimeTearDown] public override void Destroy() { DerivedTearDownCount++; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture { public int DerivedSetUpCount; public int DerivedTearDownCount; public bool BaseSetUpCalledFirst; public bool BaseTearDownCalledLast; [OneTimeSetUp] public void Init2() { DerivedSetUpCount++; BaseSetUpCalledFirst = this.SetUpCount > 0; } [OneTimeTearDown] public void Destroy2() { DerivedTearDownCount++; BaseTearDownCalledLast = this.TearDownCount == 0; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class StaticSetUpAndTearDownFixture { public static int SetUpCount = 0; public static int TearDownCount = 0; [OneTimeSetUp] public static void Init() { SetUpCount++; } [OneTimeTearDown] public static void Destroy() { TearDownCount++; } [Test] public static void MyTest() { } } [TestFixture] public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture { public static int DerivedSetUpCount; public static int DerivedTearDownCount; public static bool BaseSetUpCalledFirst; public static bool BaseTearDownCalledLast; [OneTimeSetUp] public static void Init2() { DerivedSetUpCount++; BaseSetUpCalledFirst = SetUpCount > 0; } [OneTimeTearDown] public static void Destroy2() { DerivedTearDownCount++; BaseTearDownCalledLast = TearDownCount == 0; } [Test] public static void SomeTest() { } } [TestFixture] public static class StaticClassSetUpAndTearDownFixture { public static int SetUpCount = 0; public static int TearDownCount = 0; [OneTimeSetUp] public static void Init() { SetUpCount++; } [OneTimeTearDown] public static void Destroy() { TearDownCount++; } [Test] public static void MyTest() { } } [TestFixture] public class FixtureWithParallelizableOnOneTimeSetUp { [OneTimeSetUp] [Parallelizable] public void BadOneTimeSetup() { } [Test] public void Test() { } } [TestFixture] public class MisbehavingFixture { public bool BlowUpInSetUp = false; public bool BlowUpInTest = false; public bool BlowUpInTearDown = false; public int SetUpCount = 0; public int TearDownCount = 0; public void Reinitialize() { SetUpCount = 0; TearDownCount = 0; BlowUpInSetUp = false; BlowUpInTearDown = false; } [OneTimeSetUp] public void SetUp() { SetUpCount++; if (BlowUpInSetUp) throw new Exception("This was thrown from fixture setup"); } [OneTimeTearDown] public void TearDown() { TearDownCount++; if (BlowUpInTearDown) throw new Exception("This was thrown from fixture teardown"); } [Test] public void Test() { if (BlowUpInTest) throw new Exception("This was thrown from a test"); } } [TestFixture] public class ExceptionInConstructor { public ExceptionInConstructor() { throw new Exception( "This was thrown in constructor" ); } [Test] public void NothingToTest() { } } [TestFixture] public class IgnoreInFixtureSetUp { [OneTimeSetUp] public void SetUpCallsIgnore() { Assert.Ignore("OneTimeSetUp called Ignore"); } [Test] public void NothingToTest() { } } [TestFixture] public class SetUpAndTearDownWithTestInName { public int SetUpCount = 0; public int TearDownCount = 0; [OneTimeSetUp] public virtual void OneTimeSetUp() { SetUpCount++; } [OneTimeTearDown] public virtual void OneTimeTearDown() { TearDownCount++; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture, Ignore( "Do Not Run This" )] public class IgnoredFixture { public bool SetupCalled = false; public bool TeardownCalled = false; [OneTimeSetUp] public virtual void ShouldNotRun() { SetupCalled = true; } [OneTimeTearDown] public virtual void NeitherShouldThis() { TeardownCalled = true; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture] public class FixtureWithNoTests { public bool SetupCalled = false; public bool TeardownCalled = false; [OneTimeSetUp] public virtual void Init() { SetupCalled = true; } [OneTimeTearDown] public virtual void Destroy() { TeardownCalled = true; } } [TestFixture] public class DisposableFixture : IDisposable { public int DisposeCalled = 0; public List<String> Actions = new List<String>(); [OneTimeSetUp] public void OneTimeSetUp() { Actions.Add("OneTimeSetUp"); } [OneTimeTearDown] public void OneTimeTearDown() { Actions.Add("OneTimeTearDown"); } [Test] public void OneTest() { } public void Dispose() { Actions.Add("Dispose"); DisposeCalled++; } } [TestFixture] public class DisposableFixtureWithTestCases : IDisposable { public int DisposeCalled = 0; [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] public void TestCaseTest(int data) { } public void Dispose() { DisposeCalled++; } } }
// 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; internal class A { public virtual int f0(int i) { return 1; } } internal unsafe class B : A { public override int f0(int i) { return i; } public static int f1(ref int i) { return i; } public int f(int i) { return f1(ref i); } public static int F1downBy1ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 4; i >= 1; i -= 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 1; i -= 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy1le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 4; i += 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy1lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 4; i += 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy1gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i > 2; i -= 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy2le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 5; i += 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy2ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i >= 1; i -= 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy2lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 5; i += 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy2gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 10; i > 2; i -= 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 4; i += 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 2; i -= 1) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 5; i += 2) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1upBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 1; i != 8; i += 3) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F1downBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 8; i != 1; i -= 3) { Object c = new Object(); c = amount; sum += Convert.ToInt32(c); } return sum + i; } public static int F2downBy1ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 4; i >= 1; i -= 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 1; i -= 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy1le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 4; i += 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy1lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 4; i += 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy1gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i > 2; i -= 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy2le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 5; i += 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy2ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i >= 1; i -= 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy2lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 5; i += 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy2gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 10; i > 2; i -= 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 4; i += 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 2; i -= 1) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 5; i += 2) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2upBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 1; i != 8; i += 3) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F2downBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 8; i != 1; i -= 3) { int* n = stackalloc int[1]; *n = amount; sum += amount; } return sum + i; } public static int F3downBy1ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 4; i >= 1; i -= 1) { int[] n = new int[i]; } for (i = 4; i >= 1; i -= 1) { sum += amount; } return sum + i; } public static int F3downBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 1; i -= 2) { int[] n = new int[i]; } for (i = 5; i != 1; i -= 2) { sum += amount; } return sum + i; } public static int F3upBy1le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 4; i += 1) { int[] n = new int[i]; } for (i = 1; i <= 4; i += 1) { sum += amount; } return sum + i; } public static int F3upBy1lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 4; i += 1) { int[] n = new int[i]; } for (i = 1; i < 4; i += 1) { sum += amount; } return sum + i; } public static int F3downBy1gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i > 2; i -= 1) { int[] n = new int[i]; } for (i = 5; i > 2; i -= 1) { sum += amount; } return sum + i; } public static int F3upBy2le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 5; i += 2) { int[] n = new int[i]; } for (i = 1; i <= 5; i += 2) { sum += amount; } return sum + i; } public static int F3downBy2ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i >= 1; i -= 2) { int[] n = new int[i]; } for (i = 5; i >= 1; i -= 2) { sum += amount; } return sum + i; } public static int F3upBy2lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 5; i += 2) { int[] n = new int[i]; } for (i = 1; i < 5; i += 2) { sum += amount; } return sum + i; } public static int F3downBy2gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 10; i > 2; i -= 2) { int[] n = new int[i]; } for (i = 10; i > 2; i -= 2) { sum += amount; } return sum + i; } public static int F3upBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 4; i += 1) { int[] n = new int[i]; } for (i = 1; i != 4; i += 1) { sum += amount; } return sum + i; } public static int F3downBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 2; i -= 1) { int[] n = new int[i]; } for (i = 5; i != 2; i -= 1) { sum += amount; } return sum + i; } public static int F3upBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 5; i += 2) { int[] n = new int[i]; } for (i = 1; i != 5; i += 2) { sum += amount; } return sum + i; } public static int F3upBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 1; i != 10; i += 3) { int[] n = new int[i]; } for (i = 1; i != 8; i += 3) { sum += amount; } return sum + i; } public static int F3downBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 10; i != 1; i -= 3) { int[] n = new int[i]; } for (i = 8; i != 1; i -= 3) { sum += amount; } return sum + i; } public static int F4downBy1ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 4; i >= 1; i -= 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 1; i -= 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy1le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 4; i += 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy1lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 4; i += 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy1gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i > 2; i -= 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy2le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 5; i += 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy2ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i >= 1; i -= 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy2lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 5; i += 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy2gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 10; i > 2; i -= 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 4; i += 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 2; i -= 1) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 5; i += 2) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4upBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 1; i != 8; i += 3) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F4downBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 8; i != 1; i -= 3) { TypedReference _ref = __makeref(sum); __refvalue(_ref, int) += amount; } return sum + i; } public static int F5downBy1ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 4; i >= 1; i -= 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 1; i -= 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy1le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 4; i += 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy1lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 4; i += 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy1gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i > 2; i -= 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy2le(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i <= 5; i += 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy2ge(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i >= 1; i -= 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy2lt(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i < 5; i += 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy2gt(int amount) { int i; int sum = 0; B b = new B(); for (i = 10; i > 2; i -= 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 4; i += 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy1ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 5; i != 2; i -= 1) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy2ne(int amount) { int i; int sum = 0; B b = new B(); for (i = 1; i != 5; i += 2) { try { sum += amount; } catch { } } return sum + i; } public static int F5upBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 1; i != 8; i += 3) { try { sum += amount; } catch { } } return sum + i; } public static int F5downBy3neWrap(int amount) { short i; int sum = 0; B b = new B(); for (i = 8; i != 1; i -= 3) { try { sum += amount; } catch { } } return sum + i; } public static int Main(String[] args) { bool failed = false; if (F1upBy1le(10) != 45) { Console.WriteLine("F1upBy1le failed"); failed = true; } if (F1downBy1ge(10) != 40) { Console.WriteLine("F1downBy1ge failed"); failed = true; } if (F1upBy1lt(10) != 34) { Console.WriteLine("F1upBy1lt failed"); failed = true; } if (F1downBy1gt(10) != 32) { Console.WriteLine("F1downBy1gt failed"); failed = true; } if (F1upBy2le(10) != 37) { Console.WriteLine("F1upBy2le failed"); failed = true; } if (F1downBy2ge(10) != 29) { Console.WriteLine("F1downBy2ge failed"); failed = true; } if (F1upBy2lt(10) != 25) { Console.WriteLine("F1upBy2lt failed"); failed = true; } if (F1downBy2gt(10) != 42) { Console.WriteLine("F1downBy2gt failed"); failed = true; } if (F1upBy1ne(10) != 34) { Console.WriteLine("F1upBy1ne failed"); failed = true; } if (F1downBy1ne(10) != 32) { Console.WriteLine("F1downBy1ne failed"); failed = true; } if (F1upBy2ne(10) != 25) { Console.WriteLine("F1upBy2ne failed"); failed = true; } if (F1downBy2ne(10) != 21) { Console.WriteLine("F1downBy2ne failed"); failed = true; } if (F1upBy3neWrap(1) != 43701) { Console.WriteLine("F1upBy3neWrap failed"); failed = true; } if (F1downBy3neWrap(1) != 43694) { Console.WriteLine("F1downBy3neWrap failed"); failed = true; } if (F2upBy1le(10) != 45) { Console.WriteLine("F2upBy1le failed"); failed = true; } if (F2downBy1ge(10) != 40) { Console.WriteLine("F2downBy1ge failed"); failed = true; } if (F2upBy1lt(10) != 34) { Console.WriteLine("F2upBy1lt failed"); failed = true; } if (F2downBy1gt(10) != 32) { Console.WriteLine("F2downBy1gt failed"); failed = true; } if (F2upBy2le(10) != 37) { Console.WriteLine("F2upBy2le failed"); failed = true; } if (F2downBy2ge(10) != 29) { Console.WriteLine("F2downBy2ge failed"); failed = true; } if (F2upBy2lt(10) != 25) { Console.WriteLine("F2upBy2lt failed"); failed = true; } if (F2downBy2gt(10) != 42) { Console.WriteLine("F2downBy2gt failed"); failed = true; } if (F2upBy1ne(10) != 34) { Console.WriteLine("F2upBy1ne failed"); failed = true; } if (F2downBy1ne(10) != 32) { Console.WriteLine("F2downBy1ne failed"); failed = true; } if (F2upBy2ne(10) != 25) { Console.WriteLine("F2upBy2ne failed"); failed = true; } if (F2downBy2ne(10) != 21) { Console.WriteLine("F2downBy2ne failed"); failed = true; } if (F2upBy3neWrap(1) != 43701) { Console.WriteLine("F2upBy3neWrap failed"); failed = true; } if (F2downBy3neWrap(1) != 43694) { Console.WriteLine("F2downBy3neWrap failed"); failed = true; } if (F3upBy1le(10) != 45) { Console.WriteLine("F3upBy1le failed"); failed = true; } if (F3downBy1ge(10) != 40) { Console.WriteLine("F3downBy1ge failed"); failed = true; } if (F3upBy1lt(10) != 34) { Console.WriteLine("F3upBy1lt failed"); failed = true; } if (F3downBy1gt(10) != 32) { Console.WriteLine("F3downBy1gt failed"); failed = true; } if (F3upBy2le(10) != 37) { Console.WriteLine("F3upBy2le failed"); failed = true; } if (F3downBy2ge(10) != 29) { Console.WriteLine("F3downBy2ge failed"); failed = true; } if (F3upBy2lt(10) != 25) { Console.WriteLine("F3upBy2lt failed"); failed = true; } if (F3downBy2gt(10) != 42) { Console.WriteLine("F3downBy2gt failed"); failed = true; } if (F3upBy1ne(10) != 34) { Console.WriteLine("F3upBy1ne failed"); failed = true; } if (F3downBy1ne(10) != 32) { Console.WriteLine("F3downBy1ne failed"); failed = true; } if (F3upBy2ne(10) != 25) { Console.WriteLine("F3upBy2ne failed"); failed = true; } if (F3downBy2ne(10) != 21) { Console.WriteLine("F3downBy2ne failed"); failed = true; } if (F3upBy3neWrap(1) != 43701) { Console.WriteLine("F3upBy3neWrap failed"); failed = true; } if (F3downBy3neWrap(1) != 43694) { Console.WriteLine("F3downBy3neWrap failed"); failed = true; } if (F4upBy1le(10) != 45) { Console.WriteLine("F4upBy1le failed"); failed = true; } if (F4downBy1ge(10) != 40) { Console.WriteLine("F4downBy1ge failed"); failed = true; } if (F4upBy1lt(10) != 34) { Console.WriteLine("F4upBy1lt failed"); failed = true; } if (F4downBy1gt(10) != 32) { Console.WriteLine("F4downBy1gt failed"); failed = true; } if (F4upBy2le(10) != 37) { Console.WriteLine("F4upBy2le failed"); failed = true; } if (F4downBy2ge(10) != 29) { Console.WriteLine("F4downBy2ge failed"); failed = true; } if (F4upBy2lt(10) != 25) { Console.WriteLine("F4upBy2lt failed"); failed = true; } if (F4downBy2gt(10) != 42) { Console.WriteLine("F4downBy2gt failed"); failed = true; } if (F4upBy1ne(10) != 34) { Console.WriteLine("F4upBy1ne failed"); failed = true; } if (F4downBy1ne(10) != 32) { Console.WriteLine("F4downBy1ne failed"); failed = true; } if (F4upBy2ne(10) != 25) { Console.WriteLine("F4upBy2ne failed"); failed = true; } if (F4downBy2ne(10) != 21) { Console.WriteLine("F4downBy2ne failed"); failed = true; } if (F4upBy3neWrap(1) != 43701) { Console.WriteLine("F4upBy3neWrap failed"); failed = true; } if (F4downBy3neWrap(1) != 43694) { Console.WriteLine("F4downBy3neWrap failed"); failed = true; } if (F5upBy1le(10) != 45) { Console.WriteLine("F5upBy1le failed"); failed = true; } if (F5downBy1ge(10) != 40) { Console.WriteLine("F5downBy1ge failed"); failed = true; } if (F5upBy1lt(10) != 34) { Console.WriteLine("F5upBy1lt failed"); failed = true; } if (F5downBy1gt(10) != 32) { Console.WriteLine("F5downBy1gt failed"); failed = true; } if (F5upBy2le(10) != 37) { Console.WriteLine("F5upBy2le failed"); failed = true; } if (F5downBy2ge(10) != 29) { Console.WriteLine("F5downBy2ge failed"); failed = true; } if (F5upBy2lt(10) != 25) { Console.WriteLine("F5upBy2lt failed"); failed = true; } if (F5downBy2gt(10) != 42) { Console.WriteLine("F5downBy2gt failed"); failed = true; } if (F5upBy1ne(10) != 34) { Console.WriteLine("F5upBy1ne failed"); failed = true; } if (F5downBy1ne(10) != 32) { Console.WriteLine("F5downBy1ne failed"); failed = true; } if (F5upBy2ne(10) != 25) { Console.WriteLine("F5upBy2ne failed"); failed = true; } if (F5downBy2ne(10) != 21) { Console.WriteLine("F5downBy2ne failed"); failed = true; } if (F5upBy3neWrap(1) != 43701) { Console.WriteLine("F5upBy3neWrap failed"); failed = true; } if (F5downBy3neWrap(1) != 43694) { Console.WriteLine("F5downBy3neWrap failed"); failed = true; } if (!failed) { Console.WriteLine(); Console.WriteLine("Passed"); return 100; } else { Console.WriteLine(); Console.WriteLine("Failed"); return 1; } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SlimManualResetEvent.cs // // // An manual-reset event that mixes a little spinning with a true Win32 event. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics; using System.Security.Permissions; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Threading { // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to // a brief amount of spinning that should, on the average, make using the slim event // cheaper than using Win32 events directly. This can be reset manually, much like // a Win32 manual-reset would be. // // Notes: // We lazily allocate the Win32 event internally. Therefore, the caller should // always call Dispose to clean it up, just in case. This API is a no-op of the // event wasn't allocated, but if it was, ensures that the event goes away // eagerly, instead of waiting for finalization. /// <summary> /// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>. /// </summary> /// <remarks> /// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Set = {IsSet}")] [HostProtection(Synchronization = true, ExternalThreading = true)] public class ManualResetEventSlim : IDisposable { // These are the default spin counts we use on single-proc and MP machines. private const int DEFAULT_SPIN_SP = 1; private const int DEFAULT_SPIN_MP = SpinWait.YIELD_THRESHOLD; private volatile object m_lock; // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 private const int SignalledState_ShiftCount = 31; //1-bit for disposed state private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 //11-bits for m_spinCount private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 private const int SpinCountState_ShiftCount = 19; private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 private const int NumWaitersState_ShiftCount = 0; private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 // ----------- // #if DEBUG private static int s_nextId; // The next id that will be given out. private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. private long m_lastSetTime; private long m_lastResetTime; #endif /// <summary> /// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see /// cref="ManualResetEventSlim"/>. /// </summary> /// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see /// cref="ManualResetEventSlim"/>.</value> /// <remarks> /// Accessing this property forces initialization of an underlying event object if one hasn't /// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>, /// the public Wait methods should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); } return m_eventObj; } } /// <summary> /// Gets whether the event is set. /// </summary> /// <value>true if the event has is set; otherwise, false.</value> public bool IsSet { get { return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); } private set { UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); } } /// <summary> /// Gets the number of spin waits that will be occur before falling back to a true wait. /// </summary> public int SpinCount { get { return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); } private set { Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } } /// <summary> /// How many threads are waiting. /// </summary> private int Waiters { get { return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); } set { //setting to <0 would indicate an internal flaw, hence Assert is appropriate. Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) throw new InvalidOperationException(String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_TooManyWaiters"), NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } } //----------------------------------------------------------------------------------- // Constructs a new event, optionally specifying the initial state and spin count. // The defaults are that the event is unsignaled and some reasonable default spin. // /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with an initial state of nonsignaled. /// </summary> public ManualResetEventSlim() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolen value indicating whether to set the intial state to signaled. /// </summary> /// <param name="initialState">true to set the initial state signaled; false to set the initial state /// to nonsignaled.</param> public ManualResetEventSlim(bool initialState) { // Specify the defualt spin count, and use default spin if we're // on a multi-processor machine. Otherwise, we won't. Initialize(initialState, DEFAULT_SPIN_MP); } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolen value indicating whether to set the intial state to signaled and a specified /// spin count. /// </summary> /// <param name="initialState">true to set the initial state to signaled; false to set the initial state /// to nonsignaled.</param> /// <param name="spinCount">The number of spin waits that will occur before falling back to a true /// wait.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than /// 0 or greater than the maximum allowed value.</exception> public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException(nameof(spinCount)); } if (spinCount > SpinCountState_MaxValue) { throw new ArgumentOutOfRangeException( nameof(spinCount), String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"), SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. Initialize(initialState, spinCount); } /// <summary> /// Initializes the internal state of the event. /// </summary> /// <param name="initialState">Whether the event is set initially or not.</param> /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; } /// <summary> /// Helper to ensure the lock object is created before first use. /// </summary> private void EnsureLockObjectCreated() { Contract.Ensures(m_lock != null); if (m_lock != null) return; object newObj = new object(); Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. } /// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> /// <returns>True if a new event was created and stored, false otherwise.</returns> private bool LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Close(); return false; } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Contract.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } return true; } } /// <summary> /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to /// proceed. /// </summary> public void Set() { Set(false); } /// <summary> /// Private helper to actually perform the Set. /// </summary> /// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param> /// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception> private void Set(bool duringCancellation) { // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj // This would be a legal movement according to the .NET memory model. // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. IsSet = true; // If there are waiting threads, we need to pulse them. if (Waiters > 0) { Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent eventObj = m_eventObj; //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic if (eventObj != null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, // but before we have gotten around to setting m_eventObj (just below). That's // because Wait first checks m_state and will only access the event if absolutely // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is // quite common, and we must support it. If the waiter woke up and disposed of // the event object before the setter has finished, however, we would try to set a // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to // protect access to the event object when setting and disposing of it. We also // double-check that the event has not become null in the meantime when in the lock. lock (eventObj) { if (m_eventObj != null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); } } } #if DEBUG m_lastSetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Sets the state of the event to nonsignaled, which causes threads to block. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. if (m_eventObj != null) { m_eventObj.Reset(); } // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. // This could cause waiting threads to wake up even though the event is in an // unsignaled state. This is fine -- those that are calling Reset concurrently are // responsible for doing "the right thing" -- e.g. rechecking the condition and // resetting the event manually. // And finally set our state back to unsignaled. IsSet = false; #if DEBUG m_lastResetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal, /// while observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); // an early convenience check if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (!IsSet) { if (millisecondsTimeout == 0) { // For 0-timeouts, we just return immediately. return false; } // We spin briefly before falling back to allocating and/or waiting on a true event. uint startTime = 0; bool bNeedTimeoutAdjustment = false; int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. if (millisecondsTimeout != Timeout.Infinite) { // We will account for time spent spinning, so that we can decrement it from our // timeout. In most cases the time spent in this section will be negligible. But // we can't discount the possibility of our thread being switched out for a lengthy // period of time. The timeout adjustments only take effect when and if we actually // decide to block in the kernel below. startTime = TimeoutHelper.GetTime(); bNeedTimeoutAdjustment = true; } //spin int HOW_MANY_SPIN_BEFORE_YIELD = 10; int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5; int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20; int spinCount = SpinCount; for (int i = 0; i < spinCount; i++) { if (IsSet) { return true; } else if (i < HOW_MANY_SPIN_BEFORE_YIELD) { if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2) { Thread.Yield(); } else { Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i)); } } else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0) { Thread.Sleep(1); } else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0) { Thread.Sleep(0); } else { Thread.Yield(); } if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count cancellationToken.ThrowIfCancellationRequested(); } // Now enter the lock and wait. EnsureLockObjectCreated(); // We must register and deregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) { lock (m_lock) { // Loop to cope with spurious wakeups from other waits being canceled while (!IsSet) { // If our token was canceled, we must throw and exit. cancellationToken.ThrowIfCancellationRequested(); //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) if (bNeedTimeoutAdjustment) { realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (realMillisecondsTimeout <= 0) return false; } // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, // so after updating waiters, we must check IsSet again. // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange // operation which provides a full memory barrier. // If we see IsSet=false, then we are guaranteed that Set() will see that we are // waiting and will pulse the monitor correctly. Waiters = Waiters + 1; if (IsSet) //This check must occur after updating Waiters. { Waiters--; //revert the increment. return true; } // Now finally perform the wait. try { // ** the actual wait ** if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) return false; //return immediately if the timeout has expired. } finally { // Clean up: we're done waiting. Waiters = Waiters - 1; } // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) } } } } // automatically disposes (and deregisters) the callback return true; //done. The wait was satisfied. } /// <summary> /// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if ((m_combinedState & Dispose_BitMask) != 0) return; // already disposed m_combinedState |= Dispose_BitMask; //set the dispose bit if (disposing) { // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent eventObj = m_eventObj; if (eventObj != null) { lock (eventObj) { eventObj.Close(); m_eventObj = null; } } } } /// <summary> /// Throw ObjectDisposedException if the MRES is disposed /// </summary> private void ThrowIfDisposed() { if ((m_combinedState & Dispose_BitMask) != 0) throw new ObjectDisposedException(Environment.GetResourceString("ManualResetEventSlim_Disposed")); } /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback); private static void CancellationTokenCallback(object obj) { ManualResetEventSlim mre = obj as ManualResetEventSlim; Contract.Assert(mre != null, "Expected a ManualResetEventSlim"); Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters } } /// <summary> /// Private helper method for updating parts of a bit-string state value. /// Mainly called from the IsSet and Waiters properties setters /// </summary> /// <remarks> /// Note: the parameter types must be int as CompareExchange cannot take a Uint /// </remarks> /// <param name="newBits">The new value</param> /// <param name="updateBitsMask">The mask used to set the bits</param> private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait sw = new SpinWait(); Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); do { int oldState = m_combinedState; // cache the old value for testing in CAS // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] int newState = (oldState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) { return; } sw.SpinOnce(); } while (true); } /// <summary> /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> /// <param name="rightBitShiftCount"></param> /// <returns></returns> private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { //convert to uint before shifting so that right-shift does not replicate the sign-bit, //then convert back to int. return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); } /// <summary> /// Performs a Mask operation, but does not perform the shift. /// This is acceptable for boolean values for which the shift is unnecessary /// eg (val &amp; Mask) != 0 is an appropriate way to extract a boolean rather than using /// ((val &amp; Mask) &gt;&gt; shiftAmount) == 1 /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> private static int ExtractStatePortion(int state, int mask) { return state & mask; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.MIME { /// <summary> /// MIME lexical tokens parser. /// </summary> public class MIME_Reader { private string m_Source = ""; private int m_Offset = 0; #region constants private static readonly char[] atextChars = new char[]{'!','#','$','%','&','\'','*','+','-','/','=','?','^','_','`','{','|','}','~'}; private static readonly char[] specials = new char[]{'(',')','<','>','[',']',':',';','@','\\',',','.','"'}; private static readonly char[] tspecials = new char[]{'(',')','<','>','@',',',';',':','\\','"','/','[',']','?','='}; #endregion /// <summary> /// Default constructor. /// </summary> /// <param name="value">Value to read.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> public MIME_Reader(string value) { if(value == null){ throw new ArgumentNullException("value"); } m_Source = value; } #region method Atom /// <summary> /// Reads RFC 2822 'atom' from source stream. /// </summary> /// <returns>Returns RFC 2822 'atom' or null if end of stream reached.</returns> public string Atom() { /* RFC 2822 3.2.4. * atom = [CFWS] 1*atext [CFWS] */ ToFirstChar(); StringBuilder retVal = new StringBuilder(); while(true){ int peekChar = Peek(false); // We reached end of string. if(peekChar == -1){ break; } else{ char c = (char)peekChar; if(IsAText(c)){ retVal.Append((char)Char(false)); } // Char is not part of 'atom', break. else{ break; } } } if(retVal.Length > 0){ return retVal.ToString(); } else{ return null; } } #endregion #region method DotAtom /// <summary> /// Reads RFC 2822 'dot-atom' from source stream. /// </summary> /// <returns>Returns RFC 2822 'dot-atom' or null if end of stream reached.</returns> public string DotAtom() { /* RFC 2822 3.2.4. * dot-atom = [CFWS] dot-atom-text [CFWS] * dot-atom-text = 1*atext *("." 1*atext) */ ToFirstChar(); StringBuilder retVal = new StringBuilder(); while(true){ string atom = Atom(); // We reached end of string. if(atom == null){ break; } else{ retVal.Append(atom); // dot-atom-text continues. if(Peek(false) == '.'){ retVal.Append((char)Char(false)); } else{ break; } } } if(retVal.Length > 0){ return retVal.ToString(); } else{ return null; } } #endregion #region method Token /// <summary> /// Reads RFC 2045 (section 5) 'token' from source stream. /// </summary> /// <returns>Returns RFC 2045 (section 5) 'token' or null if end of stream reached.</returns> public string Token() { /* RFC 2045 5. * token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials> */ ToFirstChar(); StringBuilder retVal = new StringBuilder(); while(true){ int peekChar = Peek(false); // We reached end of string. if(peekChar == -1){ break; } else{ char c = (char)peekChar; if(IsToken(c)){ retVal.Append((char)Char(false)); } // Char is not part of 'token', break. else{ break; } } } if(retVal.Length > 0){ return retVal.ToString(); } else{ return null; } } #endregion #region method Comment /// <summary> /// Reads RFC 822 'comment' from source stream. /// </summary> /// <returns>Returns RFC 822 'comment' or null if end of stream reached.</returns> public string Comment() { /* RFC 822 3.3. * comment = "(" *(ctext / quoted-pair / comment) ")" * ctext = <any CHAR excluding "(", ")", "\" & CR, & including linear-white-space> * quoted-pair = "\" CHAR */ ToFirstChar(); if(Peek(false) != '('){ throw new InvalidOperationException("No 'comment' value available."); } StringBuilder retVal = new StringBuilder(); // Remove '('. Char(false); int nestedParenthesis = 0; while(true){ int intC = Char(false); // End of stream reached, invalid 'comment' value. if(intC == -1){ throw new ArgumentException("Invalid 'comment' value, no closing ')'."); } else if(intC == '('){ nestedParenthesis++; } else if(intC == ')'){ // We readed whole 'comment' ok. if(nestedParenthesis == 0){ break; } else{ nestedParenthesis--; } } else{ retVal.Append((char)intC); } } return retVal.ToString(); } #endregion #region method Word /// <summary> /// Reads RFC 2822 (section 3.2.6) 'word' from source stream. /// </summary> /// <returns>Returns RFC 2822 (section 3.2.6) 'word' or null if end of stream reached.</returns> public string Word() { /* RFC 2822 3.2.6. * word = atom / quoted-string */ if(Peek(true) == '"'){ return QuotedString(); } else{ return Atom(); } } #endregion #region method EncodedWord /// <summary> /// Reads RFC 2047 'encoded-word' from source stream. /// </summary> /// <returns>Returns RFC 2047 'encoded-word' or null if end of stream reached.</returns> /// <exception cref="InvalidOperationException">Is raised when source stream has no encoded-word at current position.</exception> public string EncodedWord() { /* RFC 2047 2. * encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" * * An 'encoded-word' may not be more than 75 characters long, including * 'charset', 'encoding', 'encoded-text', and delimiters. If it is * desirable to encode more text than will fit in an 'encoded-word' of * 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may * be used. */ ToFirstChar(); if(Peek(false) != '='){ throw new InvalidOperationException("No encoded-word available."); } StringBuilder retVal = new StringBuilder(); while(true){ string encodedWord = Atom(); try{ string[] parts = encodedWord.Split('?'); if(parts[2].ToUpper() == "Q"){ retVal.Append(Core.QDecode(Encoding.GetEncoding(parts[1]),parts[3])); } else if(parts[2].ToUpper() == "B"){ retVal.Append(Encoding.GetEncoding(parts[1]).GetString(Core.Base64Decode(Encoding.Default.GetBytes(parts[3])))); } else{ throw new Exception(""); } } catch{ // Failed to parse encoded-word, leave it as is. RFC 2047 6.3. retVal.Append(encodedWord); } ToFirstChar(); // encoded-word does not continue. if(Peek(false) != '='){ break; } } return retVal.ToString(); } #endregion #region method QuotedString /// <summary> /// Reads RFC 822 'quoted-string' from source stream. /// </summary> /// <returns>Returns RFC 822 'quoted-string' or null if end of stream reached.</returns> /// <exception cref="InvalidOperationException">Is raised when source stream has no quoted-string at current position.</exception> /// <exception cref="ArgumentException">Is raised when not valid 'quoted-string'.</exception> public string QuotedString() { /* RFC 2822 3.2.5. * qtext = NO-WS-CTL / ; Non white space controls %d33 / ; The rest of the US-ASCII %d35-91 / ; characters not including "\" %d93-126 ; or the quote character qcontent = qtext / quoted-pair quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS] */ ToFirstChar(); if(Peek(false) != '"'){ throw new InvalidOperationException("No quoted-string available."); } // Read start DQUOTE. Char(false); StringBuilder retVal = new StringBuilder(); bool escape = false; while(true){ int intC = Char(false); // We reached end of stream, invalid quoted string, end quote is missing. if(intC == -1){ throw new ArgumentException("Invalid quoted-string, end quote is missing."); } // This char is escaped. else if(escape){ escape = false; retVal.Append((char)intC); } // Closing DQUOTE. else if(intC == '"'){ break; } // Next char is escaped. else if(intC == '\\'){ escape = true; } // Skip folding chars. else if(intC == '\r' || intC == '\n'){ } // Normal char in quoted-string. else{ retVal.Append((char)intC); } } return retVal.ToString(); } #endregion #region method Value /// <summary> /// Reads RFC 2045 (section 5) 'token' from source stream. /// </summary> /// <returns>Returns 2045 (section 5) 'token' or null if end of stream reached.</returns> public string Value() { // value := token / quoted-string if(Peek(true) == '"'){ return QuotedString(); } else{ return Token(); } } #endregion #region method Phrase /// <summary> /// Reads RFC 2047 (section 5) 'phrase' from source stream. /// </summary> /// <returns>Returns RFC 2047 (section 5) 'phrase' or null if end of stream reached.</returns> public string Phrase() { /* RFC 2047 5. * phrase = 1*( encoded-word / word ) * word = atom / quoted-string */ throw new NotImplementedException(); /* int peek = m_pStringReader.Peek(); if(peek == '"'){ return QuotedString(); } else if(peek == '='){ return EncodedWord(); } else{ return Atom(); }*/ //return ""; } #endregion #region method Text /// <summary> /// Reads RFC 822 '*text' from source stream. /// </summary> /// <returns>Returns RFC 822 '*text' or null if end of stream reached.</returns> public string Text() { throw new NotImplementedException(); } #endregion #region method ToFirstChar /// <summary> /// Reads all white-space chars + CR and LF. /// </summary> /// <returns>Returns readed chars.</returns> public string ToFirstChar() { // NOTE: Never call Peek or Char method here or stack overflow ! StringBuilder retVal = new StringBuilder(); while(true){ int peekChar = -1; if(m_Offset > m_Source.Length - 1){ peekChar = -1; } else{ peekChar = m_Source[m_Offset]; } // We reached end of string. if(peekChar == -1){ break; } else if(peekChar == ' ' || peekChar == '\t' || peekChar == '\r' || peekChar == '\n'){ retVal.Append(m_Source[m_Offset++]); } else{ break; } } return retVal.ToString(); } #endregion #region method Char /// <summary> /// Reads 1 char from source stream. /// </summary> /// <param name="readToFirstChar">Specifies if postion is moved to char(skips white spaces).</param> /// <returns>Returns readed char or -1 if end of stream reached.</returns> public int Char(bool readToFirstChar) { if(readToFirstChar){ ToFirstChar(); } if(m_Offset > m_Source.Length - 1){ return -1; } else{ return m_Source[m_Offset++]; } } #endregion #region method Peek /// <summary> /// Shows next char in source stream, this method won't consume that char. /// </summary> /// <param name="readToFirstChar">Specifies if postion is moved to char(skips white spaces).</param> /// <returns>Returns next char in source stream, returns -1 if end of stream.</returns> public int Peek(bool readToFirstChar) { if(readToFirstChar){ ToFirstChar(); } if(m_Offset > m_Source.Length - 1){ return -1; } else{ return m_Source[m_Offset]; } } #endregion #region method StartsWith /// <summary> /// Gets if source stream valu starts with the specified value. Compare is case-insensitive. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if source steam satrs with specified string.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> public bool StartsWith(string value) { if(value == null){ throw new ArgumentNullException("value"); } return m_Source.Substring(m_Offset).StartsWith(value,StringComparison.InvariantCultureIgnoreCase); } #endregion #region method ToEnd /// <summary> /// Reads all data from current postion to the end. /// </summary> /// <returns>Retruns readed data. Returns null if end of string is reached.</returns> public string ToEnd() { if(m_Offset >= m_Source.Length){ return null; } string retVal = m_Source.Substring(m_Offset); m_Offset = m_Source.Length; return retVal; } #endregion #region static method IsAlpha /// <summary> /// Gets if the specified char is RFC 822 'ALPHA'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 822 'ALPHA'.</returns> public static bool IsAlpha(char c) { /* RFC 822 3.3. ALPHA = <any ASCII alphabetic character>; (65.- 90.); (97.-122.) */ if((c >= 65 && c <= 90) || (c >= 97 && c <= 122)){ return true; } else{ return false; } } #endregion #region static method IsAText /// <summary> /// Gets if the specified char is RFC 2822 'atext'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2822 'atext'.</returns> public static bool IsAText(char c) { /* RFC 2822 3.2.4. * atext = ALPHA / DIGIT / * "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / * "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / * "|" / "}" / "~" */ if(IsAlpha(c) || char.IsDigit(c)){ return true; } else{ foreach(char aC in atextChars){ if(c == aC){ return true; } } } return false; } #endregion #region static method IsDotAtom /// <summary> /// Gets if the specified value can be represented as "dot-atom". /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if the specified value can be represented as "dot-atom".</returns> public static bool IsDotAtom(string value) { if(value == null){ throw new ArgumentNullException("value"); } /* RFC 2822 3.2.4. * dot-atom = [CFWS] dot-atom-text [CFWS] * dot-atom-text = 1*atext *("." 1*atext) */ foreach(char c in value){ if(c != '.' && !IsAText(c)){ return false; } } return true; } #endregion #region static method IsToken /// <summary> /// Gets if specified valu is RFC 2045 (section 5) 'token'. /// </summary> /// <param name="text">Text to check.</param> /// <returns>Returns true if specified char is RFC 2045 (section 5) 'token'.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null.</exception> public static bool IsToken(string text) { if(text == null){ throw new ArgumentNullException("text"); } if(text == ""){ return false; } foreach(char c in text){ if(!IsToken(c)){ return false; } } return true; } /// <summary> /// Gets if the specified char is RFC 2045 (section 5) 'token'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2045 (section 5) 'token'.</returns> public static bool IsToken(char c) { /* RFC 2045 5. * token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials> * * RFC 822 3.3. * CTL = <any ASCII control; (0.- 31.); (127.) */ if(c <= 31 || c == 127){ return false; } else if(c == ' '){ return false; } else{ foreach(char tsC in tspecials){ if(tsC == c){ return false; } } } return true; } #endregion #region static method IsAttributeChar /// <summary> /// Gets if the specified char is RFC 2231 (section 7) 'attribute-char'. /// </summary> /// <param name="c">Char to check.</param> /// <returns>Returns true if specified char is RFC 2231 (section 7) 'attribute-char'.</returns> public static bool IsAttributeChar(char c) { /* RFC 2231 7. * attribute-char := <any (US-ASCII) CHAR except SPACE, CTLs, "*", "'", "%", or tspecials> * * RFC 822 3.3. * CTL = <any ASCII control; (0.- 31.); (127.) */ if(c <= 31 || c > 127){ return false; } else if(c == ' ' || c == '*' || c == '\'' || c == '%'){ return false; } else{ foreach(char cS in tspecials){ if(c == cS){ return false; } } } return true; } #endregion #region method ReadParenthesized /// <summary> /// Reads parenthesized value. Supports {},(),[],&lt;&gt; parenthesis. /// Throws exception if there isn't parenthesized value or closing parenthesize is missing. /// </summary> /// <returns>Returns value between parenthesized.</returns> public string ReadParenthesized() { ToFirstChar(); char startingChar = ' '; char closingChar = ' '; if(m_Source[m_Offset] == '{'){ startingChar = '{'; closingChar = '}'; } else if(m_Source[m_Offset] == '('){ startingChar = '('; closingChar = ')'; } else if(m_Source[m_Offset] == '['){ startingChar = '['; closingChar = ']'; } else if(m_Source[m_Offset] == '<'){ startingChar = '<'; closingChar = '>'; } else{ throw new Exception("No parenthesized value '" + m_Source.Substring(m_Offset) + "' !"); } m_Offset++; bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char)0; int nestedStartingCharCounter = 0; for(int i=m_Offset;i<m_Source.Length;i++){ // Skip escaped(\) " if(lastChar != '\\' && m_Source[i] == '\"'){ // Start/end quoted string area inQuotedString = !inQuotedString; } // We need to skip parenthesis in quoted string else if(!inQuotedString){ // There is nested parenthesis if(m_Source[i] == startingChar){ nestedStartingCharCounter++; } // Closing char else if(m_Source[i] == closingChar){ // There isn't nested parenthesis closing chars left, this is closing char what we want. if(nestedStartingCharCounter == 0){ string retVal = m_Source.Substring(m_Offset,i - m_Offset); m_Offset = i + 1; return retVal; } // This is nested parenthesis closing char else{ nestedStartingCharCounter--; } } } lastChar = m_Source[i]; } throw new ArgumentException("There is no closing parenthesize for '" + m_Source.Substring(m_Offset) + "' !"); } #endregion #region method QuotedReadToDelimiter /// <summary> /// Reads string to specified delimiter or to end of underlying string. Notes: Delimiters in quoted string is skipped. /// For example: delimiter = ',', text = '"aaaa,eee",qqqq' - then result is '"aaaa,eee"'. /// </summary> /// <param name="delimiters">Data delimiters.</param> /// <returns>Returns readed string or null if end of string reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>delimiters</b> is null reference.</exception> public string QuotedReadToDelimiter(char[] delimiters) { if(delimiters == null){ throw new ArgumentNullException("delimiters"); } if(this.Available == 0){ return null; } ToFirstChar(); StringBuilder currentSplitBuffer = new StringBuilder(); // Holds active bool inQuotedString = false; // Holds flag if position is quoted string or not char lastChar = (char)0; for(int i=m_Offset;i<m_Source.Length;i++){ char c = (char)Peek(false); // Skip escaped(\) " if(lastChar != '\\' && c == '\"'){ // Start/end quoted string area inQuotedString = !inQuotedString; } // See if char is delimiter bool isDelimiter = false; foreach(char delimiter in delimiters){ if(c == delimiter){ isDelimiter = true; break; } } // Current char is split char and it isn't in quoted string, do split if(!inQuotedString && isDelimiter){ return currentSplitBuffer.ToString(); } else{ currentSplitBuffer.Append(c); m_Offset++; } lastChar = c; } // If we reached so far then we are end of string, return it. return currentSplitBuffer.ToString(); } #endregion #region Properties implementation /// <summary> /// Gets number of chars has left for processing. /// </summary> public int Available { get{ return m_Source.Length - m_Offset; } } #endregion } }
// // PersonaAuthorizer.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Auth; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Auth { public class PersonaAuthorizer : Authorizer { public const string LoginParameterAssertion = "assertion"; private static IDictionary<IList<string>, string> assertions; public const string AssertionFieldEmail = "email"; public const string AssertionFieldOrigin = "origin"; public const string AssertionFieldExpiration = "exp"; public const string QueryParameter = "personaAssertion"; private bool skipAssertionExpirationCheck; private string emailAddress; public PersonaAuthorizer(string emailAddress) { // set to true to skip checking whether assertions have expired (useful for testing) this.emailAddress = emailAddress; } public virtual void SetSkipAssertionExpirationCheck(bool skipAssertionExpirationCheck ) { this.skipAssertionExpirationCheck = skipAssertionExpirationCheck; } public virtual bool IsSkipAssertionExpirationCheck() { return skipAssertionExpirationCheck; } public virtual string GetEmailAddress() { return emailAddress; } protected internal virtual bool IsAssertionExpired(IDictionary<string, object> parsedAssertion ) { if (this.IsSkipAssertionExpirationCheck() == true) { return false; } DateTime exp; exp = (DateTime)parsedAssertion[AssertionFieldExpiration]; DateTime now = new DateTime(); if (exp < now) { Log.W(Database.Tag, string.Format("%s assertion for %s expired: %s", this.GetType (), this.emailAddress, exp)); return true; } return false; } public virtual string AssertionForSite(Uri site) { string assertion = AssertionForEmailAndSite(this.emailAddress, site); if (assertion == null) { Log.W(Database.Tag, string.Format("%s %s no assertion found for: %s", this.GetType (), this.emailAddress, site)); return null; } IDictionary<string, object> result = ParseAssertion(assertion); if (IsAssertionExpired(result)) { return null; } return assertion; } public override bool UsesCookieBasedLogin { get {return true;} } public override IDictionary<string, string> LoginParametersForSite(Uri site) { IDictionary<string, string> loginParameters = new Dictionary<string, string>(); string assertion = AssertionForSite(site); if (assertion != null) { loginParameters[LoginParameterAssertion] = assertion; return loginParameters; } else { return null; } } public override string LoginPathForSite(Uri site) { return "/_persona"; } public static string RegisterAssertion(string assertion) { lock (typeof(PersonaAuthorizer)) { string email; string origin; IDictionary<string, object> result = ParseAssertion(assertion); email = (string)result[AssertionFieldEmail]; origin = (string)result[AssertionFieldOrigin]; // Normalize the origin URL string: try { Uri originURL = new Uri(origin); if (origin == null) { throw new ArgumentException("Invalid assertion, origin was null"); } origin = originURL.ToString().ToLower(); } catch (UriFormatException e) { string message = "Error registering assertion: " + assertion; Log.E(Database.Tag, message, e); throw new ArgumentException(message, e); } return RegisterAssertion(assertion, email, origin); } } /// <summary> /// don't use this!! this was factored out for testing purposes, and had to be /// made public since tests are in their own package. /// </summary> /// <remarks> /// don't use this!! this was factored out for testing purposes, and had to be /// made public since tests are in their own package. /// </remarks> public static string RegisterAssertion(string assertion, string email, string origin ) { lock (typeof(PersonaAuthorizer)) { IList<string> key = new AList<string>(); key.AddItem(email); key.AddItem(origin); if (assertions == null) { assertions = new Dictionary<IList<string>, string>(); } Log.D(Database.Tag, "PersonaAuthorizer registering key: " + key); assertions[key] = assertion; return email; } } public static IDictionary<string, object> ParseAssertion(string assertion) { // https://github.com/mozilla/id-specs/blob/prod/browserid/index.md // http://self-issued.info/docs/draft-jones-json-web-token-04.html IDictionary<string, object> result = new Dictionary<string, object>(); string[] components = assertion.Split("\\."); // split on "." if (components.Length < 4) { throw new ArgumentException("Invalid assertion given, only " + components.Length + " found. Expected 4+"); } string component1Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components [1], Base64.Default)); string component3Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components [3], Base64.Default)); try { ObjectWriter mapper = new ObjectWriter(); IDictionary<object, object> component1Json = mapper.ReadValue<IDictionary>(component1Decoded ); IDictionary<object, object> principal = (IDictionary<object, object>)component1Json ["principal"]; result.Put(AssertionFieldEmail, principal["email"]); IDictionary<object, object> component3Json = mapper.ReadValue<IDictionary>(component3Decoded ); result.Put(AssertionFieldOrigin, component3Json["aud"]); long expObject = (long)component3Json["exp"]; Log.D(Database.Tag, "PersonaAuthorizer exp: " + expObject + " class: " + expObject .GetType()); DateTime expDate = Sharpen.Extensions.CreateDate(expObject); result[AssertionFieldExpiration] = expDate; } catch (IOException e) { string message = "Error parsing assertion: " + assertion; Log.E(Database.Tag, message, e); throw new ArgumentException(message, e); } return result; } public static string AssertionForEmailAndSite(string email, Uri site) { IList<string> key = new AList<string>(); key.AddItem(email); key.AddItem(site.ToString().ToLower()); Log.D(Database.Tag, "PersonaAuthorizer looking up key: " + key + " from list of assertions" ); return assertions[key]; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1010Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1010Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1010Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1010Response, global::DolphinServer.ProtoEntity.A1010Response.Builder> internal__static_A1010Response__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1010Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTAxMFJlc3BvbnNlLnR4dCJuCg1BMTAxMFJlc3BvbnNlEhEKCUVycm9y", "SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSCwoDVWlkGAMgASgJEgwK", "BENhcmQYBCABKAUSDQoFQ2FyZDEYBSABKAUSDQoFQ2FyZDIYBiABKAVCHKoC", "GURvbHBoaW5TZXJ2ZXIuUHJvdG9FbnRpdHk=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1010Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1010Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1010Response, global::DolphinServer.ProtoEntity.A1010Response.Builder>(internal__static_A1010Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "Uid", "Card", "Card1", "Card2", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1010Response : pb::GeneratedMessage<A1010Response, A1010Response.Builder> { private A1010Response() { } private static readonly A1010Response defaultInstance = new A1010Response().MakeReadOnly(); private static readonly string[] _a1010ResponseFieldNames = new string[] { "Card", "Card1", "Card2", "ErrorCode", "ErrorInfo", "Uid" }; private static readonly uint[] _a1010ResponseFieldTags = new uint[] { 32, 40, 48, 16, 10, 26 }; public static A1010Response DefaultInstance { get { return defaultInstance; } } public override A1010Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1010Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1010Response.internal__static_A1010Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1010Response, A1010Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1010Response.internal__static_A1010Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int UidFieldNumber = 3; private bool hasUid; private string uid_ = ""; public bool HasUid { get { return hasUid; } } public string Uid { get { return uid_; } } public const int CardFieldNumber = 4; private bool hasCard; private int card_; public bool HasCard { get { return hasCard; } } public int Card { get { return card_; } } public const int Card1FieldNumber = 5; private bool hasCard1; private int card1_; public bool HasCard1 { get { return hasCard1; } } public int Card1 { get { return card1_; } } public const int Card2FieldNumber = 6; private bool hasCard2; private int card2_; public bool HasCard2 { get { return hasCard2; } } public int Card2 { get { return card2_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1010ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[4], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[3], ErrorCode); } if (hasUid) { output.WriteString(3, field_names[5], Uid); } if (hasCard) { output.WriteInt32(4, field_names[0], Card); } if (hasCard1) { output.WriteInt32(5, field_names[1], Card1); } if (hasCard2) { output.WriteInt32(6, field_names[2], Card2); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } if (hasUid) { size += pb::CodedOutputStream.ComputeStringSize(3, Uid); } if (hasCard) { size += pb::CodedOutputStream.ComputeInt32Size(4, Card); } if (hasCard1) { size += pb::CodedOutputStream.ComputeInt32Size(5, Card1); } if (hasCard2) { size += pb::CodedOutputStream.ComputeInt32Size(6, Card2); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1010Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1010Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1010Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1010Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1010Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1010Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1010Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1010Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1010Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1010Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1010Response MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1010Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1010Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1010Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1010Response result; private A1010Response PrepareBuilder() { if (resultIsReadOnly) { A1010Response original = result; result = new A1010Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1010Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1010Response.Descriptor; } } public override A1010Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1010Response.DefaultInstance; } } public override A1010Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1010Response) { return MergeFrom((A1010Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1010Response other) { if (other == global::DolphinServer.ProtoEntity.A1010Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.HasUid) { Uid = other.Uid; } if (other.HasCard) { Card = other.Card; } if (other.HasCard1) { Card1 = other.Card1; } if (other.HasCard2) { Card2 = other.Card2; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1010ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1010ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 26: { result.hasUid = input.ReadString(ref result.uid_); break; } case 32: { result.hasCard = input.ReadInt32(ref result.card_); break; } case 40: { result.hasCard1 = input.ReadInt32(ref result.card1_); break; } case 48: { result.hasCard2 = input.ReadInt32(ref result.card2_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public bool HasUid { get { return result.hasUid; } } public string Uid { get { return result.Uid; } set { SetUid(value); } } public Builder SetUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUid = true; result.uid_ = value; return this; } public Builder ClearUid() { PrepareBuilder(); result.hasUid = false; result.uid_ = ""; return this; } public bool HasCard { get { return result.hasCard; } } public int Card { get { return result.Card; } set { SetCard(value); } } public Builder SetCard(int value) { PrepareBuilder(); result.hasCard = true; result.card_ = value; return this; } public Builder ClearCard() { PrepareBuilder(); result.hasCard = false; result.card_ = 0; return this; } public bool HasCard1 { get { return result.hasCard1; } } public int Card1 { get { return result.Card1; } set { SetCard1(value); } } public Builder SetCard1(int value) { PrepareBuilder(); result.hasCard1 = true; result.card1_ = value; return this; } public Builder ClearCard1() { PrepareBuilder(); result.hasCard1 = false; result.card1_ = 0; return this; } public bool HasCard2 { get { return result.hasCard2; } } public int Card2 { get { return result.Card2; } set { SetCard2(value); } } public Builder SetCard2(int value) { PrepareBuilder(); result.hasCard2 = true; result.card2_ = value; return this; } public Builder ClearCard2() { PrepareBuilder(); result.hasCard2 = false; result.card2_ = 0; return this; } } static A1010Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1010Response.Descriptor, null); } } #endregion } #endregion Designer generated code
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EntitySpaces, LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- */ using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Threading; using Tiraggo.DynamicQuery; using Tiraggo.Interfaces; using VistaDB.Diagnostic; using VistaDB.Provider; namespace Tiraggo.VistaDB4Provider { public class DataProvider : IDataProvider { public DataProvider() { } #region esTraceArguments private sealed class esTraceArguments : Tiraggo.Interfaces.ITraceArguments, IDisposable { static private long packetOrder = 0; private sealed class esTraceParameter : ITraceParameter { public string Name { get; set; } public string Direction { get; set; } public string ParamType { get; set; } public string BeforeValue { get; set; } public string AfterValue { get; set; } } public esTraceArguments() { } public esTraceArguments(tgDataRequest request, IDbCommand cmd, tgEntitySavePacket packet, string action, string callStack) { PacketOrder = Interlocked.Increment(ref esTraceArguments.packetOrder); this.command = cmd; TraceChannel = DataProvider.sTraceChannel; Syntax = "VISTADB"; Request = request; ThreadId = Thread.CurrentThread.ManagedThreadId; Action = action; CallStack = callStack; SqlCommand = cmd; ApplicationName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); IDataParameterCollection parameters = cmd.Parameters; if (parameters.Count > 0) { Parameters = new List<ITraceParameter>(parameters.Count); for (int i = 0; i < parameters.Count; i++) { VistaDBParameter param = parameters[i] as VistaDBParameter; esTraceParameter p = new esTraceParameter() { Name = param.ParameterName, Direction = param.Direction.ToString(), ParamType = param.DbType.ToString().ToUpper(), BeforeValue = param.Value != null && param.Value != DBNull.Value ? Convert.ToString(param.Value) : "null" }; try { // Let's make it look like we're using parameters for the profiler if (param.Value == null || param.Value == DBNull.Value) { if (param.SourceVersion == DataRowVersion.Current || param.SourceVersion == DataRowVersion.Default) { object o = packet.CurrentValues[param.SourceColumn]; if (o != null && o != DBNull.Value) { p.BeforeValue = Convert.ToString(o); } } else if (param.SourceVersion == DataRowVersion.Original) { object o = packet.OriginalValues[param.SourceColumn]; if (o != null && o != DBNull.Value) { p.BeforeValue = Convert.ToString(o); } } } } catch { } this.Parameters.Add(p); } } stopwatch = Stopwatch.StartNew(); } public esTraceArguments(tgDataRequest request, IDbCommand cmd, string action, string callStack) { PacketOrder = Interlocked.Increment(ref esTraceArguments.packetOrder); this.command = cmd; TraceChannel = DataProvider.sTraceChannel; Syntax = "VISTADB"; Request = request; ThreadId = Thread.CurrentThread.ManagedThreadId; Action = action; CallStack = callStack; SqlCommand = cmd; ApplicationName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); IDataParameterCollection parameters = cmd.Parameters; if (parameters.Count > 0) { Parameters = new List<ITraceParameter>(parameters.Count); for (int i = 0; i < parameters.Count; i++) { VistaDBParameter param = parameters[i] as VistaDBParameter; esTraceParameter p = new esTraceParameter() { Name = param.ParameterName, Direction = param.Direction.ToString(), ParamType = param.DbType.ToString().ToUpper(), BeforeValue = param.Value != null && param.Value != DBNull.Value ? Convert.ToString(param.Value) : "null" }; this.Parameters.Add(p); } } stopwatch = Stopwatch.StartNew(); } // Temporary variable private IDbCommand command; public long PacketOrder { get; set; } public string Syntax { get; set; } public tgDataRequest Request { get; set; } public int ThreadId { get; set; } public string Action { get; set; } public string CallStack { get; set; } public IDbCommand SqlCommand { get; set; } public string ApplicationName { get; set; } public string TraceChannel { get; set; } public long Duration { get; set; } public long Ticks { get; set; } public string Exception { get; set; } public List<ITraceParameter> Parameters { get; set; } private Stopwatch stopwatch; void IDisposable.Dispose() { stopwatch.Stop(); Duration = stopwatch.ElapsedMilliseconds; Ticks = stopwatch.ElapsedTicks; // Gather Output Parameters if (this.Parameters != null && this.Parameters.Count > 0) { IDataParameterCollection parameters = command.Parameters; for (int i = 0; i < this.Parameters.Count; i++) { ITraceParameter esParam = this.Parameters[i]; IDbDataParameter param = parameters[esParam.Name] as IDbDataParameter; if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output) { esParam.AfterValue = param.Value != null ? Convert.ToString(param.Value) : "null"; } } } DataProvider.sTraceHandler(this); } } #endregion esTraceArguments #region Profiling Logic /// <summary> /// The EventHandler used to decouple the profiling code from the core assemblies /// </summary> event TraceEventHandler IDataProvider.TraceHandler { add { DataProvider.sTraceHandler += value; } remove { DataProvider.sTraceHandler -= value; } } static private event TraceEventHandler sTraceHandler; /// <summary> /// Returns true if this Provider is current being profiled /// </summary> bool IDataProvider.IsTracing { get { return sTraceHandler != null ? true : false; } } /// <summary> /// Used to set the Channel this provider is to use during Profiling /// </summary> string IDataProvider.TraceChannel { get { return DataProvider.sTraceChannel; } set { DataProvider.sTraceChannel = value; } } static private string sTraceChannel = "Channel1"; #endregion Profiling Logic /// <summary> /// This method acts as a delegate for tgTransactionScope /// </summary> /// <returns></returns> static private IDbConnection CreateIDbConnectionDelegate() { return new VistaDBConnection(); } static private void CleanupCommand(VistaDBCommand cmd) { if (cmd != null && cmd.Connection != null) { if (cmd.Connection.State == ConnectionState.Open) { cmd.Connection.Close(); } } } #region IDataProvider Members tgDataResponse IDataProvider.esLoadDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; case tgQueryType.DynamicQuery: response = new tgDataResponse(); VistaDBCommand cmd = QueryBuilder.PrepareCommand(request); LoadDataTableFromDynamicQuery(request, response, cmd); break; case tgQueryType.DynamicQueryParseOnly: response = new tgDataResponse(); VistaDBCommand cmd1 = QueryBuilder.PrepareCommand(request); response.LastQuery = cmd1.CommandText; break; case tgQueryType.ManyToMany: response = LoadManyToMany(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.esSaveDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { if (request.SqlAccessType == tgSqlAccessType.StoredProcedure) { if (request.CollectionSavePacket != null) SaveStoredProcCollection(request); else SaveStoredProcEntity(request); } else { if (request.EntitySavePacket.CurrentValues == null) SaveDynamicCollection(request); else SaveDynamicEntity(request); } } catch (VistaDBException ex) { tgException es = Shared.CheckForConcurrencyException(ex); if (es != null) response.Exception = es; else response.Exception = ex; } catch (DBConcurrencyException dbex) { response.Exception = new tgConcurrencyException("Error in VistaDBProvider.esSaveDataTable", dbex); } response.Table = request.Table; return response; } tgDataResponse IDataProvider.ExecuteNonQuery(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { cmd = new VistaDBCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteNonQuery", System.Environment.StackTrace)) { try { response.RowsEffected = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.RowsEffected = cmd.ExecuteNonQuery(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteReader(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { cmd = new VistaDBCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } cmd.Connection = new VistaDBConnection(request.ConnectionString); cmd.Connection.Open(); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteReader", System.Environment.StackTrace)) { try { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteScalar(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { cmd = new VistaDBCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteScalar", System.Environment.StackTrace)) { try { response.Scalar = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.Scalar = cmd.ExecuteScalar(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataSet(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataSetFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataSetFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } #endregion IDataProvider Members static private tgDataResponse LoadDataSetFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new VistaDBCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); VistaDBDataAdapter da = new VistaDBDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataSetFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new VistaDBCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); VistaDBDataAdapter da = new VistaDBDataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadDataSetFromText", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); }; response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new VistaDBCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); VistaDBDataAdapter da = new VistaDBDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new VistaDBCommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); VistaDBDataAdapter da = new VistaDBDataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromText", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadManyToMany(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); VistaDBCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new VistaDBCommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; string mmQuery = request.QueryText; string[] sections = mmQuery.Split('|'); string[] tables = sections[0].Split(','); string[] columns = sections[1].Split(','); // We build the query, we don't use Delimiters to avoid tons of extra concatentation string sql = "SELECT * FROM [" + tables[0]; sql += "] JOIN [" + tables[1] + "] ON [" + tables[0] + "].[" + columns[0] + "] = ["; sql += tables[1] + "].[" + columns[1]; sql += "] WHERE [" + tables[1] + "].[" + sections[2] + "] = @"; if (request.Parameters != null) { foreach (tgParameter esParam in request.Parameters) { sql += esParam.Name; } Shared.AddParameters(cmd, request); } VistaDBDataAdapter da = new VistaDBDataAdapter(); cmd.CommandText = sql; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadManyToMany", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } // This is used only to execute the Dynamic Query API static private void LoadDataTableFromDynamicQuery(tgDataRequest request, tgDataResponse response, VistaDBCommand cmd) { try { response.LastQuery = cmd.CommandText; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); VistaDBDataAdapter da = new VistaDBDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromDynamicQuery", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; } catch (Exception) { CleanupCommand(cmd); throw; } finally { } } static private DataTable SaveStoredProcCollection(tgDataRequest request) { throw new NotImplementedException("Stored Procedure Support Not Implemented"); } static private DataTable SaveStoredProcEntity(tgDataRequest request) { throw new NotImplementedException("Stored Procedure Support Not Implemented"); } static private DataTable SaveDynamicCollection(tgDataRequest request) { tgEntitySavePacket pkt = request.CollectionSavePacket[0]; if (pkt.RowState == tgDataRowState.Deleted) { //============================================================================ // We do all our deletes at once, so if the first one is a delete they all are //============================================================================ return SaveDynamicCollection_Deletes(request); } else { //============================================================================ // We do all our Inserts and Updates at once //============================================================================ return SaveDynamicCollection_InsertsUpdates(request); } } static private DataTable SaveDynamicCollection_InsertsUpdates(tgDataRequest request) { DataTable dataTable = CreateDataTable(request); using (tgTransactionScope scope = new tgTransactionScope()) { using (VistaDBDataAdapter da = new VistaDBDataAdapter()) { da.AcceptChangesDuringUpdate = false; da.ContinueUpdateOnError = request.ContinueUpdateOnError; VistaDBCommand cmd = null; if (!request.IgnoreComputedColumns) { da.RowUpdated += new VistaDBRowUpdatedEventHandler(OnRowUpdated); } foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { if (packet.RowState != tgDataRowState.Added && packet.RowState != tgDataRowState.Modified) continue; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); switch (packet.RowState) { case tgDataRowState.Added: cmd = da.InsertCommand = Shared.BuildDynamicInsertCommand(request, packet.ModifiedColumns); SetModifiedValues(request, packet, row); break; case tgDataRowState.Modified: cmd = da.UpdateCommand = Shared.BuildDynamicUpdateCommand(request, packet.ModifiedColumns); SetOriginalValues(request, packet, row, false); SetModifiedValues(request, packet, row); row.AcceptChanges(); row.SetModified(); break; } request.Properties["tgDataRequest"] = request; request.Properties["esEntityData"] = packet; dataTable.ExtendedProperties["props"] = request.Properties; DataRow[] singleRow = new DataRow[1]; singleRow[0] = row; try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, packet, "SaveCollectionDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } if (row.HasErrors) { request.FireOnError(packet, row.RowError); } } finally { tgTransactionScope.DeEnlist(cmd); dataTable.Rows.Clear(); } if (!row.HasErrors && cmd.Parameters != null) { foreach (VistaDBParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: packet.CurrentValues[param.SourceColumn] = param.Value; break; } } } cmd.Dispose(); } } scope.Complete(); } return dataTable; } static private DataTable SaveDynamicCollection_Deletes(tgDataRequest request) { VistaDBCommand cmd = null; DataTable dataTable = CreateDataTable(request); using (tgTransactionScope scope = new tgTransactionScope()) { using (VistaDBDataAdapter da = new VistaDBDataAdapter()) { da.AcceptChangesDuringUpdate = false; da.ContinueUpdateOnError = request.ContinueUpdateOnError; try { cmd = da.DeleteCommand = Shared.BuildDynamicDeleteCommand(request, request.CollectionSavePacket[0].ModifiedColumns); tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); DataRow[] singleRow = new DataRow[1]; // Delete each record foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); SetOriginalValues(request, packet, row, true); row.AcceptChanges(); row.Delete(); singleRow[0] = row; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, packet, "SaveCollectionDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } if (row.HasErrors) { request.FireOnError(packet, row.RowError); } dataTable.Rows.Clear(); // ADO.NET won't let us reuse the same DataRow } } finally { tgTransactionScope.DeEnlist(cmd); cmd.Dispose(); } } scope.Complete(); } return request.Table; } static private DataTable SaveDynamicEntity(tgDataRequest request) { bool needToDelete = request.EntitySavePacket.RowState == tgDataRowState.Deleted; DataTable dataTable = CreateDataTable(request); using (VistaDBDataAdapter da = new VistaDBDataAdapter()) { da.AcceptChangesDuringUpdate = false; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); VistaDBCommand cmd = null; switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: cmd = da.InsertCommand = Shared.BuildDynamicInsertCommand(request, request.EntitySavePacket.ModifiedColumns); SetModifiedValues(request, request.EntitySavePacket, row); break; case tgDataRowState.Modified: cmd = da.UpdateCommand = Shared.BuildDynamicUpdateCommand(request, request.EntitySavePacket.ModifiedColumns); SetOriginalValues(request, request.EntitySavePacket, row, false); SetModifiedValues(request, request.EntitySavePacket, row); row.AcceptChanges(); row.SetModified(); break; case tgDataRowState.Deleted: cmd = da.DeleteCommand = Shared.BuildDynamicDeleteCommand(request, null); SetOriginalValues(request, request.EntitySavePacket, row, true); row.AcceptChanges(); row.Delete(); break; } if (!needToDelete && request.Properties != null) { request.Properties["tgDataRequest"] = request; request.Properties["esEntityData"] = request.EntitySavePacket; dataTable.ExtendedProperties["props"] = request.Properties; } DataRow[] singleRow = new DataRow[1]; singleRow[0] = row; try { if (!request.IgnoreComputedColumns) { da.RowUpdated += new VistaDBRowUpdatedEventHandler(OnRowUpdated); } tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, request.EntitySavePacket, "SaveEntityDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.EntitySavePacket.RowState != tgDataRowState.Deleted && cmd.Parameters != null) { foreach (VistaDBParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: request.EntitySavePacket.CurrentValues[param.SourceColumn] = param.Value; break; } } } cmd.Dispose(); } return dataTable; } static private DataTable CreateDataTable(tgDataRequest request) { DataTable dataTable = new DataTable(); DataColumnCollection dataColumns = dataTable.Columns; tgColumnMetadataCollection cols = request.Columns; if (request.SelectedColumns == null) { tgColumnMetadata col; for (int i = 0; i < cols.Count; i++) { col = cols[i]; dataColumns.Add(new DataColumn(col.Name, col.Type)); } } else { foreach (string col in request.SelectedColumns.Keys) { dataColumns.Add(new DataColumn(col, cols[col].Type)); } } return dataTable; } private static void SetOriginalValues(tgDataRequest request, tgEntitySavePacket packet, DataRow row, bool primaryKeysAndConcurrencyOnly) { foreach (tgColumnMetadata col in request.Columns) { if (primaryKeysAndConcurrencyOnly && (!col.IsInPrimaryKey && !col.IsConcurrency && !col.IsTiraggoConcurrency)) continue; string columnName = col.Name; if (packet.OriginalValues.ContainsKey(columnName)) { row[columnName] = packet.OriginalValues[columnName]; } } } private static void SetModifiedValues(tgDataRequest request, tgEntitySavePacket packet, DataRow row) { foreach (string column in packet.ModifiedColumns) { if (request.Columns.FindByColumnName(column) != null) { row[column] = packet.CurrentValues[column]; } } } protected static void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e) { try { PropertyCollection props = e.Row.Table.ExtendedProperties; if (props.ContainsKey("props")) { props = (PropertyCollection)props["props"]; } if (e.Status == UpdateStatus.Continue && (e.StatementType == StatementType.Insert || e.StatementType == StatementType.Update)) { tgDataRequest request = props["tgDataRequest"] as tgDataRequest; tgEntitySavePacket packet = (tgEntitySavePacket)props["esEntityData"]; string source = props["Source"] as string; if (e.StatementType == StatementType.Insert) { if (props.Contains("AutoInc")) { string autoInc = props["AutoInc"] as string; VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; cmd.CommandText = "SELECT LastIdentity([" + autoInc + "]) FROM [" + source + "]"; object o = null; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace)) { try { o = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { o = cmd.ExecuteScalar(); } if (o != null) { e.Row[autoInc] = o; e.Command.Parameters["@" + autoInc].Value = o; } } if (props.Contains("EntitySpacesConcurrency")) { string esConcurrencyColumn = props["EntitySpacesConcurrency"] as string; packet.CurrentValues[esConcurrencyColumn] = 1; } } if (props.Contains("Timestamp")) { string column = props["Timestamp"] as string; VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; cmd.CommandText = "SELECT LastTimestamp('" + source + "');"; object o = null; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace)) { try { o = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { o = cmd.ExecuteScalar(); } if (o != null) { e.Command.Parameters["@" + column].Value = o; } } //------------------------------------------------------------------------------------------------- // Fetch any defaults, SQLite doesn't support output parameters so we gotta do this the hard way //------------------------------------------------------------------------------------------------- if (props.Contains("Defaults")) { // Build the Where parameter and parameters VistaDBCommand cmd = new VistaDBCommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; string select = (string)props["Defaults"]; string[] whereParameters = ((string)props["Where"]).Split(','); string comma = String.Empty; string where = String.Empty; int i = 1; foreach (string parameter in whereParameters) { VistaDBParameter p = new VistaDBParameter("@p" + i++.ToString(), e.Row[parameter]); cmd.Parameters.Add(p); where += comma + "[" + parameter + "]=" + p.ParameterName; comma = " AND "; } // Okay, now we can execute the sql and get any values that have defaults that were // null at the time of the insert and/or our timestamp cmd.CommandText = "SELECT " + select + " FROM [" + request.ProviderMetadata.Source + "] WHERE " + where + ";"; VistaDBDataReader rdr = null; try { #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace)) { try { rdr = cmd.ExecuteReader(CommandBehavior.SingleResult); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { rdr = cmd.ExecuteReader(CommandBehavior.SingleResult); } if (rdr.Read()) { select = select.Replace("[", String.Empty).Replace("]", String.Empty); string[] selectCols = select.Split(','); for (int k = 0; k < selectCols.Length; k++) { packet.CurrentValues[selectCols[k]] = rdr.GetValue(k); } } } finally { // Make sure we close the reader no matter what if (rdr != null) rdr.Close(); } } if (e.StatementType == StatementType.Update) { string colName = props["EntitySpacesConcurrency"] as string; object o = e.Row[colName]; VistaDBParameter p = e.Command.Parameters["@" + colName]; object v = null; switch (Type.GetTypeCode(o.GetType())) { case TypeCode.Int16: v = ((System.Int16)o) + 1; break; case TypeCode.Int32: v = ((System.Int32)o) + 1; break; case TypeCode.Int64: v = ((System.Int64)o) + 1; break; case TypeCode.UInt16: v = ((System.UInt16)o) + 1; break; case TypeCode.UInt32: v = ((System.UInt32)o) + 1; break; case TypeCode.UInt64: v = ((System.UInt64)o) + 1; break; } p.Value = v; } } } catch { } } } }
/* * Copyright 2006 Jeremias Maerki. * * 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; namespace ZXing.Datamatrix.Encoder { /// <summary> /// Symbol Character Placement Program. Adapted from Annex M.1 in ISO/IEC 16022:2000(E). /// </summary> public class DefaultPlacement { private readonly String codewords; private readonly int numrows; private readonly int numcols; private readonly byte[] bits; /// <summary> /// Main constructor /// </summary> /// <param name="codewords">the codewords to place</param> /// <param name="numcols">the number of columns</param> /// <param name="numrows">the number of rows</param> public DefaultPlacement(String codewords, int numcols, int numrows) { this.codewords = codewords; this.numcols = numcols; this.numrows = numrows; this.bits = new byte[numcols * numrows]; SupportClass.Fill(this.bits, (byte)2); //Initialize with "not set" value } public int Numrows { get { return numrows; } } public int Numcols { get { return numcols; } } public byte[] Bits { get { return bits; } } public bool getBit(int col, int row) { return bits[row * numcols + col] == 1; } private void setBit(int col, int row, bool bit) { bits[row * numcols + col] = (byte)(bit ? 1 : 0); } private bool hasBit(int col, int row) { return bits[row * numcols + col] < 2; } public void place() { int pos = 0; int row = 4; int col = 0; do { /* repeatedly first check for one of the special corner cases, then... */ if ((row == numrows) && (col == 0)) { corner1(pos++); } if ((row == numrows - 2) && (col == 0) && ((numcols % 4) != 0)) { corner2(pos++); } if ((row == numrows - 2) && (col == 0) && (numcols % 8 == 4)) { corner3(pos++); } if ((row == numrows + 4) && (col == 2) && ((numcols % 8) == 0)) { corner4(pos++); } /* sweep upward diagonally, inserting successive characters... */ do { if ((row < numrows) && (col >= 0) && !hasBit(col, row)) { utah(row, col, pos++); } row -= 2; col += 2; } while (row >= 0 && (col < numcols)); row++; col += 3; /* and then sweep downward diagonally, inserting successive characters, ... */ do { if ((row >= 0) && (col < numcols) && !hasBit(col, row)) { utah(row, col, pos++); } row += 2; col -= 2; } while ((row < numrows) && (col >= 0)); row += 3; col++; /* ...until the entire array is scanned */ } while ((row < numrows) || (col < numcols)); /* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */ if (!hasBit(numcols - 1, numrows - 1)) { setBit(numcols - 1, numrows - 1, true); setBit(numcols - 2, numrows - 2, true); } } private void module(int row, int col, int pos, int bit) { if (row < 0) { row += numrows; col += 4 - ((numrows + 4) % 8); } if (col < 0) { col += numcols; row += 4 - ((numcols + 4) % 8); } // Note the conversion: int v = codewords[pos]; v &= 1 << (8 - bit); setBit(col, row, v != 0); } /// <summary> /// Places the 8 bits of a utah-shaped symbol character in ECC200. /// </summary> /// <param name="row">The row.</param> /// <param name="col">The col.</param> /// <param name="pos">character position</param> private void utah(int row, int col, int pos) { module(row - 2, col - 2, pos, 1); module(row - 2, col - 1, pos, 2); module(row - 1, col - 2, pos, 3); module(row - 1, col - 1, pos, 4); module(row - 1, col, pos, 5); module(row, col - 2, pos, 6); module(row, col - 1, pos, 7); module(row, col, pos, 8); } private void corner1(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, 1, pos, 2); module(numrows - 1, 2, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner2(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 4, pos, 4); module(0, numcols - 3, pos, 5); module(0, numcols - 2, pos, 6); module(0, numcols - 1, pos, 7); module(1, numcols - 1, pos, 8); } private void corner3(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner4(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, numcols - 1, pos, 2); module(0, numcols - 3, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 3, pos, 6); module(1, numcols - 2, pos, 7); module(1, numcols - 1, pos, 8); } } }
using System; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using System.Collections.Generic; namespace Microsoft.Msagl.Core.Layout { /// <summary> /// Node of the graph /// </summary> #if TEST_MSAGL [Serializable] #endif public class Node : GeometryObject { #if DEBUG ///<summary> /// used for debugging purposes ///</summary> public object DebugId { get; set; } #endif #region Fields set by the client double padding = 1; /// <summary> /// Padding around the node: splines should not get closer than padding to the node boundary /// </summary> public double Padding { get { return padding; } set { padding = value; } } ICurve boundaryCurve; /// <summary> /// The engine assumes that the node boundaryCurve is defined relatively to the point (0,0) /// This must be a closed curve. /// </summary> public virtual ICurve BoundaryCurve { get { return boundaryCurve; } set { RaiseLayoutChangeEvent(value); boundaryCurve = value; } } /// <summary> /// The default constructor /// </summary> public Node() { } /// <summary> /// Creates a Node instance /// </summary> /// <param name="curve">node boundaryCurve</param> public Node(ICurve curve) { boundaryCurve = curve; } /// <summary> /// Create a node instance with the given curve and user data. /// </summary> public Node(ICurve curve, object userData) { this.boundaryCurve = curve; this.UserData = userData; } /// <summary> /// Gets the UserData string if present. /// </summary> /// <returns>The UserData string.</returns> public override string ToString() { if (UserData != null) { var ret = UserData.ToString(); #if TEST_MSAGL // if(DebugId!=null) // ret+= " "+DebugId.ToString(); #endif return ret; } return base.ToString(); } #endregion /// <summary> /// the list of in edges /// </summary> protected Set<Edge> inEdges_ = new Set<Edge>(); /// <summary> /// enumeration of the node incoming edges /// </summary> virtual public IEnumerable<Edge> InEdges { get { return inEdges_; } set { inEdges_ = (Set<Edge>)value; } } /// <summary> /// the list of out edges /// </summary> protected Set<Edge> outEdges_ = new Set<Edge>(); /// <summary> /// enumeration of the node outcoming edges /// </summary> virtual public IEnumerable<Edge> OutEdges { get { return outEdges_; } set { outEdges_ = (Set<Edge>)value; } } /// <summary> /// the list of self edges /// </summary> protected Set<Edge> selfEdges_ = new Set<Edge>(); /// <summary> ///enumeration of the node self edges /// </summary> virtual public IEnumerable<Edge> SelfEdges { get { return selfEdges_; } set { selfEdges_ = (Set<Edge>)value; } } List<Cluster> clusterParents = new List<Cluster>(); /// <summary> /// Parents (if any) of which this node is a member /// </summary> public IEnumerable<Cluster> ClusterParents { get { return clusterParents; } set { clusterParents = (List<Cluster>)value; } } /// <summary> /// Walk up the ancestor chain for this node /// </summary> /// <value>an IEnumerable of ancestor clusters</value> public IEnumerable<Cluster> AllClusterAncestors { get { Cluster parent = this.ClusterParents.FirstOrDefault(); while (parent != null) { yield return parent; parent = parent.ClusterParents.FirstOrDefault(); } } } /// <summary> /// Add the parent cluster to this node's list of parents /// </summary> /// <param name="parent"></param> public void AddClusterParent(Cluster parent) { ValidateArg.IsNotNull(parent, "parent"); Debug.Assert(parent != this); clusterParents.Add(parent); } /// <summary> /// removes a self edge /// </summary> /// <param name="edge"></param> public bool RemoveSelfEdge(Edge edge) { return selfEdges_.Remove(edge); } /// <summary> /// adds and outgoing edge /// </summary> /// <param name="edge"></param> public void AddOutEdge(Edge edge) { ValidateArg.IsNotNull(edge, "edge"); Debug.Assert(edge.Source != edge.Target); Debug.Assert(edge.Source == this); outEdges_.Insert(edge); } /// <summary> /// add an incoming edge /// </summary> /// <param name="edge"></param> public void AddInEdge(Edge edge) { ValidateArg.IsNotNull(edge, "edge"); Debug.Assert(edge.Source != edge.Target); Debug.Assert(edge.Target == this); inEdges_.Insert(edge); } /// <summary> /// adds a self edge /// </summary> /// <param name="edge"></param> public void AddSelfEdge(Edge edge) { ValidateArg.IsNotNull(edge, "edge"); Debug.Assert(edge.Target == this && edge.Source == this); selfEdges_.Insert(edge); } /// <summary> /// enumerates over all edges /// </summary> public IEnumerable<Edge> Edges { get { foreach (Edge e in outEdges_) yield return e; foreach (Edge e in inEdges_) yield return e; foreach (Edge e in selfEdges_) yield return e; } } #region Fields which are set by Msagl // Point center; /// <summary> /// return the center of the curve bounding box /// </summary> public Point Center { get { return BoundaryCurve.BoundingBox.Center; } set { var del = value - Center; if (del.X==0 && del.Y==0) return; RaiseLayoutChangeEvent(value); //an optimization can be appied here; move the boundary curve only on demand BoundaryCurve.Translate(del); } } /// <summary> /// sets the bounding curve scaled to fit the targetBounds /// </summary> /// <param name="targetBounds"></param> protected void FitBoundaryCurveToTarget(Rectangle targetBounds) { if (BoundaryCurve != null) { // RoundedRect is special, rather than simply scaling the geometry we want to keep the corner radii constant RoundedRect rr = BoundaryCurve as RoundedRect; if (rr == null) { Debug.Assert(BoundaryCurve.BoundingBox.Width > 0); Debug.Assert(BoundaryCurve.BoundingBox.Height > 0); double scaleX = targetBounds.Width / BoundaryCurve.BoundingBox.Width; double scaleY = targetBounds.Height / BoundaryCurve.BoundingBox.Height; BoundaryCurve.Translate(-BoundaryCurve.BoundingBox.LeftBottom); BoundaryCurve = BoundaryCurve.ScaleFromOrigin(scaleX, scaleY); BoundaryCurve.Translate(targetBounds.LeftBottom); } else { BoundaryCurve = rr.FitTo(targetBounds); } Debug.Assert(ApproximateComparer.Close(BoundaryCurve.BoundingBox, targetBounds, ApproximateComparer.UserDefinedTolerance), "FitToBounds didn't succeed in scaling/translating to target bounds"); } } /// <summary> /// the bounding box of the node /// </summary> override public Rectangle BoundingBox { get { return BoundaryCurve != null ? BoundaryCurve.BoundingBox : Rectangle.CreateAnEmptyBox(); } set { if(Math.Abs(value.Width - Width) < 0.01 && Math.Abs(value.Height - Height) < 0.01) { Center = value.Center; } else { this.FitBoundaryCurveToTarget(value); } } } /// <summary> /// Width of the node does not include the padding /// </summary> public double Width { get { return BoundaryCurve.BoundingBox.Width; } } /// <summary> /// Height of the node does not including the padding /// </summary> public double Height { get { return BoundaryCurve.BoundingBox.Height; } } /// <summary> /// returns the node degree /// </summary> public int Degree { get { return OutEdges.Count()+InEdges.Count()+SelfEdges.Count(); } } #endregion /// <summary> /// removes an outgoing edge /// </summary> /// <param name="edge"></param> /// <returns>True if the node is adjacent to the edge , and false otherwise.</returns> public bool RemoveInEdge(Edge edge) { return inEdges_.Remove(edge); } /// <summary> /// removes an incoming edge /// </summary> /// <param name="edge"></param> /// <returns>True if the node is adjacent to the edge , and false otherwise.</returns> public bool RemoveOutEdge(Edge edge) { return outEdges_.Remove(edge); } /// <summary> /// remove all edges /// </summary> public void ClearEdges() { inEdges_.Clear(); outEdges_.Clear(); } ///<summary> ///</summary> ///<param name="transformation"></param> public void Transform(PlaneTransformation transformation) { if (BoundaryCurve != null) BoundaryCurve = BoundaryCurve.Transform(transformation); } /// <summary> /// Determines if this node is a descendant of the given cluster. /// </summary> /// <returns>True if the node is a descendant of the cluster. False otherwise.</returns> public bool IsDescendantOf(Cluster cluster) { Queue<Cluster> parents = new Queue<Cluster>(this.ClusterParents); while (parents.Count > 0) { Cluster parent = parents.Dequeue(); if (parent == cluster) { return true; } foreach (Cluster grandParent in parent.ClusterParents) { parents.Enqueue(grandParent); } } return false; } internal bool UnderCollapsedCluster() { return ClusterParents.Any(c => c.IsCollapsed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.Sys.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (IOException) when (!disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference()) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="destination">The buffer to write the data into.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult) { Debug.Assert(_useAsyncIO); if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= destination.Length) { try { PrepareForReading(); new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span); _readPos += destination.Length; synchronousResult = destination.Length; return null; } catch (Exception exc) { synchronousResult = 0; return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. synchronousResult = 0; _asyncState.Memory = destination; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { Memory<byte> memory = thisRef._asyncState.Memory; thisRef._asyncState.Memory = default(Memory<byte>); return thisRef.ReadSpan(memory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &source.DangerousGetPinnableReference()) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="source">The buffer to write data from.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { try { PrepareForWriting(); source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length)); _writePos += source.Length; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.ReadOnlyMemory = source; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory; thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>); thisRef.WriteSpan(readOnlyMemory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { internal ReadOnlyMemory<byte> ReadOnlyMemory; internal Memory<byte> Memory; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ReferenceApiWeblessUmbraco.Areas.HelpPage.ModelDescriptions; using ReferenceApiWeblessUmbraco.Areas.HelpPage.Models; namespace ReferenceApiWeblessUmbraco.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
namespace Manssiere.Core.Graphics { using System; using System.IO; using Core; using OpenTK; using OpenTK.Graphics.OpenGL; /// <summary> /// OpenGl shader wrapper. /// </summary> public class Shader : IDisposable { private readonly int _programHandle; /// <summary> /// Create a new shader program. /// </summary> private Shader() { _programHandle = GL.CreateProgram(); } /// <summary> /// Load a new shader /// </summary> /// <param name="vertexShader">The vertexshader.</param> /// <param name="fragmentShader">The fragmentshader</param> public static Shader Load(StringReader vertexShader, StringReader fragmentShader) { var shader = new Shader(); string vertexShaderCode = vertexShader.ReadToEnd(); string fragmentShaderCode = fragmentShader.ReadToEnd(); if (string.IsNullOrEmpty(vertexShaderCode) && string.IsNullOrEmpty(fragmentShaderCode)) { throw new InvalidOperationException("Both vertex and fragement shader code are empty."); } if (string.IsNullOrEmpty(vertexShaderCode) == false) { shader.AttachShaderCode(vertexShaderCode, ShaderType.VertexShader); } if (string.IsNullOrEmpty(fragmentShaderCode) == false) { shader.AttachShaderCode(fragmentShaderCode, ShaderType.FragmentShader); } shader.Build(); return shader; } /// <summary> /// Load a new shader /// </summary> /// <param name="vertexShaderCode">The vertexshader code.</param> /// <param name="fragmentShaderCode">The fragmentshader code</param> public static Shader Load(string vertexShaderCode, string fragmentShaderCode) { return Load(new StringReader(vertexShaderCode), new StringReader(fragmentShaderCode)); } #region IDisposable Members ///<summary> ///Release the loaded shader ///</summary> ///<filterpriority>2</filterpriority> public void Dispose() { if (_programHandle > 0) GL.DeleteProgram(_programHandle); } #endregion /// <summary> /// Helper to use the framebuffer in a using construction. /// </summary> /// <returns>The framebuffer dispose helper.</returns> public IDisposable PushShader() { InternalEnableShader(); return new DisposableAction(InternalDisableShader); } /// <summary> /// (Re)link the shader program /// </summary> private void Build() { int status; GL.LinkProgram(_programHandle); GL.GetProgram(_programHandle, ProgramParameter.LinkStatus, out status); if (status != 1) { string info; GL.GetShaderInfoLog(_programHandle, out info); throw new ApplicationException("Error during shader program setup." + info); } InternalDisableShader(); } /// <summary> /// Enable this shader. /// </summary> private void InternalEnableShader() { GL.UseProgram(_programHandle); } /// <summary> /// Disable this shader. /// </summary> private static void InternalDisableShader() { GL.UseProgram(0); } /// <summary> /// Attach the code to the shader program. /// </summary> /// <param name="shaderCode">The shader code.</param> /// <param name="shaderType">The code type.</param> private void AttachShaderCode(string shaderCode, ShaderType shaderType) { int shaderHandle = GL.CreateShader(shaderType); int status; // load and compile the shader code GL.ShaderSource(shaderHandle, shaderCode); GL.CompileShader(shaderHandle); GL.GetShader(shaderHandle, ShaderParameter.CompileStatus, out status); if (status != 1) { string log; GL.GetShaderInfoLog(shaderHandle, out log); throw new ApplicationException("Can not compile the shader code" + log); } // attach to the program GL.AttachShader(_programHandle, shaderHandle); // flag the shader objects for deletion. They won't be deleted until the program is deleted. GL.DeleteShader(shaderHandle); } private int GetUniformLocation(string name) { if (name == null) throw new ArgumentNullException("name"); int id = GL.GetUniformLocation(_programHandle, name); if (id == -1) { throw new ApplicationException(string.Format("Can not locate uniform with name {0}", name)); } return id; } /// <summary> /// Set a Single value on a shader variable. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value.</param> public void SetUniform(string name, Single value) { GL.Uniform1(GetUniformLocation(name), value); } /// <summary> /// Set a Single cast to a Single value on a shader variable. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value.</param> public void SetUniform(string name, double value) { GL.Uniform1(GetUniformLocation(name), (Single) value); } /// <summary> /// Set a Vector3D value on a shader variable. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value.</param> public void SetUniform(string name, Vector3 value) { GL.Uniform3(GetUniformLocation(name), value.X, value.Y, value.Z); } /// <summary> /// Set a Vector4D value on a shader variable. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value.</param> public void SetUniform(string name, Vector4 value) { GL.Uniform4(GetUniformLocation(name), value.X, value.Y, value.Z, value.W); } /// <summary> /// Set a int 1 value on a shader variable. /// </summary> /// <remarks>When binding textures, bind to the channel not the texture handle!</remarks> /// <param name="name">The name of the variable.</param> /// <param name="value">The value.</param> public void SetUniform(string name, int value) { GL.Uniform1(GetUniformLocation(name), value); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075XPathDocumentCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments(".ctor"); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075XPathDocumentBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments(".ctor"); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseXPathDocumentWithoutReaderShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; using System.Xml.XPath; namespace TestNamespace { public class UseXmlReaderForXPathDocument { public void TestMethod(string path) { XPathDocument doc = new XPathDocument(path); } } } ", GetCA3075XPathDocumentCSharpResultAt(11, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Imports System.Xml.XPath Namespace TestNamespace Public Class UseXmlReaderForXPathDocument Public Sub TestMethod(path As String) Dim doc As New XPathDocument(path) End Sub End Class End Namespace", GetCA3075XPathDocumentBasicResultAt(8, 24) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInGetShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml.XPath; class TestClass { public XPathDocument Test { get { var xml = """"; XPathDocument doc = new XPathDocument(xml); return doc; } } }", GetCA3075XPathDocumentCSharpResultAt(11, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml.XPath Class TestClass Public ReadOnly Property Test() As XPathDocument Get Dim xml = """" Dim doc As New XPathDocument(xml) Return doc End Get End Property End Class", GetCA3075XPathDocumentBasicResultAt(8, 24) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInSetShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml.XPath; class TestClass { XPathDocument privateDoc; public XPathDocument GetDoc { set { if (value == null) { var xml = """"; XPathDocument doc = new XPathDocument(xml); privateDoc = doc; } else privateDoc = value; } } }", GetCA3075XPathDocumentCSharpResultAt(14, 41) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml.XPath Class TestClass Private privateDoc As XPathDocument Public WriteOnly Property GetDoc() As XPathDocument Set If value Is Nothing Then Dim xml = """" Dim doc As New XPathDocument(xml) privateDoc = doc Else privateDoc = value End If End Set End Property End Class", GetCA3075XPathDocumentBasicResultAt(10, 28) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInTryBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml.XPath; class TestClass { private void TestMethod() { try { var xml = """"; XPathDocument doc = new XPathDocument(xml); } catch (Exception) { throw; } finally { } } }", GetCA3075XPathDocumentCSharpResultAt(12, 37) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Xml.XPath Class TestClass Private Sub TestMethod() Try Dim xml = """" Dim doc As New XPathDocument(xml) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075XPathDocumentBasicResultAt(9, 24) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInCatchBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml.XPath; class TestClass { private void TestMethod() { try { } catch (Exception) { var xml = """"; XPathDocument doc = new XPathDocument(xml); } finally { } } }", GetCA3075XPathDocumentCSharpResultAt(13, 37) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Xml.XPath Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim xml = """" Dim doc As New XPathDocument(xml) Finally End Try End Sub End Class", GetCA3075XPathDocumentBasicResultAt(10, 24) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInFinallyBlockShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml.XPath; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var xml = """"; XPathDocument doc = new XPathDocument(xml); } } }", GetCA3075XPathDocumentCSharpResultAt(14, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Xml.XPath Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim xml = """" Dim doc As New XPathDocument(xml) End Try End Sub End Class", GetCA3075XPathDocumentBasicResultAt(12, 24) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInAsyncAwaitShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Xml.XPath; class TestClass { private async Task TestMethod() { await Task.Run(() => { var xml = """"; XPathDocument doc = new XPathDocument(xml); }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075XPathDocumentCSharpResultAt(11, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Xml.XPath Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim xml = """" Dim doc As New XPathDocument(xml) End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075XPathDocumentBasicResultAt(9, 20) ); } [Fact] public async Task UseXPathDocumentWithoutReaderInDelegateShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml.XPath; class TestClass { delegate void Del(); Del d = delegate () { var xml = """"; XPathDocument doc = new XPathDocument(xml); }; }", GetCA3075XPathDocumentCSharpResultAt(10, 29) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml.XPath Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim xml = """" Dim doc As New XPathDocument(xml) End Sub End Class", GetCA3075XPathDocumentBasicResultAt(9, 16) ); } [Fact] public async Task UseXPathDocumentWithXmlReaderShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; using System.Xml.XPath; namespace TestNamespace { public class UseXmlReaderForXPathDocument { public void TestMethod17(XmlReader reader) { XPathDocument doc = new XPathDocument(reader); } } } " ); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of Protection Profile operations for the Site Recovery /// extension. /// </summary> public partial interface IProtectionProfileOperations { /// <summary> /// Creates a profile /// </summary> /// <param name='name'> /// Input to associate profile /// </param> /// <param name='input'> /// Input to associate profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> AssociateAsync(string name, ProtectionProfileAssociationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='name'> /// Input to associate profile /// </param> /// <param name='input'> /// Input to associate profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginAssociatingAsync(string name, ProtectionProfileAssociationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='input'> /// Input to create profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginCreatingAsync(CreateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deletes a ProtectionProfile /// </summary> /// <param name='name'> /// ProtectionProfile name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDeletingAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='name'> /// Input to dissociate profile /// </param> /// <param name='input'> /// Input to dissociate profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDissociatingAsync(string name, DisassociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Update protection profile. /// </summary> /// <param name='input'> /// input. /// </param> /// <param name='protectionProfileId'> /// Profile id. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginUpdatingAsync(UpdateProtectionProfileInput input, string protectionProfileId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='input'> /// Input to create profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> CreateAsync(CreateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deletes a ProtectionProfile /// </summary> /// <param name='name'> /// ProtectionProfile name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DeleteAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a profile /// </summary> /// <param name='name'> /// Input to dissociate profile /// </param> /// <param name='input'> /// Input to create profile /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DissociateAsync(string name, DisassociateProtectionProfileInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Get the protected Profile by Id. /// </summary> /// <param name='protectionProfileId'> /// Protection Profile ID. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Protection Profile object. /// </returns> Task<ProtectionProfileResponse> GetAsync(string protectionProfileId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<AssociateProtectionProfileOperationResponse> GetAssociateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<CreateProfileOperationResponse> GetCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<DeleteProtectionProfileOperationResponse> GetDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<DissociateProtectionProfileOperationResponse> GetDissociateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<UpdateProtectionProfileOperationResponse> GetUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Get the list of all ProtectionContainers for the given server. /// </summary> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list ProtectionProfiles operation. /// </returns> Task<ProtectionProfileListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Update protection profile. /// </summary> /// <param name='input'> /// input. /// </param> /// <param name='protectionProfileId'> /// Profile id. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> UpdateAsync(UpdateProtectionProfileInput input, string protectionProfileId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); } }
// Copyright (c) 2010-2013 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. #if DIRECTX11_1 using System; namespace SharpDX.Direct2D1 { public partial class DeviceContext { /// <summary> /// Initializes a new instance of the <see cref="DeviceContext"/> class. /// </summary> /// <param name="surface">The surface.</param> /// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged> public DeviceContext(SharpDX.DXGI.Surface surface) : base(IntPtr.Zero) { D2D1.CreateDeviceContext(surface, null, this); } /// <summary> /// Initializes a new instance of the <see cref="Device"/> class. /// </summary> /// <param name="surface">The surface.</param> /// <param name="creationProperties">The creation properties.</param> /// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged> public DeviceContext(SharpDX.DXGI.Surface surface, CreationProperties creationProperties) : base(IntPtr.Zero) { D2D1.CreateDeviceContext(surface, creationProperties, this); } /// <summary> /// Initializes a new instance of the <see cref="DeviceContext"/> class using an existing <see cref="Device"/>. /// </summary> /// <param name="device">The device.</param> /// <param name="options">The options to be applied to the created device context.</param> /// <remarks> /// The new device context will not have a selected target bitmap. The caller must create and select a bitmap as the target surface of the context. /// </remarks> /// <unmanaged>HRESULT ID2D1Device::CreateDeviceContext([In] D2D1_DEVICE_CONTEXT_OPTIONS options,[Out] ID2D1DeviceContext** deviceContext)</unmanaged> public DeviceContext(Device device, DeviceContextOptions options) : base(IntPtr.Zero) { device.CreateDeviceContext(options, this); } /// <summary> /// No documentation. /// </summary> /// <param name="effect">No documentation.</param> /// <param name="targetOffset">No documentation.</param> /// <param name="interpolationMode">No documentation.</param> /// <param name="compositeMode">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged> public void DrawImage(SharpDX.Direct2D1.Effect effect, SharpDX.Vector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver) { using (var output = effect.Output) DrawImage(output, targetOffset, null, interpolationMode, compositeMode); } /// <summary> /// No documentation. /// </summary> /// <param name="effect">No documentation.</param> /// <param name="interpolationMode">No documentation.</param> /// <param name="compositeMode">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged> public void DrawImage(SharpDX.Direct2D1.Effect effect, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver) { using (var output = effect.Output) DrawImage(output, null, null, interpolationMode, compositeMode); } /// <summary> /// No documentation. /// </summary> /// <param name="image">No documentation.</param> /// <param name="targetOffset">No documentation.</param> /// <param name="interpolationMode">No documentation.</param> /// <param name="compositeMode">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged> public void DrawImage(SharpDX.Direct2D1.Image image, SharpDX.Vector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver) { DrawImage(image, targetOffset, null, interpolationMode, compositeMode); } /// <summary> /// No documentation. /// </summary> /// <param name="image">No documentation.</param> /// <param name="interpolationMode">No documentation.</param> /// <param name="compositeMode">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged> public void DrawImage(SharpDX.Direct2D1.Image image, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver) { DrawImage(image, null, null, interpolationMode, compositeMode); } /// <summary> /// Draws the bitmap. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="opacity">The opacity.</param> /// <param name="interpolationMode">The interpolation mode.</param> /// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged> public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode) { DrawBitmap(bitmap, null, opacity, interpolationMode, null, null); } /// <summary> /// Draws the bitmap. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="opacity">The opacity.</param> /// <param name="interpolationMode">The interpolation mode.</param> /// <param name="perspectiveTransformRef">The perspective transform ref.</param> /// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged> public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, SharpDX.Matrix perspectiveTransformRef) { DrawBitmap(bitmap, null, opacity, interpolationMode, null, perspectiveTransformRef); } /// <summary> /// Draws the bitmap. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="opacity">The opacity.</param> /// <param name="interpolationMode">The interpolation mode.</param> /// <param name="sourceRectangle">The source rectangle.</param> /// <param name="perspectiveTransformRef">The perspective transform ref.</param> /// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged> public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, SharpDX.RectangleF sourceRectangle, SharpDX.Matrix perspectiveTransformRef) { DrawBitmap(bitmap, null, opacity, interpolationMode, sourceRectangle, perspectiveTransformRef); } /// <summary> /// No documentation. /// </summary> /// <param name="layerParameters">No documentation.</param> /// <param name="layer">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::PushLayer([In] const D2D1_LAYER_PARAMETERS1* layerParameters,[In, Optional] ID2D1Layer* layer)</unmanaged> public void PushLayer(SharpDX.Direct2D1.LayerParameters1 layerParameters, SharpDX.Direct2D1.Layer layer) { PushLayer(ref layerParameters, layer); } /// <summary> /// Gets the effect invalid rectangles. /// </summary> /// <param name="effect">The effect.</param> /// <returns></returns> /// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectInvalidRectangles([In] ID2D1Effect* effect,[Out, Buffer] D2D_RECT_F* rectangles,[In] unsigned int rectanglesCount)</unmanaged> public SharpDX.RectangleF[] GetEffectInvalidRectangles(SharpDX.Direct2D1.Effect effect) { var invalidRects = new RectangleF[GetEffectInvalidRectangleCount(effect)]; if (invalidRects.Length == 0) return invalidRects; GetEffectInvalidRectangles(effect, invalidRects, invalidRects.Length); return invalidRects; } /// <summary> /// Gets the effect required input rectangles. /// </summary> /// <param name="renderEffect">The render effect.</param> /// <param name="inputDescriptions">The input descriptions.</param> /// <returns></returns> /// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged> public SharpDX.RectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions) { var result = new RectangleF[inputDescriptions.Length]; GetEffectRequiredInputRectangles(renderEffect, null, inputDescriptions, result, inputDescriptions.Length); return result; } /// <summary> /// Gets the effect required input rectangles. /// </summary> /// <param name="renderEffect">The render effect.</param> /// <param name="renderImageRectangle">The render image rectangle.</param> /// <param name="inputDescriptions">The input descriptions.</param> /// <returns></returns> /// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged> public SharpDX.RectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, SharpDX.RectangleF renderImageRectangle, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions) { var result = new RectangleF[inputDescriptions.Length]; GetEffectRequiredInputRectangles(renderEffect, renderImageRectangle, inputDescriptions, result, inputDescriptions.Length); return result; } /// <summary> /// No documentation. /// </summary> /// <param name="opacityMask">No documentation.</param> /// <param name="brush">No documentation.</param> /// <unmanaged>void ID2D1DeviceContext::FillOpacityMask([In] ID2D1Bitmap* opacityMask,[In] ID2D1Brush* brush,[In, Optional] const D2D_RECT_F* destinationRectangle,[In, Optional] const D2D_RECT_F* sourceRectangle)</unmanaged> public void FillOpacityMask(SharpDX.Direct2D1.Bitmap opacityMask, SharpDX.Direct2D1.Brush brush) { FillOpacityMask(opacityMask, brush, null, null); } } } #endif
using Microsoft.VisualBasic; using System; using System.Collections; using System.Data; using System.Diagnostics; using System.Collections; using System.Data.SqlClient; using TarsimAvlCL; using System.Collections.Generic; namespace TarsimAvlDAL { public class PersonalClass : DB { public int insert(ClPersonal c, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_Personal_Insert", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser;// + logparam.GetBrowserVersion(); cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url;//(); cmd.Parameters.Add(new SqlParameter("CodeMelli", SqlDbType.NVarChar)).Value = c.CodeMelli; cmd.Parameters.Add(new SqlParameter("ShomarShenasname", SqlDbType.NVarChar)).Value = c.ShomarShenasname; cmd.Parameters.Add(new SqlParameter("Name", SqlDbType.NVarChar)).Value = c.Name; cmd.Parameters.Add(new SqlParameter("Family", SqlDbType.NVarChar)).Value = c.Family; cmd.Parameters.Add(new SqlParameter("FatherName", SqlDbType.NVarChar)).Value = c.FatherName; cmd.Parameters.Add(new SqlParameter("JensiyyatTypeId", SqlDbType.Int)).Value = c.JensiyyatTypeId; cmd.Parameters.Add(new SqlParameter("Mobile", SqlDbType.NVarChar)).Value = c.Mobile; cmd.Parameters.Add(new SqlParameter("Active", SqlDbType.Bit)).Value = c.Active; cmd.Parameters.Add(new SqlParameter("UserName", SqlDbType.NVarChar)).Value = c.UserName; cmd.Parameters.Add(new SqlParameter("Pass", SqlDbType.NVarChar)).Value = c.Pass; cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.Int)).Value = c.OrganID; cmd.Parameters.Add(new SqlParameter("SematID", SqlDbType.Int)).Value = c.SematID; cmd.Parameters.Add(new SqlParameter("personTypeID", SqlDbType.Int)).Value = c.personTypeID; cmd.Parameters.Add(new SqlParameter("PersonaliCode", SqlDbType.NVarChar)).Value = c.PersonaliCode; cmd.Parameters.Add(new SqlParameter("BirthDate", SqlDbType.DateTime)).Value = c.BirthDate; cmd.Parameters.Add(new SqlParameter("SodorLocation", SqlDbType.NVarChar)).Value = c.SodorLocation; cmd.Parameters.Add(new SqlParameter("Tel", SqlDbType.NVarChar)).Value = c.Tel; cmd.Parameters.Add(new SqlParameter("DegreeEducation", SqlDbType.Int)).Value = c.DegreeEducation; cmd.Parameters.Add(new SqlParameter("DriveCertificateDate", SqlDbType.DateTime)).Value = c.DriveCertificateDate; cmd.Parameters.Add(new SqlParameter("Background_crime", SqlDbType.NVarChar)).Value = c.Background_crime; cmd.Parameters.Add(new SqlParameter("Health_Test", SqlDbType.Int)).Value = c.Health_Test; cmd.Parameters.Add(new SqlParameter("CarID", SqlDbType.Int)).Value = c.CarID; cmd.Parameters.Add(new SqlParameter("DriverLineId", SqlDbType.Int)).Value = c.DriverLineId; cmd.Parameters.Add(new SqlParameter("ActivityPermission", SqlDbType.Int)).Value = c.ActivityPermission; cmd.Parameters.Add(new SqlParameter("Adress", SqlDbType.NVarChar)).Value = c.Adress; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } //--------------------------------------------------------------------------------------------------------- public CLPersonalList GetList(ClPersonalFilter c, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_Personal_GetList", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("ShomarShenasname", SqlDbType.NVarChar)).Value = c.ClPersonal.ShomarShenasname; cmd.Parameters.Add(new SqlParameter("PersonalID", SqlDbType.Int)).Value = c.ClPersonal.PersonalID; cmd.Parameters.Add(new SqlParameter("personTypeID", SqlDbType.Int)).Value = c.ClPersonal.personTypeID; cmd.Parameters.Add(new SqlParameter("personTypeID2", SqlDbType.NVarChar)).Value = c.ClPersonal.personTypeID2; cmd.Parameters.Add(new SqlParameter("CodeMelli", SqlDbType.NVarChar)).Value = c.ClPersonal.CodeMelli; cmd.Parameters.Add(new SqlParameter("Name", SqlDbType.NVarChar)).Value = c.ClPersonal.Name; cmd.Parameters.Add(new SqlParameter("Family", SqlDbType.NVarChar)).Value = c.ClPersonal.Family; cmd.Parameters.Add(new SqlParameter("FatherName", SqlDbType.NVarChar)).Value = c.ClPersonal.FatherName; cmd.Parameters.Add(new SqlParameter("JensiyyatTypeId", SqlDbType.Int)).Value = c.ClPersonal.JensiyyatTypeId; cmd.Parameters.Add(new SqlParameter("Mobile", SqlDbType.NVarChar)).Value = c.ClPersonal.Mobile; cmd.Parameters.Add(new SqlParameter("Active", SqlDbType.Bit)).Value = c.ClPersonal.Active; cmd.Parameters.Add(new SqlParameter("UserName", SqlDbType.NVarChar)).Value = c.ClPersonal.UserName; cmd.Parameters.Add(new SqlParameter("Pass", SqlDbType.NVarChar)).Value = c.ClPersonal.Pass; cmd.Parameters.Add(new SqlParameter("PersonaliCode", SqlDbType.NVarChar)).Value = c.ClPersonal.PersonaliCode; cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.Int)).Value = c.ClPersonal.OrganID; cmd.Parameters.Add(new SqlParameter("SematID", SqlDbType.Int)).Value = c.ClPersonal.SematID; cmd.Parameters.Add(new SqlParameter("CarID", SqlDbType.Int)).Value = c.ClPersonal.CarID; cmd.Parameters.Add(new SqlParameter(PAGEINDEX_PARAM, SqlDbType.Int)).Value = c.PageIndex; cmd.Parameters.Add(new SqlParameter(PAGESIZE_PARAM, SqlDbType.Int)).Value = c.PageSize; if (String.IsNullOrEmpty(c.OrderBy)) c.OrderBy = "PersonalID "; cmd.Parameters.Add(new SqlParameter(ORDERBY_PARAM, SqlDbType.NVarChar)).Value = c.OrderBy; if (string.IsNullOrEmpty(c.Order)) c.Order = "desc"; cmd.Parameters.Add(new SqlParameter(ORDER_PARAM, SqlDbType.NVarChar)).Value = c.Order; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); //DataSet ds = new DataSet(); SqlDataReader dataReader = null; var PersonalList = new CLPersonalList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { if ((PersonalList.RowCount == null || PersonalList.RowCount == 0) && dataReader["ROW_COUNT"] != DBNull.Value) PersonalList.RowCount = Convert.ToInt32(dataReader["ROW_COUNT"]); ClPersonal metadatadb = new ClPersonal(); if (dataReader["PersonalID"] != DBNull.Value) { //metadatadb.MetaDataID = Convert.ToInt32(dataReader[metadatadb.METADATAID_FIELD]); metadatadb.FillForObject(dataReader); PersonalList.Rows.Add(metadatadb); } } //da.Fill(ds); dataReader.Close(); ProjectConnection.Close(); return PersonalList; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public CLPersonalList GetListRep(ClPersonalFilter c, LogParam logparam) { SqlCommand cmd = new SqlCommand("Rep_Prc_Personal", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("ShomarShenasname", SqlDbType.NVarChar)).Value = c.ClPersonal.ShomarShenasname; cmd.Parameters.Add(new SqlParameter("PersonalID", SqlDbType.Int)).Value = c.ClPersonal.PersonalID; cmd.Parameters.Add(new SqlParameter("personTypeID", SqlDbType.Int)).Value = c.ClPersonal.personTypeID; cmd.Parameters.Add(new SqlParameter("personTypeID2", SqlDbType.NVarChar)).Value = c.ClPersonal.personTypeID2; cmd.Parameters.Add(new SqlParameter("CodeMelli", SqlDbType.NVarChar)).Value = c.ClPersonal.CodeMelli; cmd.Parameters.Add(new SqlParameter("Name", SqlDbType.NVarChar)).Value = c.ClPersonal.Name; cmd.Parameters.Add(new SqlParameter("Family", SqlDbType.NVarChar)).Value = c.ClPersonal.Family; cmd.Parameters.Add(new SqlParameter("FatherName", SqlDbType.NVarChar)).Value = c.ClPersonal.FatherName; cmd.Parameters.Add(new SqlParameter("JensiyyatTypeId", SqlDbType.Int)).Value = c.ClPersonal.JensiyyatTypeId; cmd.Parameters.Add(new SqlParameter("Mobile", SqlDbType.NVarChar)).Value = c.ClPersonal.Mobile; cmd.Parameters.Add(new SqlParameter("Active", SqlDbType.Bit)).Value = c.ClPersonal.Active; cmd.Parameters.Add(new SqlParameter("UserName", SqlDbType.NVarChar)).Value = c.ClPersonal.UserName; cmd.Parameters.Add(new SqlParameter("Pass", SqlDbType.NVarChar)).Value = c.ClPersonal.Pass; cmd.Parameters.Add(new SqlParameter("PersonaliCode", SqlDbType.NVarChar)).Value = c.ClPersonal.PersonaliCode; cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.Int)).Value = c.ClPersonal.OrganID; cmd.Parameters.Add(new SqlParameter("SematID", SqlDbType.Int)).Value = c.ClPersonal.SematID; cmd.Parameters.Add(new SqlParameter("CarID", SqlDbType.Int)).Value = c.ClPersonal.CarID; cmd.Parameters.Add(new SqlParameter(PAGEINDEX_PARAM, SqlDbType.Int)).Value = c.PageIndex; cmd.Parameters.Add(new SqlParameter(PAGESIZE_PARAM, SqlDbType.Int)).Value = c.PageSize; if (String.IsNullOrEmpty(c.OrderBy)) c.OrderBy = "PersonalID "; cmd.Parameters.Add(new SqlParameter(ORDERBY_PARAM, SqlDbType.NVarChar)).Value = c.OrderBy; if (string.IsNullOrEmpty(c.Order)) c.Order = "desc"; cmd.Parameters.Add(new SqlParameter(ORDER_PARAM, SqlDbType.NVarChar)).Value = c.Order; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); //DataSet ds = new DataSet(); SqlDataReader dataReader = null; var PersonalList = new CLPersonalList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { if ((PersonalList.RowCount == null || PersonalList.RowCount == 0) && dataReader["ROW_COUNT"] != DBNull.Value) PersonalList.RowCount = Convert.ToInt32(dataReader["ROW_COUNT"]); ClPersonal metadatadb = new ClPersonal(); if (dataReader["PersonalID"] != DBNull.Value) { //metadatadb.MetaDataID = Convert.ToInt32(dataReader[metadatadb.METADATAID_FIELD]); metadatadb.FillForObject(dataReader); PersonalList.Rows.Add(metadatadb); } } //da.Fill(ds); dataReader.Close(); ProjectConnection.Close(); return PersonalList; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public DataSet GetListRport(ClPersonal c) { SqlCommand cmd = new SqlCommand("Rep_Prc_Personal", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.NVarChar)).Value = c.OrganID; cmd.Parameters.Add(new SqlParameter("type", SqlDbType.NVarChar)).Value = c.personTypeID; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); try { ProjectConnection.Open(); da.Fill(ds); return ds; } catch (Exception ex) { return null; } finally { ProjectConnection.Close(); } } public CLCarList PersonalCarGetList(int UserID) { SqlCommand cmd = new SqlCommand("HJSP_Personal_GetCarList", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserID", SqlDbType.NVarChar)).Value = UserID; SqlDataReader dataReader = null; var PersonalList = new CLCarList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); ; while (dataReader.Read()) { ClCar metadatadb = new ClCar(); if (dataReader["CarID"] != DBNull.Value) { metadatadb.FillForObject(dataReader); PersonalList.Rows.Add(metadatadb); } } //da.Fill(ds); dataReader.Close(); ProjectConnection.Close(); return PersonalList; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public int SaveCars(int UserID, string Cars) { SqlCommand cmd = new SqlCommand("HJSP_Personal_SaveCars", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserID", SqlDbType.Int)).Value = UserID; cmd.Parameters.Add(new SqlParameter("Cars", SqlDbType.NVarChar)).Value = Cars; SqlDataReader dataReader = null; int Result = -1; try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); ; while (dataReader.Read()) { if (dataReader["Result"] != DBNull.Value) { Result = Convert.ToInt32(dataReader["Result"]); } } Result = 1; dataReader.Close(); ProjectConnection.Close(); return Result; } catch (Exception ex) { return -1; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } //--------------------------------------------------------------------------------------------------------- public int Update(ClPersonal c, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_Personal_Update", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("PersonalID", SqlDbType.Int)).Value = c.PersonalID; cmd.Parameters.Add(new SqlParameter("ShomarShenasname", SqlDbType.NVarChar)).Value = c.ShomarShenasname; cmd.Parameters.Add(new SqlParameter("CodeMelli", SqlDbType.NVarChar)).Value = c.CodeMelli; cmd.Parameters.Add(new SqlParameter("Name", SqlDbType.NVarChar)).Value = c.Name; cmd.Parameters.Add(new SqlParameter("Family", SqlDbType.NVarChar)).Value = c.Family; cmd.Parameters.Add(new SqlParameter("FatherName", SqlDbType.NVarChar)).Value = c.FatherName; cmd.Parameters.Add(new SqlParameter("JensiyyatTypeId", SqlDbType.Int)).Value = c.JensiyyatTypeId; cmd.Parameters.Add(new SqlParameter("Mobile", SqlDbType.NVarChar)).Value = c.Mobile; cmd.Parameters.Add(new SqlParameter("Active", SqlDbType.Bit)).Value = c.Active; cmd.Parameters.Add(new SqlParameter("UserName", SqlDbType.NVarChar)).Value = c.UserName; cmd.Parameters.Add(new SqlParameter("Pass", SqlDbType.NVarChar)).Value = c.Pass; cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.Int)).Value = c.OrganID; cmd.Parameters.Add(new SqlParameter("SematID", SqlDbType.Int)).Value = c.SematID; cmd.Parameters.Add(new SqlParameter("personTypeID", SqlDbType.Int)).Value = c.personTypeID; cmd.Parameters.Add(new SqlParameter("PersonaliCode", SqlDbType.NVarChar)).Value = c.PersonaliCode; cmd.Parameters.Add(new SqlParameter("BirthDate", SqlDbType.NVarChar)).Value = c.BirthDate; cmd.Parameters.Add(new SqlParameter("SodorLocation", SqlDbType.NVarChar)).Value = c.SodorLocation; cmd.Parameters.Add(new SqlParameter("Tel", SqlDbType.NVarChar)).Value = c.Tel; cmd.Parameters.Add(new SqlParameter("DegreeEducation", SqlDbType.Int)).Value = c.DegreeEducation; cmd.Parameters.Add(new SqlParameter("DriveCertificateDate", SqlDbType.NVarChar)).Value = c.DriveCertificateDate; cmd.Parameters.Add(new SqlParameter("Background_crime", SqlDbType.NVarChar)).Value = c.Background_crime; cmd.Parameters.Add(new SqlParameter("Health_Test", SqlDbType.Int)).Value = c.Health_Test; cmd.Parameters.Add(new SqlParameter("CarID", SqlDbType.Int)).Value = c.CarID; cmd.Parameters.Add(new SqlParameter("ActivityPermission", SqlDbType.Int)).Value = c.ActivityPermission; cmd.Parameters.Add(new SqlParameter("Adress", SqlDbType.NVarChar)).Value = c.Adress; cmd.Parameters.Add(new SqlParameter("DriverLineId", SqlDbType.Int)).Value = c.DriverLineId; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } //--------------------------------------------------------------------------------------------------------- public int Delete(string PersonalID, LogParam Logparam) { SqlCommand cmd = new SqlCommand("PRC_Personal_Delete", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = Logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = Logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = Logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = Logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = Logparam.Url; cmd.Parameters.Add(new SqlParameter("PersonalID", SqlDbType.Int)).Value = PersonalID; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } } }
using Microsoft.Data.Entity.Relational.Migrations; using Microsoft.Data.Entity.Relational.Migrations.Builders; using Microsoft.Data.Entity.Relational.Migrations.MigrationsModel; using System; namespace PartsUnlimitedWebsite.Migrations { public partial class InitialMigration : Migration { public override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable("AspNetRoles", c => new { Id = c.String(), ConcurrencyStamp = c.String(), Name = c.String(), NormalizedName = c.String() }) .PrimaryKey("PK_AspNetRoles", t => t.Id); migrationBuilder.CreateTable("AspNetRoleClaims", c => new { Id = c.Int(nullable: false, identity: true), ClaimType = c.String(), ClaimValue = c.String(), RoleId = c.String() }) .PrimaryKey("PK_AspNetRoleClaims", t => t.Id); migrationBuilder.CreateTable("AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), ClaimType = c.String(), ClaimValue = c.String(), UserId = c.String() }) .PrimaryKey("PK_AspNetUserClaims", t => t.Id); migrationBuilder.CreateTable("AspNetUserLogins", c => new { LoginProvider = c.String(), ProviderKey = c.String(), ProviderDisplayName = c.String(), UserId = c.String() }) .PrimaryKey("PK_AspNetUserLogins", t => new { t.LoginProvider, t.ProviderKey }); migrationBuilder.CreateTable("AspNetUserRoles", c => new { UserId = c.String(), RoleId = c.String() }) .PrimaryKey("PK_AspNetUserRoles", t => new { t.UserId, t.RoleId }); migrationBuilder.CreateTable("AspNetUsers", c => new { Id = c.String(), AccessFailedCount = c.Int(nullable: false), ConcurrencyStamp = c.String(), Email = c.String(), EmailConfirmed = c.Boolean(nullable: false), LockoutEnabled = c.Boolean(nullable: false), LockoutEnd = c.DateTimeOffset(), Name = c.String(), NormalizedEmail = c.String(), NormalizedUserName = c.String(), PasswordHash = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), TwoFactorEnabled = c.Boolean(nullable: false), UserName = c.String() }) .PrimaryKey("PK_AspNetUsers", t => t.Id); migrationBuilder.CreateTable("CartItem", c => new { CartItemId = c.Int(nullable: false, identity: true), CartId = c.String(), Count = c.Int(nullable: false), DateCreated = c.DateTime(nullable: false), ProductId = c.Int(nullable: false) }) .PrimaryKey("PK_CartItem", t => t.CartItemId); migrationBuilder.CreateTable("Category", c => new { CategoryId = c.Int(nullable: false, identity: true), Description = c.String(), Name = c.String() }) .PrimaryKey("PK_Category", t => t.CategoryId); migrationBuilder.CreateTable("Order", c => new { OrderId = c.Int(nullable: false, identity: true), Address = c.String(), City = c.String(), Country = c.String(), Email = c.String(), Name = c.String(), OrderDate = c.DateTime(nullable: false), Phone = c.String(), PostalCode = c.String(), State = c.String(), Total = c.Decimal(nullable: false), Username = c.String() }) .PrimaryKey("PK_Order", t => t.OrderId); migrationBuilder.CreateTable("OrderDetail", c => new { OrderDetailId = c.Int(nullable: false, identity: true), Quantity = c.Int(nullable: false), UnitPrice = c.Decimal(nullable: false), OrderId = c.Int(nullable: false), ProductId = c.Int(nullable: false) }) .PrimaryKey("PK_OrderDetail", t => t.OrderDetailId); migrationBuilder.CreateTable("Product", c => new { ProductId = c.Int(nullable: false, identity: true), Created = c.DateTime(nullable: false), Price = c.Decimal(nullable: false), ProductArtUrl = c.String(), SalePrice = c.Decimal(nullable: false), Title = c.String(), CategoryId = c.Int(nullable: false) }) .PrimaryKey("PK_Product", t => t.ProductId); migrationBuilder.CreateTable("Raincheck", c => new { RaincheckId = c.Int(nullable: false, identity: true), Name = c.String(), Quantity = c.Int(nullable: false), SalePrice = c.Double(nullable: false), StoreId = c.Int(nullable: false), ProductId = c.Int(nullable: false) }) .PrimaryKey("PK_Raincheck", t => t.RaincheckId); migrationBuilder.CreateTable("Store", c => new { StoreId = c.Int(nullable: false, identity: true), Name = c.String() }) .PrimaryKey("PK_Store", t => t.StoreId); migrationBuilder.AddForeignKey( "AspNetRoleClaims", "FK_AspNetRoleClaims_AspNetRoles_RoleId", new[] { "RoleId" }, "AspNetRoles", new[] { "Id" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "AspNetUserClaims", "FK_AspNetUserClaims_AspNetUsers_UserId", new[] { "UserId" }, "AspNetUsers", new[] { "Id" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "AspNetUserLogins", "FK_AspNetUserLogins_AspNetUsers_UserId", new[] { "UserId" }, "AspNetUsers", new[] { "Id" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "CartItem", "FK_CartItem_Product_ProductId", new[] { "ProductId" }, "Product", new[] { "ProductId" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "OrderDetail", "FK_OrderDetail_Order_OrderId", new[] { "OrderId" }, "Order", new[] { "OrderId" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "OrderDetail", "FK_OrderDetail_Product_ProductId", new[] { "ProductId" }, "Product", new[] { "ProductId" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "Product", "FK_Product_Category_CategoryId", new[] { "CategoryId" }, "Category", new[] { "CategoryId" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "Raincheck", "FK_Raincheck_Store_StoreId", new[] { "StoreId" }, "Store", new[] { "StoreId" }, cascadeDelete: false); migrationBuilder.AddForeignKey( "Raincheck", "FK_Raincheck_Product_ProductId", new[] { "ProductId" }, "Product", new[] { "ProductId" }, cascadeDelete: false); } public override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey("AspNetRoleClaims", "FK_AspNetRoleClaims_AspNetRoles_RoleId"); migrationBuilder.DropForeignKey("AspNetUserClaims", "FK_AspNetUserClaims_AspNetUsers_UserId"); migrationBuilder.DropForeignKey("AspNetUserLogins", "FK_AspNetUserLogins_AspNetUsers_UserId"); migrationBuilder.DropForeignKey("Product", "FK_Product_Category_CategoryId"); migrationBuilder.DropForeignKey("OrderDetail", "FK_OrderDetail_Order_OrderId"); migrationBuilder.DropForeignKey("CartItem", "FK_CartItem_Product_ProductId"); migrationBuilder.DropForeignKey("OrderDetail", "FK_OrderDetail_Product_ProductId"); migrationBuilder.DropForeignKey("Raincheck", "FK_Raincheck_Product_ProductId"); migrationBuilder.DropForeignKey("Raincheck", "FK_Raincheck_Store_StoreId"); migrationBuilder.DropTable("AspNetRoles"); migrationBuilder.DropTable("AspNetRoleClaims"); migrationBuilder.DropTable("AspNetUserClaims"); migrationBuilder.DropTable("AspNetUserLogins"); migrationBuilder.DropTable("AspNetUserRoles"); migrationBuilder.DropTable("AspNetUsers"); migrationBuilder.DropTable("CartItem"); migrationBuilder.DropTable("Category"); migrationBuilder.DropTable("Order"); migrationBuilder.DropTable("OrderDetail"); migrationBuilder.DropTable("Product"); migrationBuilder.DropTable("Raincheck"); migrationBuilder.DropTable("Store"); } } }
#region Using using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using TribalWars.Maps; using TribalWars.Maps.Drawing; using TribalWars.Maps.Drawing.Displays; using TribalWars.Maps.Drawing.Views; using TribalWars.Maps.Manipulators.Managers; using TribalWars.Maps.Monitoring; using TribalWars.Tools; using System.Globalization; using TribalWars.Villages; using TribalWars.Villages.Buildings; using TribalWars.Villages.Units; using TribalWars.WorldTemplate; using World = TribalWars.Worlds.World; #endregion namespace TribalWars.Worlds { /// <summary> /// Creates a whole bunch of classes from XML files /// </summary> public static class Builder { #region Setting Files /// <summary> /// Builds the classes from a sets file /// </summary> public static DisplaySettings ReadSettings(FileInfo file, Map map, Monitor monitor) { Debug.Assert(file.Exists); var newReader = XDocument.Load(file.FullName); var sets = new XmlReaderSettings(); sets.IgnoreWhitespace = true; sets.CloseInput = true; using (XmlReader r = XmlReader.Create(File.Open(file.FullName, FileMode.Open, FileAccess.Read), sets)) { r.ReadStartElement(); //DateTime date = XmlConvert.ToDateTime(r.GetAttribute("Date")); // You string youString = r.GetAttribute("Name"); r.ReadStartElement(); Player ply = World.Default.GetPlayer(youString); if (ply != null) { World.Default.You = ply; } else { World.Default.You = new Player(); } map.MarkerManager.ReadDefaultMarkers(r); r.ReadEndElement(); // Monitor monitor.ReadXml(r); // MainMap r.ReadStartElement(); // MainMap: Location Point? location = World.Default.GetCoordinates(r.GetAttribute("XY")); int x = 500; int y = 500; if (location.HasValue) { x = location.Value.X; y = location.Value.Y; } int z = Convert.ToInt32(r.GetAttribute("Zoom")); var displayType = (DisplayTypes)Enum.Parse(typeof(DisplayTypes), r.GetAttribute("Display"), true); map.HomeLocation = new Location(displayType, x, y, z); // MainMap: Display r.ReadStartElement(); Color backgroundColor = XmlHelper.GetColor(r.GetAttribute("BackgroundColor")); r.ReadStartElement(); bool continentLines = Convert.ToBoolean(r.ReadElementString("LinesContinent")); bool provinceLines = Convert.ToBoolean(r.ReadElementString("LinesProvince")); bool hideAbandoned = Convert.ToBoolean(r.ReadElementString("HideAbandoned")); bool markedOnly = Convert.ToBoolean(r.ReadElementString("MarkedOnly")); r.Skip(); r.ReadEndElement(); var displaySettings = new DisplaySettings(backgroundColor, continentLines, provinceLines, hideAbandoned, markedOnly); // Views World.Default.Views = ReadViews(newReader); // MainMap: Markers r.ReadStartElement(); map.MarkerManager.ReadUserDefinedMarkers(r); // MainMap: Manipulators Dictionary<ManipulatorManagerTypes, ManipulatorManagerBase> dict = map.Manipulators.Manipulators; map.Manipulators.CleanUp(); r.ReadToFollowing("Manipulator"); while (r.IsStartElement("Manipulator")) { var manipulatorType = (ManipulatorManagerTypes)Enum.Parse(typeof(ManipulatorManagerTypes), r.GetAttribute("Type")); if (dict.ContainsKey(manipulatorType)) { if (dict[manipulatorType].UseLegacyXmlWriter) { dict[manipulatorType].ReadXml(r); } else { r.Skip(); dict[manipulatorType].ReadXml(newReader); } } else { r.Skip(); } } r.ReadEndElement(); if (r.IsStartElement("RoamingManipulators")) { r.Skip(); map.Manipulators.ReadRoamingXml(newReader); } // End Main Map r.ReadEndElement(); return displaySettings; } } private static ViewsCollection ReadViews(XDocument xSets) { var xml = xSets.Descendants("Views") .First() .Elements("View") .Select(view => new { Type = view.Attribute("Type").Value, Name = view.Attribute("Name").Value, Drawers = view.Element("Drawers").Elements() }); var backgroundViews = new List<IBackgroundView>(); var decoratorViews = new List<IDecoratorView>(); foreach (var view in xml) { ViewBase viewToAdd = CreateView(view.Name, view.Type); foreach (var drawer in view.Drawers) { viewToAdd.ReadDrawerXml(drawer); } var toAddAsBackground = viewToAdd as IBackgroundView; if (toAddAsBackground != null) { backgroundViews.Add(toAddAsBackground); } else { Debug.Assert(viewToAdd is IDecoratorView); decoratorViews.Add(viewToAdd as IDecoratorView); } } return new ViewsCollection(backgroundViews, decoratorViews); } /// <summary> /// Write the settings file /// </summary> public static void WriteSettings(FileInfo file, Map map, Monitor monitor) { // There is the old and the new 'way' // old = XmlReader/Writer: error prone, difficult maintenance // new = XDocument/Linq: easier... var sets = new XmlWriterSettings(); sets.Indent = true; sets.IndentChars = " "; using (XmlWriter w = XmlWriter.Create(file.FullName, sets)) { w.WriteStartElement("Settings"); w.WriteAttributeString("Date", DateTime.Now.ToLongDateString()); w.WriteStartElement("You"); w.WriteAttributeString("Name", World.Default.You.Name); map.MarkerManager.WriteDefaultMarkers(w); w.WriteEndElement(); monitor.WriteXml(w); w.WriteStartElement("MainMap"); w.WriteStartElement("Location"); w.WriteAttributeString("Display", map.HomeLocation.Display.ToString()); w.WriteAttributeString("XY", map.HomeLocation.X + "|" + map.HomeLocation.Y); w.WriteAttributeString("Zoom", map.HomeLocation.Zoom.ToString(CultureInfo.InvariantCulture)); w.WriteEndElement(); w.WriteStartElement("Display"); w.WriteAttributeString("BackgroundColor", XmlHelper.SetColor(map.Display.Settings.BackgroundColor)); w.WriteElementString("LinesContinent", map.Display.Settings.ContinentLines.ToString()); w.WriteElementString("LinesProvince", map.Display.Settings.ProvinceLines.ToString()); w.WriteElementString("HideAbandoned", map.Display.Settings.HideAbandoned.ToString()); w.WriteElementString("MarkedOnly", map.Display.Settings.MarkedOnly.ToString()); w.WriteRaw(World.Default.Views.WriteViews()); w.WriteEndElement(); w.WriteStartElement("Markers"); map.MarkerManager.WriteUserDefinedMarkers(w); w.WriteEndElement(); // Manipulators w.WriteStartElement("Manipulators"); foreach (KeyValuePair<ManipulatorManagerTypes, ManipulatorManagerBase> pair in map.Manipulators.Manipulators) { w.WriteStartElement("Manipulator"); w.WriteAttributeString("Type", pair.Key.ToString()); if (pair.Value.UseLegacyXmlWriter) { pair.Value.WriteXml(w); } else { string resultingXml = pair.Value.WriteXml(); w.WriteRaw(resultingXml); } w.WriteEndElement(); } w.WriteEndElement(); w.WriteStartElement("RoamingManipulators"); w.WriteRaw(map.Manipulators.GetRoamingXml()); w.WriteEndElement(); // end MainMap w.WriteEndElement(); // end Settings w.WriteEndElement(); } } #endregion #region World Files /// <summary> /// Reads the world settings /// </summary> public static void ReadWorld(string worldXmlPath) { World w = World.Default; var info = WorldConfiguration.LoadFromFile(worldXmlPath); w.Settings.Server = new Uri(info.Server); w.Settings.Name = info.Name; w.Settings.ServerOffset = new TimeSpan(0, 0, Convert.ToInt32(info.Offset)); w.Settings.Speed = Convert.ToSingle(info.Speed, CultureInfo.InvariantCulture); w.Settings.UnitSpeed = Convert.ToSingle(info.UnitSpeed, CultureInfo.InvariantCulture); w.Structure.DownloadVillage = info.DataVillage; w.Structure.DownloadPlayer = info.DataPlayer; w.Structure.DownloadTribe = info.DataTribe; w.Settings.GameLink = info.GameVillage; w.Settings.GuestPlayerLink = info.GuestPlayer; w.Settings.GuestTribeLink = info.GuestTribe; w.Settings.TwStats.Default = new Uri(info.TWStatsGeneral); w.Settings.TwStats.Village = info.TWStatsVillage; w.Settings.TwStats.Player = info.TWStatsPlayer; w.Settings.TwStats.Tribe = info.TWStatsTribe; w.Settings.TwStats.PlayerGraph = info.TWStatsPlayerGraph; w.Settings.TwStats.TribeGraph = info.TWStatsTribeGraph; w.Settings.IconScenery = (IconDrawerFactory.Scenery)Convert.ToInt32(info.WorldDatScenery); w.Settings.Church = info.Church == "1"; WorldBuildings.Default.SetBuildings(ReadWorldBuildings(info.Buildings)); WorldUnits.Default.SetUnits(ReadWorldUnits(info.Units)); } /// <summary> /// Creates a view from the XML node /// </summary> private static ViewBase CreateView(string name, string type) { switch (type) { case "Points": return new PointsView(name); case "VillageType": return new VillageTypeView(name); } Debug.Assert(false); return null; } /// <summary> /// Loads the buildings from the World.xml stream /// </summary> private static Dictionary<BuildingTypes, Building> ReadWorldBuildings(IEnumerable<WorldConfigurationBuildingsBuilding> buildingsIn) { var buildingsOut = new Dictionary<BuildingTypes, Building>(); foreach (var building in buildingsIn) { var build = new Building(building.Name, building.Type, building.Image, building.Points, building.People); build.Production = building.Production; buildingsOut.Add(build.Type, build); } return buildingsOut; } /// <summary> /// Loads the units from the World.xml stream /// </summary> private static Dictionary<UnitTypes, Unit> ReadWorldUnits(IEnumerable<WorldConfigurationUnitsUnit> unitsIn) { var unitsOut = new Dictionary<UnitTypes, Unit>(); foreach (var unit in unitsIn) { int carry = Convert.ToInt32(unit.Carry); float speed = Convert.ToSingle(unit.Speed, CultureInfo.InvariantCulture); bool farmer = Convert.ToBoolean(unit.Farmer); bool hideAttacker = Convert.ToBoolean(unit.HideAttacker); bool offense = Convert.ToBoolean(unit.Offense); int people = Convert.ToInt32(unit.CostPeople); int wood = Convert.ToInt32(unit.CostWood); int clay = Convert.ToInt32(unit.CostClay); int iron = Convert.ToInt32(unit.CostIron); var u = new Unit(Convert.ToInt32(unit.Position), unit.Name, unit.Short, unit.Type, carry, farmer, hideAttacker, wood, clay, iron, people, speed, offense); unitsOut.Add(u.Type, u); } return unitsOut; } #endregion } }
using System; using System.Data; using System.Windows.Forms; using C1.Win.C1TrueDBGrid; using PCSComUtils.Admin.BO; using PCSComUtils.Common; using PCSComUtils.PCSExc; using PCSUtils.Log; using PCSUtils.Utils; namespace PCSUtils.Admin { /// <summary> /// ManageUser Form. /// Created by: Cuong NT /// Implemented by: Thien HD. /// </summary> public class ManageRole : System.Windows.Forms.Form { #region Declaration #region System Generated private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnDelete; private C1.Win.C1TrueDBGrid.C1TrueDBGrid tgridViewData; private System.Windows.Forms.Button btnSaveToDB; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; #endregion System Generated private const string THIS = "PCSUtils.Admin.ManageRole"; private const char CHR_SEPARATOR = ';'; private DataSet dstData; // this variable is used to store all data for this form; private bool blnEditUpdateData; //This variable is used to determine user action to edit or not private bool blnErrorOccurs; string strDeletedRole = string.Empty; #endregion Declaration #region Constructor, Destructor public ManageRole() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #endregion Constructor, Destructor #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ManageRole)); this.btnClose = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.tgridViewData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid(); this.btnSaveToDB = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.tgridViewData)).BeginInit(); this.SuspendLayout(); // // btnClose // this.btnClose.AccessibleDescription = resources.GetString("btnClose.AccessibleDescription"); this.btnClose.AccessibleName = resources.GetString("btnClose.AccessibleName"); this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnClose.Anchor"))); this.btnClose.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClose.BackgroundImage"))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnClose.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnClose.Dock"))); this.btnClose.Enabled = ((bool)(resources.GetObject("btnClose.Enabled"))); this.btnClose.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnClose.FlatStyle"))); this.btnClose.Font = ((System.Drawing.Font)(resources.GetObject("btnClose.Font"))); this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image"))); this.btnClose.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.ImageAlign"))); this.btnClose.ImageIndex = ((int)(resources.GetObject("btnClose.ImageIndex"))); this.btnClose.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnClose.ImeMode"))); this.btnClose.Location = ((System.Drawing.Point)(resources.GetObject("btnClose.Location"))); this.btnClose.Name = "btnClose"; this.btnClose.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnClose.RightToLeft"))); this.btnClose.Size = ((System.Drawing.Size)(resources.GetObject("btnClose.Size"))); this.btnClose.TabIndex = ((int)(resources.GetObject("btnClose.TabIndex"))); this.btnClose.Text = resources.GetString("btnClose.Text"); this.btnClose.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.TextAlign"))); this.btnClose.Visible = ((bool)(resources.GetObject("btnClose.Visible"))); this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnHelp // this.btnHelp.AccessibleDescription = resources.GetString("btnHelp.AccessibleDescription"); this.btnHelp.AccessibleName = resources.GetString("btnHelp.AccessibleName"); this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnHelp.Anchor"))); this.btnHelp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHelp.BackgroundImage"))); this.btnHelp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnHelp.Dock"))); this.btnHelp.Enabled = ((bool)(resources.GetObject("btnHelp.Enabled"))); this.btnHelp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnHelp.FlatStyle"))); this.btnHelp.Font = ((System.Drawing.Font)(resources.GetObject("btnHelp.Font"))); this.btnHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnHelp.Image"))); this.btnHelp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.ImageAlign"))); this.btnHelp.ImageIndex = ((int)(resources.GetObject("btnHelp.ImageIndex"))); this.btnHelp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnHelp.ImeMode"))); this.btnHelp.Location = ((System.Drawing.Point)(resources.GetObject("btnHelp.Location"))); this.btnHelp.Name = "btnHelp"; this.btnHelp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnHelp.RightToLeft"))); this.btnHelp.Size = ((System.Drawing.Size)(resources.GetObject("btnHelp.Size"))); this.btnHelp.TabIndex = ((int)(resources.GetObject("btnHelp.TabIndex"))); this.btnHelp.Text = resources.GetString("btnHelp.Text"); this.btnHelp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.TextAlign"))); this.btnHelp.Visible = ((bool)(resources.GetObject("btnHelp.Visible"))); this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnDelete // this.btnDelete.AccessibleDescription = resources.GetString("btnDelete.AccessibleDescription"); this.btnDelete.AccessibleName = resources.GetString("btnDelete.AccessibleName"); this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnDelete.Anchor"))); this.btnDelete.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnDelete.BackgroundImage"))); this.btnDelete.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnDelete.Dock"))); this.btnDelete.Enabled = ((bool)(resources.GetObject("btnDelete.Enabled"))); this.btnDelete.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnDelete.FlatStyle"))); this.btnDelete.Font = ((System.Drawing.Font)(resources.GetObject("btnDelete.Font"))); this.btnDelete.Image = ((System.Drawing.Image)(resources.GetObject("btnDelete.Image"))); this.btnDelete.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnDelete.ImageAlign"))); this.btnDelete.ImageIndex = ((int)(resources.GetObject("btnDelete.ImageIndex"))); this.btnDelete.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnDelete.ImeMode"))); this.btnDelete.Location = ((System.Drawing.Point)(resources.GetObject("btnDelete.Location"))); this.btnDelete.Name = "btnDelete"; this.btnDelete.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnDelete.RightToLeft"))); this.btnDelete.Size = ((System.Drawing.Size)(resources.GetObject("btnDelete.Size"))); this.btnDelete.TabIndex = ((int)(resources.GetObject("btnDelete.TabIndex"))); this.btnDelete.Text = resources.GetString("btnDelete.Text"); this.btnDelete.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnDelete.TextAlign"))); this.btnDelete.Visible = ((bool)(resources.GetObject("btnDelete.Visible"))); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // tgridViewData // this.tgridViewData.AccessibleDescription = resources.GetString("tgridViewData.AccessibleDescription"); this.tgridViewData.AccessibleName = resources.GetString("tgridViewData.AccessibleName"); this.tgridViewData.AllowAddNew = ((bool)(resources.GetObject("tgridViewData.AllowAddNew"))); this.tgridViewData.AllowArrows = ((bool)(resources.GetObject("tgridViewData.AllowArrows"))); this.tgridViewData.AllowColMove = ((bool)(resources.GetObject("tgridViewData.AllowColMove"))); this.tgridViewData.AllowColSelect = ((bool)(resources.GetObject("tgridViewData.AllowColSelect"))); this.tgridViewData.AllowDelete = ((bool)(resources.GetObject("tgridViewData.AllowDelete"))); this.tgridViewData.AllowDrag = ((bool)(resources.GetObject("tgridViewData.AllowDrag"))); this.tgridViewData.AllowFilter = ((bool)(resources.GetObject("tgridViewData.AllowFilter"))); this.tgridViewData.AllowHorizontalSplit = ((bool)(resources.GetObject("tgridViewData.AllowHorizontalSplit"))); this.tgridViewData.AllowRowSelect = ((bool)(resources.GetObject("tgridViewData.AllowRowSelect"))); this.tgridViewData.AllowSort = ((bool)(resources.GetObject("tgridViewData.AllowSort"))); this.tgridViewData.AllowUpdate = ((bool)(resources.GetObject("tgridViewData.AllowUpdate"))); this.tgridViewData.AllowUpdateOnBlur = ((bool)(resources.GetObject("tgridViewData.AllowUpdateOnBlur"))); this.tgridViewData.AllowVerticalSplit = ((bool)(resources.GetObject("tgridViewData.AllowVerticalSplit"))); this.tgridViewData.AlternatingRows = ((bool)(resources.GetObject("tgridViewData.AlternatingRows"))); this.tgridViewData.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("tgridViewData.Anchor"))); this.tgridViewData.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("tgridViewData.BackgroundImage"))); this.tgridViewData.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("tgridViewData.BorderStyle"))); this.tgridViewData.Caption = resources.GetString("tgridViewData.Caption"); this.tgridViewData.CaptionHeight = ((int)(resources.GetObject("tgridViewData.CaptionHeight"))); this.tgridViewData.CellTipsDelay = ((int)(resources.GetObject("tgridViewData.CellTipsDelay"))); this.tgridViewData.CellTipsWidth = ((int)(resources.GetObject("tgridViewData.CellTipsWidth"))); this.tgridViewData.ChildGrid = ((C1.Win.C1TrueDBGrid.C1TrueDBGrid)(resources.GetObject("tgridViewData.ChildGrid"))); this.tgridViewData.CollapseColor = ((System.Drawing.Color)(resources.GetObject("tgridViewData.CollapseColor"))); this.tgridViewData.ColumnFooters = ((bool)(resources.GetObject("tgridViewData.ColumnFooters"))); this.tgridViewData.ColumnHeaders = ((bool)(resources.GetObject("tgridViewData.ColumnHeaders"))); this.tgridViewData.DefColWidth = ((int)(resources.GetObject("tgridViewData.DefColWidth"))); this.tgridViewData.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("tgridViewData.Dock"))); this.tgridViewData.EditDropDown = ((bool)(resources.GetObject("tgridViewData.EditDropDown"))); this.tgridViewData.EmptyRows = ((bool)(resources.GetObject("tgridViewData.EmptyRows"))); this.tgridViewData.Enabled = ((bool)(resources.GetObject("tgridViewData.Enabled"))); this.tgridViewData.ExpandColor = ((System.Drawing.Color)(resources.GetObject("tgridViewData.ExpandColor"))); this.tgridViewData.ExposeCellMode = ((C1.Win.C1TrueDBGrid.ExposeCellModeEnum)(resources.GetObject("tgridViewData.ExposeCellMode"))); this.tgridViewData.ExtendRightColumn = ((bool)(resources.GetObject("tgridViewData.ExtendRightColumn"))); this.tgridViewData.FetchRowStyles = ((bool)(resources.GetObject("tgridViewData.FetchRowStyles"))); this.tgridViewData.FilterBar = ((bool)(resources.GetObject("tgridViewData.FilterBar"))); this.tgridViewData.FlatStyle = ((C1.Win.C1TrueDBGrid.FlatModeEnum)(resources.GetObject("tgridViewData.FlatStyle"))); this.tgridViewData.Font = ((System.Drawing.Font)(resources.GetObject("tgridViewData.Font"))); this.tgridViewData.GroupByAreaVisible = ((bool)(resources.GetObject("tgridViewData.GroupByAreaVisible"))); this.tgridViewData.GroupByCaption = resources.GetString("tgridViewData.GroupByCaption"); this.tgridViewData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource")))); this.tgridViewData.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("tgridViewData.ImeMode"))); this.tgridViewData.LinesPerRow = ((int)(resources.GetObject("tgridViewData.LinesPerRow"))); this.tgridViewData.Location = ((System.Drawing.Point)(resources.GetObject("tgridViewData.Location"))); this.tgridViewData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder; this.tgridViewData.MultiSelect = C1.Win.C1TrueDBGrid.MultiSelectEnum.None; this.tgridViewData.Name = "tgridViewData"; this.tgridViewData.PictureAddnewRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureAddnewRow"))); this.tgridViewData.PictureCurrentRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureCurrentRow"))); this.tgridViewData.PictureFilterBar = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureFilterBar"))); this.tgridViewData.PictureFooterRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureFooterRow"))); this.tgridViewData.PictureHeaderRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureHeaderRow"))); this.tgridViewData.PictureModifiedRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureModifiedRow"))); this.tgridViewData.PictureStandardRow = ((System.Drawing.Image)(resources.GetObject("tgridViewData.PictureStandardRow"))); this.tgridViewData.PreviewInfo.AllowSizing = ((bool)(resources.GetObject("tgridViewData.PreviewInfo.AllowSizing"))); this.tgridViewData.PreviewInfo.Caption = resources.GetString("tgridViewData.PreviewInfo.Caption"); this.tgridViewData.PreviewInfo.Location = ((System.Drawing.Point)(resources.GetObject("tgridViewData.PreviewInfo.Location"))); this.tgridViewData.PreviewInfo.Size = ((System.Drawing.Size)(resources.GetObject("tgridViewData.PreviewInfo.Size"))); this.tgridViewData.PreviewInfo.ToolBars = ((bool)(resources.GetObject("tgridViewData.PreviewInfo.ToolBars"))); this.tgridViewData.PreviewInfo.UIStrings.Content = ((string[])(resources.GetObject("tgridViewData.PreviewInfo.UIStrings.Content"))); this.tgridViewData.PreviewInfo.ZoomFactor = ((System.Double)(resources.GetObject("tgridViewData.PreviewInfo.ZoomFactor"))); this.tgridViewData.PrintInfo.MaxRowHeight = ((int)(resources.GetObject("tgridViewData.PrintInfo.MaxRowHeight"))); this.tgridViewData.PrintInfo.OwnerDrawPageFooter = ((bool)(resources.GetObject("tgridViewData.PrintInfo.OwnerDrawPageFooter"))); this.tgridViewData.PrintInfo.OwnerDrawPageHeader = ((bool)(resources.GetObject("tgridViewData.PrintInfo.OwnerDrawPageHeader"))); this.tgridViewData.PrintInfo.PageFooter = resources.GetString("tgridViewData.PrintInfo.PageFooter"); this.tgridViewData.PrintInfo.PageFooterHeight = ((int)(resources.GetObject("tgridViewData.PrintInfo.PageFooterHeight"))); this.tgridViewData.PrintInfo.PageHeader = resources.GetString("tgridViewData.PrintInfo.PageHeader"); this.tgridViewData.PrintInfo.PageHeaderHeight = ((int)(resources.GetObject("tgridViewData.PrintInfo.PageHeaderHeight"))); this.tgridViewData.PrintInfo.PrintHorizontalSplits = ((bool)(resources.GetObject("tgridViewData.PrintInfo.PrintHorizontalSplits"))); this.tgridViewData.PrintInfo.ProgressCaption = resources.GetString("tgridViewData.PrintInfo.ProgressCaption"); this.tgridViewData.PrintInfo.RepeatColumnFooters = ((bool)(resources.GetObject("tgridViewData.PrintInfo.RepeatColumnFooters"))); this.tgridViewData.PrintInfo.RepeatColumnHeaders = ((bool)(resources.GetObject("tgridViewData.PrintInfo.RepeatColumnHeaders"))); this.tgridViewData.PrintInfo.RepeatGridHeader = ((bool)(resources.GetObject("tgridViewData.PrintInfo.RepeatGridHeader"))); this.tgridViewData.PrintInfo.RepeatSplitHeaders = ((bool)(resources.GetObject("tgridViewData.PrintInfo.RepeatSplitHeaders"))); this.tgridViewData.PrintInfo.ShowOptionsDialog = ((bool)(resources.GetObject("tgridViewData.PrintInfo.ShowOptionsDialog"))); this.tgridViewData.PrintInfo.ShowProgressForm = ((bool)(resources.GetObject("tgridViewData.PrintInfo.ShowProgressForm"))); this.tgridViewData.PrintInfo.ShowSelection = ((bool)(resources.GetObject("tgridViewData.PrintInfo.ShowSelection"))); this.tgridViewData.PrintInfo.UseGridColors = ((bool)(resources.GetObject("tgridViewData.PrintInfo.UseGridColors"))); this.tgridViewData.RecordSelectors = ((bool)(resources.GetObject("tgridViewData.RecordSelectors"))); this.tgridViewData.RecordSelectorWidth = ((int)(resources.GetObject("tgridViewData.RecordSelectorWidth"))); this.tgridViewData.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("tgridViewData.RightToLeft"))); this.tgridViewData.RowDivider.Color = ((System.Drawing.Color)(resources.GetObject("resource.Color"))); this.tgridViewData.RowDivider.Style = ((C1.Win.C1TrueDBGrid.LineStyleEnum)(resources.GetObject("resource.Style"))); this.tgridViewData.RowHeight = ((int)(resources.GetObject("tgridViewData.RowHeight"))); this.tgridViewData.RowSubDividerColor = ((System.Drawing.Color)(resources.GetObject("tgridViewData.RowSubDividerColor"))); this.tgridViewData.ScrollTips = ((bool)(resources.GetObject("tgridViewData.ScrollTips"))); this.tgridViewData.ScrollTrack = ((bool)(resources.GetObject("tgridViewData.ScrollTrack"))); this.tgridViewData.Size = ((System.Drawing.Size)(resources.GetObject("tgridViewData.Size"))); this.tgridViewData.SpringMode = ((bool)(resources.GetObject("tgridViewData.SpringMode"))); this.tgridViewData.TabAcrossSplits = ((bool)(resources.GetObject("tgridViewData.TabAcrossSplits"))); this.tgridViewData.TabIndex = ((int)(resources.GetObject("tgridViewData.TabIndex"))); this.tgridViewData.Text = resources.GetString("tgridViewData.Text"); this.tgridViewData.ViewCaptionWidth = ((int)(resources.GetObject("tgridViewData.ViewCaptionWidth"))); this.tgridViewData.ViewColumnWidth = ((int)(resources.GetObject("tgridViewData.ViewColumnWidth"))); this.tgridViewData.Visible = ((bool)(resources.GetObject("tgridViewData.Visible"))); this.tgridViewData.WrapCellPointer = ((bool)(resources.GetObject("tgridViewData.WrapCellPointer"))); this.tgridViewData.AfterDelete += new System.EventHandler(this.tgridViewData_AfterDelete); this.tgridViewData.AfterUpdate += new System.EventHandler(this.tgridViewData_AfterUpdate); this.tgridViewData.RowColChange += new C1.Win.C1TrueDBGrid.RowColChangeEventHandler(this.tgridViewData_RowColChange); this.tgridViewData.BeforeColEdit += new C1.Win.C1TrueDBGrid.BeforeColEditEventHandler(this.tgridViewData_BeforeColEdit); this.tgridViewData.Click += new System.EventHandler(this.tgridViewData_Click); this.tgridViewData.AfterColEdit += new C1.Win.C1TrueDBGrid.ColEventHandler(this.tgridViewData_AfterColEdit); this.tgridViewData.BeforeUpdate += new C1.Win.C1TrueDBGrid.CancelEventHandler(this.tgridViewData_BeforeUpdate); this.tgridViewData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.tgridViewData_AfterColUpdate); this.tgridViewData.BeforeInsert += new C1.Win.C1TrueDBGrid.CancelEventHandler(this.tgridViewData_BeforeInsert); this.tgridViewData.BeforeColUpdate += new C1.Win.C1TrueDBGrid.BeforeColUpdateEventHandler(this.tgridViewData_BeforeColUpdate); this.tgridViewData.BeforeDelete += new C1.Win.C1TrueDBGrid.CancelEventHandler(this.tgridViewData_BeforeDelete); this.tgridViewData.BeforeRowColChange += new C1.Win.C1TrueDBGrid.CancelEventHandler(this.tgridViewData_BeforeRowColChange); this.tgridViewData.Leave += new System.EventHandler(this.tgridViewData_Leave); this.tgridViewData.AfterInsert += new System.EventHandler(this.tgridViewData_AfterInsert); this.tgridViewData.KeyUp += new System.Windows.Forms.KeyEventHandler(this.tgridViewData_KeyUp); this.tgridViewData.PropBag = resources.GetString("tgridViewData.PropBag"); // // btnSaveToDB // this.btnSaveToDB.AccessibleDescription = resources.GetString("btnSaveToDB.AccessibleDescription"); this.btnSaveToDB.AccessibleName = resources.GetString("btnSaveToDB.AccessibleName"); this.btnSaveToDB.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnSaveToDB.Anchor"))); this.btnSaveToDB.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnSaveToDB.BackgroundImage"))); this.btnSaveToDB.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnSaveToDB.Dock"))); this.btnSaveToDB.Enabled = ((bool)(resources.GetObject("btnSaveToDB.Enabled"))); this.btnSaveToDB.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnSaveToDB.FlatStyle"))); this.btnSaveToDB.Font = ((System.Drawing.Font)(resources.GetObject("btnSaveToDB.Font"))); this.btnSaveToDB.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveToDB.Image"))); this.btnSaveToDB.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSaveToDB.ImageAlign"))); this.btnSaveToDB.ImageIndex = ((int)(resources.GetObject("btnSaveToDB.ImageIndex"))); this.btnSaveToDB.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnSaveToDB.ImeMode"))); this.btnSaveToDB.Location = ((System.Drawing.Point)(resources.GetObject("btnSaveToDB.Location"))); this.btnSaveToDB.Name = "btnSaveToDB"; this.btnSaveToDB.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnSaveToDB.RightToLeft"))); this.btnSaveToDB.Size = ((System.Drawing.Size)(resources.GetObject("btnSaveToDB.Size"))); this.btnSaveToDB.TabIndex = ((int)(resources.GetObject("btnSaveToDB.TabIndex"))); this.btnSaveToDB.Text = resources.GetString("btnSaveToDB.Text"); this.btnSaveToDB.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnSaveToDB.TextAlign"))); this.btnSaveToDB.Visible = ((bool)(resources.GetObject("btnSaveToDB.Visible"))); this.btnSaveToDB.Click += new System.EventHandler(this.btnSaveToDB_Click); // // ManageRole // this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.CancelButton = this.btnClose; this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.Add(this.tgridViewData); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnSaveToDB); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "ManageRole"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Closing += new System.ComponentModel.CancelEventHandler(this.ManageRole_Closing); this.Load += new System.EventHandler(this.ManageRole_Load); ((System.ComponentModel.ISupportInitialize)(this.tgridViewData)).EndInit(); this.ResumeLayout(false); } #endregion #region Class's Method /// <summary> /// Enable or Disable button based on the user action /// </summary> /// <param name="blnStatus"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void ChangeEditFlag(bool blnStatus) { blnEditUpdateData = blnStatus; btnSaveToDB.Enabled = blnStatus; //btnCancel.Enabled = blnStatus; } /// <summary> /// Load data for this form /// </summary> /// <Author> Thien HD, Jan 07, 2005</Author> private void LoadForm() { const int ROLE_NAME_WIDTH = 200; const int ROLE_DESCRIPTION_WIDTH = 400; try { //Init the BO object ManageRoleBO objManageRoleBO = new ManageRoleBO(); //Get the list of roles for this data and store into dstData variable dstData = objManageRoleBO.List(); dstData.Tables[0].DefaultView.Sort = Sys_RoleTable.NAME_FLD; //get the field length for this table DataRow drFieldLength = objManageRoleBO.GetFieldLength(); //Grant this data into the grid tgridViewData.DataSource = dstData.Tables[0]; //tgridViewData.DataMember = dstData.Tables[0].TableName; //Set the role name to be unique //dstData.Tables[0].Columns[Sys_RoleTable.NAME_FLD].Unique = true; dstData.Tables[0].Columns[Sys_RoleTable.NAME_FLD].AllowDBNull = false; //set the ROLE ID to Identity column //dstData.Tables[0].Columns[Sys_RoleTable.ROLEID_FLD].AutoIncrement = true; //Get the highest value for this column /* DataView dvDataView = dstData.Tables[0].DefaultView; dvDataView.Sort = Sys_RoleTable.ROLEID_FLD + " DESC"; if (dstData.Tables[0].Rows.Count == 0) { dstData.Tables[0].Columns[Sys_RoleTable.ROLEID_FLD].AutoIncrementSeed = 1; } else { dstData.Tables[0].Columns[Sys_RoleTable.ROLEID_FLD].AutoIncrementSeed = int.Parse(dvDataView[0][Sys_RoleTable.ROLEID_FLD].ToString()) + 1; } dstData.Tables[0].Columns[Sys_RoleTable.ROLEID_FLD].AutoIncrementStep = 1; dvDataView = null; */ //Center Heading for (int i = 0; i < tgridViewData.Splits[0].DisplayColumns.Count; i++) { tgridViewData.Splits[0].DisplayColumns[i].HeadingStyle.HorizontalAlignment = AlignHorzEnum.Center; } //Align the ID column tgridViewData.Splits[0].DisplayColumns[Sys_RoleTable.ROLEID_FLD].Style.HorizontalAlignment = AlignHorzEnum.Near; //Inivisble the ID column tgridViewData.Splits[0].DisplayColumns[Sys_RoleTable.ROLEID_FLD].Visible = false; //Set the column length for each column in grid tgridViewData.Columns[Sys_RoleTable.NAME_FLD].DataWidth = int.Parse(drFieldLength[Sys_RoleTable.NAME_FLD].ToString()); tgridViewData.Columns[Sys_RoleTable.DESCRIPTION_FLD].DataWidth = int.Parse(drFieldLength[Sys_RoleTable.DESCRIPTION_FLD].ToString()); //set the column width tgridViewData.Splits[0].DisplayColumns[Sys_RoleTable.NAME_FLD].Width = ROLE_NAME_WIDTH; tgridViewData.Splits[0].DisplayColumns[Sys_RoleTable.DESCRIPTION_FLD].Width = ROLE_DESCRIPTION_WIDTH; /// HACKED: Thachnn: fix bug 1652 //set the Mandatory Column tgridViewData.Splits[0].DisplayColumns[Sys_RoleTable.NAME_FLD].HeadingStyle.ForeColor = System.Drawing.Color.Maroon;// = oHeadingStyle; /// ENDHACKED: Thachnn : fix bug 1652 } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Save data into database /// </summary> /// <returns></returns> /// <Author> Thien HD, Jan 07, 2005</Author> private bool SaveToDatabase() { const int COL_NAME = 1; const string METHOD_NAME = THIS + ".btnSaveToDB_Click()"; if (blnErrorOccurs) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); tgridViewData.Col = COL_NAME; tgridViewData.Focus(); return false; } if (!blnEditUpdateData) { return true; } if (dstData.Tables[0].Rows.Count == 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MANAGEROLE_NOROW_TOSAVE,MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } try { ManageRoleBO objManageRoleBO = new ManageRoleBO(); //Call the UpdateDataSet method if (strDeletedRole.EndsWith(CHR_SEPARATOR.ToString())) { strDeletedRole = strDeletedRole.Substring(0,strDeletedRole.Length - 1); } objManageRoleBO.UpdateDataSetAndDelete(dstData,strDeletedRole); strDeletedRole = string.Empty; //After saving into database , refresh the data for the grid tgridViewData.Refresh(); ChangeEditFlag(false); PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA, MessageBoxIcon.Information); return true; } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } //focus if (ex.mCode == ErrorCode.DUPLICATE_KEY) { //search for duplicate row int i,j; for (i = 0; i < tgridViewData.RowCount; i++) { for (j = i + 1; j < tgridViewData.RowCount; j++) { if (tgridViewData[i,COL_NAME].ToString().Equals(tgridViewData[j,COL_NAME].ToString())) { tgridViewData.Row = j; tgridViewData.Col = COL_NAME; tgridViewData.Focus(); return false; } } } } return false; } catch (System.Runtime.InteropServices.COMException ex) { tgridViewData.Refresh(); ChangeEditFlag(false); PCSMessageBox.Show(ErrorCode.MESSAGE_COM_TRANSACTION, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } return false; } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } return false; } finally { } } //************************************************************************** /// <summary> /// Validate data before saving /// </summary> /// <returns></returns> /// <Author> Thien HD, Jan 07, 2005</Author> private bool ValidateData() { return true; } //************************************************************************** /// <summary> /// Check mandatory fields /// </summary> /// <param name="pobjControl"></param> /// <returns></returns> /// <Author> Thien HD, Jan 07, 2005</Author> private bool CheckMandatory(Control pobjControl) { if (pobjControl.Text.Trim() == string.Empty) { return false; } return true; } #endregion Class's Method #region Event Processing private void ManageRole_Load(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".ManageRole_Load()"; //Call the LoadForm method to load data for the first time try { #region Security //Set authorization for user Security objSecurity = new Security(); this.Name = THIS; if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0) { this.Close(); // You don't have the right to view this item PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW ,MessageBoxIcon.Warning); return; } #endregion LoadForm(); ChangeEditFlag(false); // set the edit, update to false } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void btnAdd_Click(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".bntAdd_Click()"; try { //' This "Add New" button moves the cursor to the //' "new (blank) row" at the end so that user can start //' adding data to the new record. //' Move to last record so that "new row" will be visible //' Move the cursor to the "addnew row", and set focus to the grid CurrencyManager cm; //cm = (CurrencyManager) tgridViewTable.BindingContext[tgridViewTable.DataSource, tgridViewTable.DataMember]; cm = (CurrencyManager) tgridViewData.BindingContext[tgridViewData.DataSource,tgridViewData.DataMember]; cm.EndCurrentEdit(); tgridViewData.Refresh(); tgridViewData.MoveLast(); tgridViewData.Row = tgridViewData.Row + 1; cm.AddNew(); tgridViewData.Select(); //Change the flag to Edit ChangeEditFlag(true); } catch (NoNullAllowedException ex) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (ConstraintException ex) { PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } tgridViewData.Select(); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void btnClose_Click(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically this.Close(); // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void ManageRole_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (blnEditUpdateData) { System.Windows.Forms.DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (dlgResult) { case DialogResult.Yes: if (!SaveToDatabase()) { e.Cancel = true; } break; case DialogResult.No: e.Cancel = false; break; case DialogResult.Cancel: e.Cancel = true; break; } /* if (PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (!SaveToDatabase()) { e.Cancel = true; } } */ } } private void btnHelp_Click(object sender, System.EventArgs e) {// Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } /// <summary> /// Update the current row information into text boxes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void tgridViewData_RowColChange(object sender, C1.Win.C1TrueDBGrid.RowColChangeEventArgs e) { const string METHOD_NAME = THIS + ".tgridViewData_RowColChange()"; try { if (tgridViewData[tgridViewData.Row, Sys_RoleTable.NAME_FLD].ToString().ToLower() == Constants.ADMINISTRATORS.ToLower()) { btnDelete.Enabled = false; } else btnDelete.Enabled = true; } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } /// <summary> /// Delete the current row from True DbGrid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void btnDelete_Click(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const int COL_ID = 0; if (tgridViewData.RowCount == 0 || tgridViewData.AddNewMode == AddNewModeEnum.AddNewCurrent) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically return; } const string METHOD_NAME = THIS + ".btnDelete_Click()"; DialogResult result; result = PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { try { int nDeletedID; try { nDeletedID = Convert.ToInt32(tgridViewData[tgridViewData.Row,COL_ID]); strDeletedRole = strDeletedRole + nDeletedID + CHR_SEPARATOR; } catch { } tgridViewData.Delete(); tgridViewData.UpdateData(); tgridViewData.Refresh(); ChangeEditFlag(true); } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } /// <summary> /// Display a message to confirm delete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void tgridViewData_BeforeDelete(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e) { if (tgridViewData[tgridViewData.Row, Sys_RoleTable.NAME_FLD].ToString().ToLower() == Constants.ADMINISTRATORS.ToLower()) { e.Cancel = true; } else { if (PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { e.Cancel = false; } else { e.Cancel = true; } } } private void tgridViewData_AfterDelete(object sender, System.EventArgs e) { ChangeEditFlag(true); } private void tgridViewData_AfterInsert(object sender, System.EventArgs e) { ChangeEditFlag(true); } private void tgridViewData_AfterUpdate(object sender, System.EventArgs e) { ChangeEditFlag(true); } /// <summary> /// Save data into the current row in grid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void btnSave_Click(object sender, System.EventArgs e) {// Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void tgridViewData_Click(object sender, System.EventArgs e) {// Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } /// <summary> /// Cancel all changes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <Author> Thien HD, Jan 07, 2005</Author> private void btnCancel_Click(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".btnCancel_Click()"; try { if (blnEditUpdateData) { if (PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { dstData.RejectChanges(); tgridViewData.RefreshRow(); ChangeEditFlag(false); } } } catch (Exception ex) { PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } /// <summary> /// Save data into database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <author> Thien HD, Jan 07, 2005</author> private void btnSaveToDB_Click(object sender, System.EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically if (SaveToDatabase()) { /// HACKED: Thachnn: fix bug 1638 tgridViewData.MoveLast(); tgridViewData.Row = tgridViewData.Row + 1; tgridViewData.Focus(); /// ENDHACKED: Thachnn: } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void tgridViewData_AfterColUpdate(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e) { e.Column.DataColumn.Value = e.Column.DataColumn.Value.ToString().Trim(); } private void tgridViewData_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e) { if (e.Column.DataColumn.DataField==Sys_RoleTable.NAME_FLD && e.Column.DataColumn.Value.ToString().Trim() == String.Empty) { e.Cancel = true; blnErrorOccurs = true; //PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); } else { e.Cancel = false; } } private void tgridViewData_AfterColEdit(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e) { e.Column.DataColumn.Value = e.Column.DataColumn.Value.ToString().Trim(); } private void tgridViewData_BeforeInsert(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e) { const string METHOD_NAME = THIS + ".tgridViewData_BeforeInsert()"; try { CurrencyManager cm; //cm = (CurrencyManager) tgridViewTable.BindingContext[tgridViewTable.DataSource, tgridViewTable.DataMember]; cm = (CurrencyManager) tgridViewData.BindingContext[tgridViewData.DataSource,tgridViewData.DataMember]; //End current edit to en-force constraint on the table cm.EndCurrentEdit(); e.Cancel = false; } catch (NoNullAllowedException ex) { e.Cancel = true; PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (ConstraintException ex) { e.Cancel = true; PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { e.Cancel = true; PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void tgridViewData_BeforeUpdate(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e) { const string METHOD_NAME = THIS + ".tgridViewData_BeforeUpdate()"; try { CurrencyManager cm; //cm = (CurrencyManager) tgridViewTable.BindingContext[tgridViewTable.DataSource, tgridViewTable.DataMember]; cm = (CurrencyManager) tgridViewData.BindingContext[tgridViewData.DataSource,tgridViewData.DataMember]; // HACK: DuongNA 2005-10-13 //Check ourselves before we can believe in Exception :(( DataRowView obj = (DataRowView)cm.Current; if (obj.Row[Sys_RoleTable.NAME_FLD].ToString().Equals(string.Empty)) { e.Cancel = true; blnErrorOccurs = true; tgridViewData.Focus(); return; } // End DuongNA 2005-10-13 //End current edit to en-force constraint on the table cm.EndCurrentEdit(); e.Cancel = false; blnErrorOccurs = false; } catch (NoNullAllowedException ex) { e.Cancel = true; blnErrorOccurs = true; tgridViewData.Focus(); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (ConstraintException ex) { e.Cancel = true; blnErrorOccurs = true; tgridViewData.Focus(); PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { e.Cancel = true; blnErrorOccurs = true; tgridViewData.Focus(); PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } private void tgridViewData_BeforeRowColChange(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e) { const string METHOD_NAME = THIS + ".tgridViewData_BeforeRowColChange"; try { if (tgridViewData.Columns[Sys_RoleTable.NAME_FLD].Value.ToString().Trim() == String.Empty) { //e.Cancel = true; } else { /// HACKED: Thachnn: fix bug if(blnEditUpdateData) { ChangeEditFlag(true); } /// ENDHACKED: Thachnn e.Cancel = false; } }catch (Exception ex) { // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } #region HACKED: Thachnn: fix bug: 1660 private void tgridViewData_Leave(object sender, System.EventArgs e) { if(blnEditUpdateData) { btnSaveToDB.Enabled = true; } } private void tgridViewData_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode != Keys.Up && e.KeyCode != Keys.Down && e.KeyCode != Keys.Left && e.KeyCode != Keys.Right && e.KeyCode != Keys.Enter && e.KeyCode != Keys.Escape && e.KeyCode != Keys.Tab ) { ChangeEditFlag(true); } } #endregion private void tgridViewData_BeforeColEdit(object sender, C1.Win.C1TrueDBGrid.BeforeColEditEventArgs e) { if (tgridViewData[tgridViewData.Row, Sys_RoleTable.NAME_FLD].ToString().ToLower() == Constants.ADMINISTRATORS.ToLower()) { e.Cancel = true; } } #endregion Event Processing } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Threading.Tasks; using System.Linq; using log4net.Config; using log4net.Layout; using log4net.Repository; using log4net.Tests.Appender; using log4net.Util; using NUnit.Framework; namespace log4net.Tests.Context { #if FRAMEWORK_4_5_OR_ABOVE /// <summary> /// Used for internal unit testing the <see cref="LogicalThreadContext"/> class. /// </summary> /// <remarks> /// Used for internal unit testing the <see cref="LogicalThreadContext"/> class. /// </remarks> [TestFixture] public class LogicalThreadContextTest { [TearDown] public void TearDown() { Utils.RemovePropertyFromAllContexts(); } [Test] public void TestLogicalThreadPropertiesPatternBasicGetSet() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestLogicalThreadPropertiesPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread properties value set"); stringAppender.Reset(); LogicalThreadContext.Properties[Utils.PROPERTY_KEY] = "val1"; log1.Info("TestMessage"); Assert.AreEqual("val1", stringAppender.GetString(), "Test logical thread properties value set"); stringAppender.Reset(); LogicalThreadContext.Properties.Remove(Utils.PROPERTY_KEY); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread properties value removed"); stringAppender.Reset(); } [Test] public async Task TestLogicalThreadPropertiesPatternAsyncAwait() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestLogicalThreadPropertiesPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); string testValueForCurrentContext = "Outer"; LogicalThreadContext.Properties[Utils.PROPERTY_KEY] = testValueForCurrentContext; log1.Info("TestMessage"); Assert.AreEqual(testValueForCurrentContext, stringAppender.GetString(), "Test logical thread properties value set"); stringAppender.Reset(); var strings = await Task.WhenAll(Enumerable.Range(0, 10).Select(x => SomeWorkProperties(x.ToString()))); // strings should be ["00AA0BB0", "01AA1BB1", "02AA2BB2", ...] for (int i = 0; i < strings.Length; i++) { Assert.AreEqual(string.Format("{0}{1}AA{1}BB{1}", testValueForCurrentContext, i), strings[i], "Test logical thread properties expected sequence"); } log1.Info("TestMessage"); Assert.AreEqual(testValueForCurrentContext, stringAppender.GetString(), "Test logical thread properties value set"); stringAppender.Reset(); LogicalThreadContext.Properties.Remove(Utils.PROPERTY_KEY); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread properties value removed"); stringAppender.Reset(); } [Test] public void TestLogicalThreadStackPattern() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1")) { log1.Info("TestMessage"); Assert.AreEqual("val1", stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); } log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread stack value removed"); stringAppender.Reset(); } [Test] public void TestLogicalThreadStackPattern2() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1")) { log1.Info("TestMessage"); Assert.AreEqual("val1", stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val2")) { log1.Info("TestMessage"); Assert.AreEqual("val1 val2", stringAppender.GetString(), "Test logical thread stack value pushed 2nd val"); stringAppender.Reset(); } } log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread stack value removed"); stringAppender.Reset(); } [Test] public void TestLogicalThreadStackPatternNullVal() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push(null)) { log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); } log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread stack value removed"); stringAppender.Reset(); } [Test] public void TestLogicalThreadStackPatternNullVal2() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestThreadStackPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push("val1")) { log1.Info("TestMessage"); Assert.AreEqual("val1", stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push(null)) { log1.Info("TestMessage"); Assert.AreEqual("val1 ", stringAppender.GetString(), "Test logical thread stack value pushed null"); stringAppender.Reset(); } } log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread stack value removed"); stringAppender.Reset(); } [Test] public async Task TestLogicalThreadStackPatternAsyncAwait() { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestLogicalThreadStackPattern"); log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test no logical thread stack value set"); stringAppender.Reset(); string testValueForCurrentContext = "Outer"; string[] strings = null; using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push(testValueForCurrentContext)) { log1.Info("TestMessage"); Assert.AreEqual(testValueForCurrentContext, stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); strings = await Task.WhenAll(Enumerable.Range(0, 10).Select(x => SomeWorkStack(x.ToString()))); } // strings should be ["Outer 0 AOuter 0 AOuter 0Outer 0 BOuter 0 B Outer 0", ...] for (int i = 0; i < strings.Length; i++) { Assert.AreEqual(string.Format("{0} {1} A{0} {1} A{0} {1}{0} {1} B{0} {1} B{0} {1}", testValueForCurrentContext, i), strings[i], "Test logical thread properties expected sequence"); } log1.Info("TestMessage"); Assert.AreEqual(SystemInfo.NullText, stringAppender.GetString(), "Test logical thread properties value removed"); stringAppender.Reset(); } static async Task<string> SomeWorkProperties(string propertyName) { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log = LogManager.GetLogger(rep.Name, "TestLogicalThreadStackPattern"); log.Info("TestMessage"); // set a new one LogicalThreadContext.Properties[Utils.PROPERTY_KEY] = propertyName; log.Info("TestMessage"); await MoreWorkProperties(log, "A"); log.Info("TestMessage"); await MoreWorkProperties(log, "B"); log.Info("TestMessage"); return stringAppender.GetString(); } static async Task MoreWorkProperties(ILog log, string propertyName) { LogicalThreadContext.Properties[Utils.PROPERTY_KEY] = propertyName; log.Info("TestMessage"); await Task.Delay(1); log.Info("TestMessage"); } static async Task<string> SomeWorkStack(string stackName) { StringAppender stringAppender = new StringAppender(); stringAppender.Layout = new PatternLayout("%property{" + Utils.PROPERTY_KEY + "}"); ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log = LogManager.GetLogger(rep.Name, "TestLogicalThreadStackPattern"); using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push(stackName)) { log.Info("TestMessage"); Assert.AreEqual(string.Format("Outer {0}", stackName), stringAppender.GetString(), "Test logical thread stack value set"); stringAppender.Reset(); await MoreWorkStack(log, "A"); log.Info("TestMessage"); await MoreWorkStack(log, "B"); log.Info("TestMessage"); } return stringAppender.GetString(); } static async Task MoreWorkStack(ILog log, string stackName) { using (LogicalThreadContext.Stacks[Utils.PROPERTY_KEY].Push(stackName)) { log.Info("TestMessage"); await Task.Delay(1); log.Info("TestMessage"); } } } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using static System.Diagnostics.Debug; namespace XSharp.MacroCompiler.Syntax { using static TokenAttr; abstract internal partial class Node { internal Symbol Symbol = null; internal virtual Node Bind(Binder b) { throw new InternalError(); } internal CompilationError Error(ErrorCode e, params object[] args) => Compilation.Error(Token, e, args); } abstract internal partial class Expr : Node { internal TypeSymbol Datatype = null; internal BindAffinity Affinity = BindAffinity.Access; internal virtual Expr Cloned(Binder b) { return this; } internal TypeSymbol ThrowError(ErrorCode e, params object[] args) { throw Error(e, args); } internal TypeSymbol ThrowError(CompilationError e) { throw e; } internal virtual void RequireValue() { if (Symbol is SymbolList && Symbol.UniqueIdent() is Symbol s) { Symbol = s; Datatype = s.Type(); } if (Datatype == null) ThrowError(ErrorCode.NotAnExpression, Symbol); if (Symbol is SymbolList) ThrowError(ErrorCode.NotAnExpression, Symbol); } internal virtual void RequireType() { if (Symbol is SymbolList) Symbol = Symbol.UniqueType(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Type", this.ToString()); if (!(Symbol is TypeSymbol)) ThrowError(ErrorCode.NotAType, Symbol); } internal virtual void RequireGetAccess() { RequireValue(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Expression", this.ToString()); if (!Symbol.HasGetAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Get); } internal virtual void RequireSetAccess() { RequireValue(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Expression", this.ToString()); if (!Symbol.HasSetAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Set); } internal virtual void RequireInitAccess() { RequireValue(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Expression", this.ToString()); if (!Symbol.HasInitAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Init); } internal virtual void RequireGetSetAccess() { RequireValue(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Expression", this.ToString()); if (!Symbol.HasGetAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Get); if (!Symbol.HasSetAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Set); } internal virtual void RequireRefAccess() { RequireValue(); if (Symbol == null) ThrowError(ErrorCode.NotFound, "Expression", this.ToString()); if (!Symbol.HasRefAccess) throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Ref); } } abstract internal partial class TypeExpr : Expr { internal override void RequireValue() { if (Symbol is MethodBaseSymbol) ThrowError(ErrorCode.NotAnExpression, Symbol); base.RequireValue(); } } abstract internal partial class NameExpr : TypeExpr { } internal partial class CachedExpr : Expr { internal LocalSymbol Local; internal Expr Expr; CachedExpr(Binder b, Expr e) : base(e.Token) { CompilerGenerated = true; Expr = e; Local = b.AddLocal(Expr.Datatype); Symbol = Expr.Symbol; Datatype = Expr.Datatype; } internal static CachedExpr Bound(Binder b, Expr expr) { return new CachedExpr(b, expr); } internal override void RequireValue() => Expr.RequireValue(); internal override void RequireType() => Expr.RequireType(); internal override void RequireGetAccess() => Expr.RequireGetAccess(); internal override void RequireSetAccess() => Expr.RequireSetAccess(); internal override void RequireGetSetAccess() => Expr.RequireGetSetAccess(); internal override void RequireRefAccess() => Expr.RequireRefAccess(); } internal partial class NativeTypeExpr : TypeExpr { internal override Node Bind(Binder b) { if (Affinity != BindAffinity.Type) { Expr e = new IdExpr(Token); b.Bind(ref e, Affinity); return e; } Symbol = Binder.GetNativeTypeFromToken(Kind) ?? ThrowError(ErrorCode.NotSupported,Kind); return null; } } internal partial class IdExpr : NameExpr { static internal IdExpr Bound(Symbol sym) { var e = new IdExpr(Token.None); e.Symbol = sym; e.Datatype = sym.Type(); return e; } internal override Node Bind(Binder b) { Symbol = b.Lookup(Name); if (Affinity != BindAffinity.Invoke && Affinity != BindAffinity.Type) { if (Symbol.IsMethodOrMethodGroup()) { // IdExpr can't be a method // TODO (nvk): If delegates are supprted this needs to be revised! Symbol = null; } else if (Symbol is TypeSymbol) { Symbol = null; } else if (Symbol is NamespaceSymbol) { Symbol = null; } else if (Symbol is SymbolList) { Symbol = Symbol.UniqueIdent(); } } if (Symbol == null && Affinity != BindAffinity.Type) { if (Affinity == BindAffinity.Alias) { return LiteralExpr.Bound(Constant.Create(Name)); } else { switch (b.Options.UndeclaredVariableResolution) { case VariableResolution.Error: throw Error(ErrorCode.IdentifierNotFound, Name); case VariableResolution.GenerateLocal: Symbol = b.AddVariable(Name, Compilation.Get(NativeType.Usual)); break; case VariableResolution.TreatAsField: return AliasExpr.Bound(Name); case VariableResolution.TreatAsFieldOrMemvar: if (Affinity == BindAffinity.Assign) b.CreatesAutoVars = true; return AutoVarExpr.Bound(Name); } } } Datatype = Symbol.Type(); return null; } } internal partial class MemberAccessExpr : Expr { internal override Node Bind(Binder b) { if (!b.Options.AllowDotAccess && Token.Type == TokenType.DOT) ThrowError(ErrorCode.DotMemberAccess); b.Bind(ref Expr); Expr.RequireValue(); if (Expr.Datatype.IsArray && Expr.Datatype.ArrayRank == 1 && Binder.LookupComparer.Equals((Member as IdExpr)?.Name, SystemNames.Length)) return ArrayLengthExpr.Bound(Expr); Symbol = b.BindMemberAccess(ref Expr, ref Member, Affinity); Datatype = Symbol.Type(); return null; } internal override Expr Cloned(Binder b) { b.Cache(ref Expr); return this; } internal static MemberAccessExpr Bound(Binder b, Expr expr, Expr member, BindAffinity affinity) { expr.RequireValue(); var e = new MemberAccessExpr(expr, Token.None, member); e.Symbol = b.BindMemberAccess(ref e.Expr, ref e.Member, affinity); e.Datatype = e.Symbol.Type(); return e; } } internal partial class ArrayLengthExpr : MemberAccessExpr { internal ArrayLengthExpr(Expr array) : base(array, array.Token, null) { } internal override void RequireGetAccess() { } internal override void RequireSetAccess() => throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Set); internal override void RequireRefAccess() => throw Binder.AccessModeError(this, Symbol, Symbol.AccessMode.Ref); internal static ArrayLengthExpr Bound(Expr expr) { return new ArrayLengthExpr(expr) { Datatype = Compilation.Get(NativeType.Int32) }; } } internal partial class QualifiedNameExpr : NameExpr { internal override Node Bind(Binder b) { b.Bind(ref Expr, BindAffinity.Type); var s = Expr.Symbol.UniqueTypeOrNamespace(); if (s is TypeSymbol t) { Expr.Symbol = t; Symbol = b.Lookup(t, Member.LookupName) ?? ThrowError(Binder.LookupError(Expr, this)); Datatype = Symbol.Type(); } else if (s is NamespaceSymbol ns) { Expr.Symbol = ns; Symbol = b.Lookup(ns, Member.LookupName) ?? ThrowError(Binder.LookupError(Expr, this)); Datatype = Symbol.Type(); } if (Symbol == null) { if (b.Options.AllowDotAccess) { if (b.Options.UndeclaredVariableResolution != VariableResolution.TreatAsField) { Expr.Symbol = null; // re-bind Expr -- this is a hack!!! b.Bind(ref Expr, Affinity); } if (Expr.Symbol.UniqueIdent() != null) return MemberAccessExpr.Bound(b, Expr, Member, Affinity); if (Expr is NameExpr aname && Member is NameExpr fname) return AliasExpr.Bound(aname.LookupName, fname.LookupName); Expr.RequireValue(); } else Expr.RequireType(); } return null; } internal override Expr Cloned(Binder b) { if (!(Expr.Symbol is TypeSymbol)) b.Cache(ref Expr); return this; } } internal partial class AssignExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Left, BindAffinity.Assign); b.Bind(ref Right); Left.RequireSetAccess(); Right.RequireGetAccess(); b.Convert(ref Right, Left.Datatype); Symbol = Left.Symbol; Datatype = Left.Datatype; return null; } internal static AssignExpr Bound(Expr Left, Expr Right, BindOptions options) { Left.RequireSetAccess(); Right.RequireGetAccess(); Binder.Convert(ref Right, Left.Datatype, options); return new AssignExpr(Left, Left.Token, Right) { Symbol = Left.Symbol, Datatype = Left.Datatype }; } } internal partial class InitExpr : AssignExpr { InitExpr(Expr l, Token o, Expr r) : base(l, o, r) { } internal static new InitExpr Bound(Expr Left, Expr Right, BindOptions options) { Left.RequireInitAccess(); Right.RequireGetAccess(); Binder.Convert(ref Right, Left.Datatype, options); return new InitExpr(Left, Left.Token, Right) { Symbol = Left.Symbol, Datatype = Left.Datatype }; } } internal partial class AssignOpExpr : AssignExpr { internal override Node Bind(Binder b) { b.Bind(ref Left, BindAffinity.Assign); b.Bind(ref Right); Left.RequireGetSetAccess(); Right.RequireGetAccess(); Right = BinaryExpr.Bound(Left.Cloned(b), Token, Right, BinaryOperatorSymbol.OperatorKind(Kind), b.Options.Binding); b.Convert(ref Right, Left.Datatype); Symbol = Left.Symbol; Datatype = Left.Datatype; return null; } internal static AssignOpExpr Bound(Expr Left, Expr Right, BinaryOperatorKind kind, Binder b) { Left.RequireGetSetAccess(); Right.RequireGetAccess(); Right = BinaryExpr.Bound(Left.Cloned(b), Left.Token, Right, kind, b.Options.Binding); b.Convert(ref Right, Left.Datatype); return new AssignOpExpr(Left, Left.Token, Right) { Symbol = Left.Symbol, Datatype = Left.Datatype }; } } internal partial class BinaryExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Left); b.Bind(ref Right); Left.RequireGetAccess(); Right.RequireGetAccess(); if (BinaryOperatorSymbol.OperatorIsLogic(Kind)) Symbol = b.BindBinaryLogicOperation(this, BinaryOperatorSymbol.OperatorKind(Kind)); else Symbol = b.BindBinaryOperation(this, BinaryOperatorSymbol.OperatorKind(Kind)); Datatype = Symbol.Type(); return null; } internal static BinaryExpr Bound(Expr Left, Token t, Expr Right, BinaryOperatorKind kind, BindOptions options) { Left.RequireGetAccess(); Right.RequireGetAccess(); var e = new BinaryExpr(Left, t, Right); e.Symbol = Binder.BindBinaryOperation(e, kind, options); e.Datatype = e.Symbol.Type(); return e; } } internal partial class BinaryLogicExpr : BinaryExpr { internal override Node Bind(Binder b) { b.Bind(ref Left); b.Bind(ref Right); Left.RequireGetAccess(); Right.RequireGetAccess(); Symbol = b.BindBinaryLogicOperation(this, BinaryOperatorSymbol.OperatorKind(Kind)); Datatype = Symbol.Type(); return null; } internal static new BinaryExpr Bound(Expr Left, Token t, Expr Right, BinaryOperatorKind kind, BindOptions options) { Left.RequireGetAccess(); Right.RequireGetAccess(); var e = new BinaryExpr(Left, t, Right); e.Symbol = Binder.BindBinaryOperation(e, kind, options | BindOptions.Logic); e.Datatype = e.Symbol.Type(); return e; } } internal partial class UnaryExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Expr); Expr.RequireGetAccess(); if (UnaryOperatorSymbol.OperatorIsLogic(Kind)) Symbol = b.BindUnaryLogicOperation(this, UnaryOperatorSymbol.OperatorKind(Kind)); else Symbol = b.BindUnaryOperation(this, UnaryOperatorSymbol.OperatorKind(Kind)); Datatype = Symbol.Type(); return null; } internal static UnaryExpr Bound(Expr expr, UnaryOperatorKind kind, BindOptions options) { var e = new UnaryExpr(expr, expr.Token); e.Symbol = Binder.BindUnaryOperation(e, kind, options); e.Datatype = e.Symbol.Type(); return e; } } internal partial class PrefixExpr : UnaryExpr { Expr Left; internal override Node Bind(Binder b) { b.Bind(ref Expr, BindAffinity.Assign); Expr.RequireGetSetAccess(); Left = Expr.Cloned(b); Expr = Bound(Expr, UnaryOperatorSymbol.OperatorKind(Kind), b.Options.Binding); b.Convert(ref Expr, Left.Datatype); Symbol = Expr.Symbol; Datatype = Expr.Datatype; return null; } } internal partial class PostfixExpr : UnaryExpr { Expr Left; Expr Value; internal override Node Bind(Binder b) { b.Bind(ref Expr, BindAffinity.Assign); Expr.RequireGetSetAccess(); Left = Expr.Cloned(b); Value = b.Cache(ref Expr); Expr = Bound(Expr, UnaryOperatorSymbol.OperatorKind(Kind), b.Options.Binding); b.Convert(ref Expr, Left.Datatype); Symbol = Value.Symbol; Datatype = Value.Datatype; return null; } } internal partial class LiteralExpr : Expr { internal override Node Bind(Binder b) { Symbol = b.CreateLiteral(this, Value); Datatype = Symbol.Type(); return null; } internal static LiteralExpr Bound(Constant c) { return new LiteralExpr(Token.None) { Symbol = c, Datatype = c.Type }; } } internal partial class SelfExpr : Expr { internal override Node Bind(Binder b) { throw Error(ErrorCode.NotSupported, "SELF keyword"); } } internal partial class SuperExpr : Expr { internal override Node Bind(Binder b) { throw Error(ErrorCode.NotSupported, "SUPER keyword"); } } internal partial class CheckedExpr : Expr { internal override Node Bind(Binder b) { throw Error(ErrorCode.NotImplemented, "CHECKED expression"); } } internal partial class UncheckedExpr : Expr { internal override Node Bind(Binder b) { throw Error(ErrorCode.NotImplemented, "UNCHECKED expression"); } } internal partial class TypeOfExpr : Expr { internal override Node Bind(Binder b) { throw Error(ErrorCode.NotImplemented, "TYPEOF operator"); } } internal partial class SizeOfExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Type, BindAffinity.Type); Type.RequireType(); Symbol = Type.Symbol as TypeSymbol; Datatype = Compilation.Get(NativeType.UInt32); return null; } internal override void RequireGetAccess() => base.RequireValue(); } internal partial class DefaultExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Type, BindAffinity.Type); Type.RequireType(); if (b.Options.Dialect == XSharpDialect.FoxPro && (Type.Symbol as TypeSymbol).NativeType == NativeType.Usual) return LiteralExpr.Bound(Constant.Create(false)); Symbol = Type.Symbol as TypeSymbol; Datatype = Symbol as TypeSymbol; return null; } internal static Expr Bound(Binder b, TypeSymbol type) { if (b.Options.Dialect == XSharpDialect.FoxPro && type.NativeType == NativeType.Usual) { Expr e = LiteralExpr.Bound(Constant.Create(false)); b.Convert(ref e, type); return e; } return new DefaultExpr(null, null) { Symbol = type, Datatype = type }; } internal override void RequireGetAccess() => base.RequireValue(); } internal partial class TypeCast : Expr { internal override Node Bind(Binder b) { b.Bind(ref Expr); b.Bind(ref Type, BindAffinity.Type); Type.RequireType(); Datatype = Type.Symbol as TypeSymbol; Symbol = b.ExplicitConversion(Expr, Datatype); if (!(Symbol as ConversionSymbol).Exists) ThrowError(ErrorCode.NoConversion, Expr.Datatype, Type.Symbol); return null; } internal static TypeCast Bound(Binder b, Expr e, TypeSymbol t) { var s = b.ExplicitConversion(e, t); return new TypeCast(null, e) { Datatype = t, Symbol = s }; } } internal partial class TypeConversion : TypeCast { internal static TypeConversion Bound(Expr e, TypeSymbol t, ConversionSymbol conv) { return new TypeConversion(null, e) { Datatype = t, Symbol = conv }; } internal new static Expr Bound(Binder b, Expr e, TypeSymbol t) { b.Convert(ref e, t); return e; } } internal partial class IsExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Expr); b.Bind(ref Type, BindAffinity.Type); Expr.RequireGetAccess(); Type.RequireType(); Symbol = Type.Symbol as TypeSymbol; if (Expr.Datatype.IsValueType) { if (Binder.TypesMatch(Expr.Datatype, Type.Symbol as TypeSymbol)) return LiteralExpr.Bound(Constant.Create(true)); else if (Binder.TypesMatch(Type.Symbol as TypeSymbol, Compilation.Get(WellKnownTypes.System_ValueType))) return LiteralExpr.Bound(Constant.Create(true)); else if (Binder.TypesMatch(Type.Symbol as TypeSymbol, Compilation.Get(NativeType.Object))) return LiteralExpr.Bound(Constant.Create(true)); return LiteralExpr.Bound(Constant.Create(false)); } Datatype = Compilation.Get(NativeType.Boolean); return null; } internal static Expr Bound(Expr expr, TypeExpr type) { if (expr.Datatype.IsValueType) { if (Binder.TypesMatch(expr.Datatype, type.Symbol as TypeSymbol)) return LiteralExpr.Bound(Constant.Create(true)); else if (Binder.TypesMatch(type.Symbol as TypeSymbol, Compilation.Get(WellKnownTypes.System_ValueType))) return LiteralExpr.Bound(Constant.Create(true)); else if (Binder.TypesMatch(type.Symbol as TypeSymbol, Compilation.Get(NativeType.Object))) return LiteralExpr.Bound(Constant.Create(true)); return LiteralExpr.Bound(Constant.Create(false)); } return new IsExpr(expr, type, null) { Symbol = type.Symbol, Datatype = Compilation.Get(NativeType.Boolean) }; } internal override void RequireGetAccess() { } } internal partial class IsVarExpr : IsExpr { internal LocalSymbol Var; internal bool? Check = null; internal static IsVarExpr Bound(Expr expr, TypeExpr type, LocalSymbol var) { bool? check = null; if (expr.Datatype.IsValueType) { if (Binder.TypesMatch(expr.Datatype, type.Symbol as TypeSymbol)) check = true; else if (Binder.TypesMatch(type.Symbol as TypeSymbol, Compilation.Get(WellKnownTypes.System_ValueType))) check = true; else if (Binder.TypesMatch(type.Symbol as TypeSymbol, Compilation.Get(NativeType.Object))) check = true; else check = false; } return new IsVarExpr(expr, type, null, null) { Symbol = type.Symbol, Datatype = Compilation.Get(NativeType.Boolean), Var = var, Check = check }; } } internal partial class AsTypeExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Expr); b.Bind(ref Type, BindAffinity.Type); Expr.RequireGetAccess(); Type.RequireType(); Symbol = Type.Symbol as TypeSymbol; Datatype = Type.Symbol as TypeSymbol; return null; } internal static Expr Bound(Expr expr, TypeExpr type) { return new AsTypeExpr(expr, type, null) { Symbol = type.Symbol, Datatype = type.Symbol as TypeSymbol }; } internal override void RequireGetAccess() { } } internal partial class MethodCallExpr : Expr { protected Expr Self = null; protected Expr WriteBack = null; internal override Node Bind(Binder b) { if (b.Options.FoxParenArrayAccess && Expr is IdExpr id && (Args.Args.Count == 1 || Args.Args.Count == 2)) { // Todo: // Validate also if the array indexes are or could be numeric // So valid are: // LONG, USUAL, OBJECT // When not, then we call the function always if (Affinity == BindAffinity.Assign) { // transform to array access var a = new ArrayAccessExpr(Expr, Args); b.Bind(ref a, Affinity); return a; } else { Expr e = new IdExpr(id.Name); b.Bind(ref e, BindAffinity.Invoke); if (e.Symbol?.IsMethodOrMethodGroup() == true) { if (b.Options.UndeclaredVariableResolution == VariableResolution.TreatAsFieldOrMemvar) { // transform to call to __FoxArrayAccess() var m = (Args.Args.Count == 1) ? WellKnownMembers.XSharp_VFP_Functions___FoxArrayAccess_1 : WellKnownMembers.XSharp_VFP_Functions___FoxArrayAccess_2; Args.Args.Insert(0, new Arg(LiteralExpr.Bound(Constant.Create(id.Name)))); Args.Args.Insert(1, new Arg(new IdExpr(id.Name))); b.Bind(ref Args); if (Args.Args[1].Expr is AutoVarExpr av) av.Safe = true; return MethodCallExpr.Bound(b, null, Compilation.Get(m), null, Args); } } else { // transform to array access var a = new ArrayAccessExpr(Expr, Args); b.Bind(ref a, Affinity); return a; } } } b.Bind(ref Expr, BindAffinity.Invoke); b.Bind(ref Args); Symbol = b.BindMethodCall(Expr, Expr.Symbol, Args, out Self, out WriteBack); Datatype = Symbol.Type(); if (Self?.Datatype.IsValueType == true) { if ((Symbol as MethodSymbol).DeclaringType.IsValueType) { if (!Symbol.HasRefAccess) { b.Cache(ref Self); } b.Convert(ref Self, Binder.ByRefOf(Self.Datatype)); } else { b.Convert(ref Self, Compilation.Get(NativeType.Object)); } } return null; } internal static MethodCallExpr Bound(Expr e, Symbol sym, Expr self, ArgList args, Expr writeBack = null) { return new MethodCallExpr(e, args) { Symbol = sym, Datatype = sym.Type(), Self = self, WriteBack = writeBack }; } internal static MethodCallExpr Bound(Binder b, Expr e, Symbol sym, Expr self, ArgList args) { Expr boundSelf; Expr writeBack; if (self != null) e = new MemberAccessExpr(self, null, null); var m = b.BindMethodCall(e, sym, args, out boundSelf, out writeBack); return new MethodCallExpr(e, args) { Symbol = m, Datatype = m.Type(), Self = boundSelf, WriteBack = writeBack }; } internal static MethodCallExpr Bound(Binder b, Expr e, string name, ArgList args) { Expr m = new IdExpr(name); Expr self; Expr writeBack; var ms = b.BindMemberAccess(ref e, ref m, BindAffinity.Invoke); if (!(ms is MethodSymbol)) throw e.Error(ErrorCode.Internal); var expr = new MemberAccessExpr(e, e.Token, m) { Symbol = ms }; var sym = b.BindMethodCall(expr, ms, ArgList.Empty, out self, out writeBack); return Bound(e, sym, self, ArgList.Empty, writeBack); } } internal partial class CtorCallExpr : MethodCallExpr { internal override Node Bind(Binder b) { b.Bind(ref Expr, BindAffinity.Type); Expr.RequireType(); b.Bind(ref Args); Symbol = b.BindCtorCall(Expr, Expr.Symbol, Args, out WriteBack); Datatype = Symbol.Type(); return null; } internal static CtorCallExpr Bound(Binder b, TypeExpr type, ArgList args) { Expr writeBack; var sym = b.BindCtorCall(type, type.Symbol, args, out writeBack); return new CtorCallExpr(type, args) { Symbol = sym, Datatype = sym.Type(), WriteBack = writeBack }; } } internal partial class IntrinsicCallExpr : MethodCallExpr { internal override Node Bind(Binder b) { b.Bind(ref Args); switch (Kind) { case IntrinsicCallType.GetFParam: case IntrinsicCallType.GetMParam: b.ConvertArrayBase(Args); b.ConvertExplicit(ref Args.Args[0].Expr, Compilation.Get(NativeType.UInt32)); Symbol = b.Lookup(XSharpSpecialNames.ClipperArgs); Datatype = Compilation.Get(NativeType.Object); break; case IntrinsicCallType.Chr: b.ConvertExplicit(ref Args.Args[0].Expr, Compilation.Get(NativeType.UInt32)); Symbol = Compilation.Get(WellKnownMembers.XSharp_Core_Functions_Chr); Datatype = Symbol.Type(); break; default: throw new InternalError(); } return null; } } internal partial class ArrayAccessExpr : MethodCallExpr { internal override Node Bind(Binder b) { b.Bind(ref Expr); Expr.RequireGetAccess(); b.Bind(ref Args); if (Expr.Datatype.IsUsualOrObject()) { b.Convert(ref Expr, Compilation.Get(NativeType.Array)); } if (Binder.TypesMatch(Expr.Datatype,NativeType.Array) || Expr.Datatype.IsArray) { b.ConvertArrayBase(Args); } if (Expr.Datatype.IsArray && Expr.Datatype.ArrayRank == 1) { if (Args.Args.Count != 1) throw Error(ErrorCode.WrongNumberIfIndices); return NativeArrayAccessExpr.Bound(Expr, Args); } Self = Expr; var s = Self.Datatype.Lookup(SystemNames.IndexerName); Symbol = b.BindArrayAccess(Self, s, Args); Datatype = Symbol.Type(); if (Expr.Datatype.IsArray && Expr.Datatype != Datatype) { Expr conv = this; b.Convert(ref conv, Expr.Datatype.ElementType); return conv; } return null; } internal override Expr Cloned(Binder b) { b.Cache(ref Expr); foreach (var arg in Args.Args) b.Cache(ref arg.Expr); return this; } internal static ArrayAccessExpr Bound(Expr e, ArgList a, Binder b) { if (e.Datatype.IsUsualOrObject()) { b.Convert(ref e, Compilation.Get(NativeType.Array)); } if (Binder.TypesMatch(e.Datatype, NativeType.Array) || e.Datatype.IsArray) { b.ConvertArrayBase(a); } if (e.Datatype.IsArray && e.Datatype.ArrayRank == 1) { if (a.Args.Count != 1) throw e.Error(ErrorCode.WrongNumberIfIndices); return NativeArrayAccessExpr.Bound(e, a); } var item = e.Datatype.Lookup(SystemNames.IndexerName); var sym = b.BindArrayAccess(e, item, a); return new ArrayAccessExpr(e, a) { Self = e, Symbol = sym, Datatype = sym.Type() }; } internal override void RequireSetAccess() => RequireGetAccess(); internal override void RequireGetSetAccess() => RequireGetAccess(); } internal partial class NativeArrayAccessExpr : ArrayAccessExpr { NativeArrayAccessExpr(Expr e, ArgList a) : base(e, a) { } internal static NativeArrayAccessExpr Bound(Expr e, ArgList a) { return new NativeArrayAccessExpr(e, a) { Self = e, Symbol = e.Symbol, Datatype = e.Symbol.Type().ElementType }; } } internal partial class EmptyExpr : Expr { internal override Node Bind(Binder b) { Symbol = Constant.CreateDefault(Compilation.Get(NativeType.Usual)); Datatype = Symbol.Type(); return null; } } internal partial class ExprList : Expr { internal override Node Bind(Binder b) { b.Bind(Exprs); foreach(var expr in Exprs) expr.RequireValue(); var e = Exprs.LastOrDefault(); if (e != null) { Symbol = e.Symbol; Datatype = e.Datatype; } else { Datatype = Compilation.Get(NativeType.Void); } return null; } } internal partial class LiteralArray : Expr { internal override Node Bind(Binder b) { if (ElemType != null) { b.Bind(ref ElemType, BindAffinity.Type); ElemType.RequireType(); } b.Bind(ref Values); if (ElemType != null) ConvertElements(ElemType.Symbol as TypeSymbol); else ConvertElements(Compilation.Get(NativeType.Usual) ?? Compilation.Get(NativeType.Object), Compilation.Get(WellKnownTypes.XSharp___Array)); return null; } internal static LiteralArray Bound(IList<Expr> values, TypeSymbol type = null) { var e = new LiteralArray(new ExprList(values)); e.ConvertElements(type ?? Compilation.Get(NativeType.Usual) ?? Compilation.Get(NativeType.Object)); return e; } internal static LiteralArray Bound(IList<Arg> args, TypeSymbol type = null) { var values = new List<Expr>(args.Count); foreach(var a in args) values.Add(a.Expr); return Bound(values, type); } private void ConvertElements(TypeSymbol et, TypeSymbol dt = null) { for (int i = 0; i < Values.Exprs.Count; i++) { var v = Values.Exprs[i]; Binder.Convert(ref v, et, BindOptions.Default); Values.Exprs[i] = v; } Symbol = et; Datatype = dt ?? Binder.ArrayOf(et); } internal override void RequireGetAccess() => base.RequireValue(); } internal partial class IifExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Cond); b.Bind(ref True); b.Bind(ref False); Cond.RequireGetAccess(); True.RequireGetAccess(); False.RequireGetAccess(); b.Convert(ref Cond, Compilation.Get(NativeType.Boolean)); Datatype = b.ConvertResult(ref True, ref False); return null; } internal static IifExpr Bound(Expr cond, Expr t, Expr f, BindOptions opt) { cond.RequireGetAccess(); t.RequireGetAccess(); f.RequireGetAccess(); Binder.Convert(ref cond, Compilation.Get(NativeType.Boolean), Binder.Conversion(cond, Compilation.Get(NativeType.Boolean), opt)); var r = new IifExpr(cond, t, f, cond.Token); r.Datatype = Binder.ConvertResult(ref r.True, ref r.False, opt); return r; } internal override void RequireGetAccess() => base.RequireValue(); } internal partial class MacroExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Expr); Expr.RequireGetAccess(); this.Symbol = Compilation.Get(WellKnownMembers.XSharp_RT_Functions_Evaluate); b.Convert(ref Expr, Compilation.Get(NativeType.String)); Datatype = Compilation.Get(NativeType.Usual); return null; } } internal partial class MacroId : Expr { internal override Node Bind(Binder b) { b.Bind(ref Id); Id.RequireGetAccess(); b.Convert(ref Id, Compilation.Get(NativeType.String)); Datatype = Compilation.Get(NativeType.Usual); return null; } } internal partial class MemvarExpr : Expr { internal override Node Bind(Binder b) { b.Bind(ref Var); Var.RequireGetAccess(); b.Convert(ref Var, Compilation.Get(NativeType.String)); Datatype = Compilation.Get(NativeType.Usual); return null; } internal override void RequireGetAccess() => RequireValue(); internal override void RequireSetAccess() => RequireValue(); internal override void RequireGetSetAccess() => RequireValue(); } internal partial class AliasExpr : Expr { internal override Node Bind(Binder b) { if (Alias != null) { b.Bind(ref Alias); Alias.RequireGetAccess(); var m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___FieldGetWa) as MethodSymbol; b.Convert(ref Alias, Binder.FindType(m.Parameters.Parameters[0].ParameterType)); } b.Bind(ref Field); Field.RequireGetAccess(); b.Convert(ref Field, Compilation.Get(NativeType.String)); Datatype = Compilation.Get(NativeType.Usual); return null; } internal static AliasExpr Bound(string fieldName) { return new AliasExpr(null, LiteralExpr.Bound(Constant.Create(fieldName)), Token.None) { Datatype = Compilation.Get(NativeType.Usual) }; } internal static AliasExpr Bound(string aliasName, string fieldName) { return new AliasExpr( LiteralExpr.Bound(Constant.Create(aliasName)), LiteralExpr.Bound(Constant.Create(fieldName)), Token.None) { Datatype = Compilation.Get(NativeType.Usual) }; } internal static AliasExpr Bound(Expr field) { return new AliasExpr(null, field, Token.None) { Datatype = Compilation.Get(NativeType.Usual) }; } internal override void RequireGetAccess() => RequireValue(); internal override void RequireSetAccess() => RequireValue(); internal override void RequireGetSetAccess() => RequireValue(); } internal partial class AliasWaExpr : AliasExpr { Stmt Stmt; internal override Node Bind(Binder b) { Stmt = b.StmtStack.Peek(); if (Alias != null) { b.Bind(ref Alias, BindAffinity.Alias); Alias.RequireGetAccess(); b.Convert(ref Alias, Compilation.Get(NativeType.Usual)); Stmt.RequireExceptionHandling = true; } b.Bind(ref Field, BindAffinity.AliasField); Datatype = Field.Datatype; return null; } internal override void RequireGetAccess() => Field.RequireGetAccess(); internal override void RequireSetAccess() => Field.RequireSetAccess(); internal override void RequireGetSetAccess() => Field.RequireGetSetAccess(); } internal partial class RuntimeIdExpr : Expr { internal override Node Bind(Binder b) { // check for macro expression // When & is followed by a ( // then this is parsed a so called ParenExpression // We consider this to be a macro // unless it is prefixed by a ":" or a "->" token. // The & could be the first token in the macro // so check to make sure that there is a Prev token // There is Always a next token after the &, either an ID or a LPAREN bool macroCompile = false; TokenType prev = this.Token.Prev != null ? this.Token.Prev.Type : TokenType.WS; if (this.Token.Next.Type == TokenType.LPAREN && prev!= TokenType.COLON && prev != TokenType.ALIAS) { Expr = new MacroExpr(Expr, this.Token); macroCompile = true; } b.Bind(ref Expr); Expr.RequireGetAccess(); if (macroCompile) b.Convert(ref Expr, Compilation.Get(NativeType.Usual)); else b.Convert(ref Expr, Compilation.Get(NativeType.String)); switch (Affinity) { case BindAffinity.AliasField: return AliasExpr.Bound(Expr); case BindAffinity.Member: return Expr; case BindAffinity.Access when macroCompile: return Expr; default: ThrowError(ErrorCode.InvalidRuntimeIdExpr); break; } return null; } internal override void RequireGetAccess() => RequireValue(); internal override void RequireSetAccess() => RequireValue(); internal override void RequireGetSetAccess() => RequireValue(); } internal partial class SubstrExpr : BinaryExpr { internal override Node Bind(Binder b) { b.Bind(ref Left); b.Bind(ref Right); Left.RequireGetAccess(); Right.RequireGetAccess(); b.Convert(ref Left, Compilation.Get(NativeType.String)); b.Convert(ref Right, Compilation.Get(NativeType.String)); Symbol = Compilation.Get(WellKnownMembers.XSharp_Core_Functions_Instr); Datatype = Compilation.Get(NativeType.Boolean); return null; } } internal partial class AutoVarExpr : Expr { internal Expr Var; internal bool Safe = false; AutoVarExpr(Expr var) : base(var.Token) { Var = var; } public override string ToString() { return "{Var:" + Var.ToString() + "}"; } internal static AutoVarExpr Bound(string varName, bool safe = false) { var e = LiteralExpr.Bound(Constant.Create(varName)); return new AutoVarExpr(e) { Symbol = e.Symbol, Datatype = Compilation.Get(NativeType.Usual), Safe = safe }; } internal override void RequireGetAccess() => RequireValue(); internal override void RequireSetAccess() => RequireValue(); internal override void RequireGetSetAccess() => RequireValue(); } internal partial class Arg : Node { internal override Node Bind(Binder b) { b.Bind(ref Expr); Expr.RequireGetAccess(); return null; } } internal partial class ArgList : Node { internal override Node Bind(Binder b) { b.Bind(Args); return null; } internal static ArgList Bound(params Expr[] argExprs) { return new ArgList(new List<Arg>(argExprs.Select(e => new Arg(e)))); } } internal partial class Codeblock : Node { LocalSymbol PCount; ArgumentSymbol ParamArray; internal override Node Bind(Binder b) { b.Entity = this; if (Params != null) { foreach (var p in Params) { b.AddLocal(p.LookupName, b.ObjectType,true); p.Bind(b); } } ParamArray = b.AddParam(XSharpSpecialNames.ClipperArgs, Binder.ArrayOf(b.ObjectType)); b.AddConstant(XSharpSpecialNames.ClipperArgCount, Constant.Create(Params?.Count ?? 0)); PCount = b.AddLocal(XSharpSpecialNames.ClipperPCount, Compilation.Get(NativeType.Int32)); if (Body != null) { b.BindStmt(ref Body); } return null; } } internal partial class CodeblockExpr : Expr { Binder NestedBinder; int CbIndex; IList<XSharp.Codeblock> CbList; bool usualMacro; internal override Node Bind(Binder b) { NestedBinder = b.CreateNested(); NestedBinder.Bind(ref Codeblock); CbIndex = b.AddNestedCodeblock(out Symbol); CbList = b.NestedCodeblocks; Datatype = Compilation.Get(WellKnownTypes.XSharp_Codeblock); usualMacro = b.ObjectType == Compilation.Get(NativeType.Usual); return null; } internal override void RequireGetAccess() => RequireValue(); } }
/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Shield.Services { using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Shield.Core; using Windows.Devices.Geolocation; using Windows.Devices.Sensors; using Windows.UI.Core; using Windows.UI.Xaml; public class DataItem : DependencyObject, INotifyPropertyChanged { public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(double), typeof(DataItem), new PropertyMetadata(0d, OnValueChanged)); public string Name { get; set; } public double Value { get { return (double)this.GetValue(ValueProperty); } set { this.SetValue(ValueProperty, value); } } public event PropertyChangedEventHandler PropertyChanged; private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs a) { var di = d as DataItem; di.NotifyPropertyChanged("Value"); } private void NotifyPropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } } public class DataItems : ObservableCollection<DataItem> { public void Refresh() { this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } public class XYZ : DependencyObject { public bool IsChanged; public XYZ() { } public XYZ(object source, string name, string tag, string[] names) { this.Source = source; this.Name = name; this.Tag = tag; this.Data = new DataItems(); foreach (var item in names) { var newitem = new DataItem { Name = item, Value = 0 }; newitem.PropertyChanged += this.SubPropertyChanged; this.Data.Add(newitem); } } // public double X { get; set; } // public double Y { get; set; } // public double Z { get; set; } // public double W { get; set; } public int Id { get; set; } public object Source { get; set; } public string Name { get; set; } public string Tag { get; set; } public double Delta { get; set; } public DataItems Data { get; set; } private bool IsWithinDelta(double a, double b) { return Math.Abs(b - a) < this.Delta; } public XYZ New(double x, double y, double z, double w) { var item = this; // ew XYZ() { Source = Source, Data = Data, Name = Name, Tag = Tag }; if (this.Delta > 0 && this.IsWithinDelta(x, item.Data[0].Value) && this.IsWithinDelta(y, item.Data[1].Value) && this.IsWithinDelta(z, item.Data[2].Value) && (item.Data.Count() < 4 || this.IsWithinDelta(w, item.Data[3].Value))) { this.IsChanged = false; return this; // no change } this.IsChanged = true; item.Data[0].Value = x; item.Data[1].Value = y; item.Data[2].Value = z; if (item.Data.Count() > 3) { item.Data[3].Value = w; } item.Data.Refresh(); return item; } public XYZ New() { this.IsChanged = true; return this; } private void SubPropertyChanged(object sender, PropertyChangedEventArgs args) { } } public class Sensors : ObservableCollection<XYZ> { public delegate void SensorUpdated(XYZ data); private const int ACCELERATOR = 0; private const int GYROSCOPE = 1; private const int COMPASS = 2; private const int LOCATION = 3; private const int QUANTIZATION = 4; private const int LIGHTSENSOR = 5; private const uint baseMinimum = 100; // ms private readonly CoreDispatcher dispatcher; private Accelerometer accelerometer; private Compass compass; private Geolocator geolocator; private Gyrometer gyrometer; private LightSensor lightSensor; private OrientationSensor orientation; public Sensors() { this.Add(new XYZ(this.accelerometer, "Accelerometer", "A", new[] { "X", "Y", "Z" })); this.Add(new XYZ(this.gyrometer, "Gyroscope", "G", new[] { "X", "Y", "Z" })); this.Add(new XYZ(this.compass, "Compass", "M", new[] { "Mag", "True" })); this.Add(new XYZ(this.geolocator, "Location", "L", new[] { "Lat", "Lon", "Alt" })); this.Add(new XYZ(this.orientation, "Orientation", "Q", new[] { "X", "Y", "Z", "W" })); this.Add(new XYZ(this.lightSensor, "LightSensor", "P", new[] { "Lux" })); } public Sensors(CoreDispatcher dispatcher) : this() { this.dispatcher = dispatcher; this.SensorSwitches = new SensorSwitches(); } public Sensors ItemsList => this; public SensorSwitches SensorSwitches { get; set; } public bool IsSending { get; set; } public event SensorUpdated OnSensorUpdated; public async void NewLight(LightSensor sender, LightSensorReadingChangedEventArgs args) { var reading = args == null ? sender?.GetCurrentReading() : args.Reading; await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[LIGHTSENSOR] = reading == null ? this[LIGHTSENSOR].New() : this[LIGHTSENSOR].New(reading.IlluminanceInLux, 0, 0, 0); if (this[LIGHTSENSOR].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[LIGHTSENSOR]); } }); if (this.SensorSwitches.P.HasValue && (this.SensorSwitches.P.Value == 1 || this.SensorSwitches.P.Value == 3)) { this.SensorSwitches.P = 0; } } public async void NewAcc(Accelerometer sender, AccelerometerReadingChangedEventArgs args) { var reading = args == null ? sender?.GetCurrentReading() : args.Reading; await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[ACCELERATOR] = reading == null ? this[ACCELERATOR].New() : this[ACCELERATOR].New( reading.AccelerationX, reading.AccelerationY, reading.AccelerationZ, 0); if (this[ACCELERATOR].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[ACCELERATOR]); } }); if (this.SensorSwitches.A.HasValue && (this.SensorSwitches.A.Value == 1 || this.SensorSwitches.A.Value == 3)) { this.SensorSwitches.A = 0; } } public async void NewGyro(Gyrometer sender, GyrometerReadingChangedEventArgs args) { var reading = args == null ? sender?.GetCurrentReading() : args.Reading; await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[GYROSCOPE] = reading == null ? this[GYROSCOPE].New(0, 0, 0, 0) : this[GYROSCOPE].New( reading.AngularVelocityX, reading.AngularVelocityY, reading.AngularVelocityZ, 0); if (this[GYROSCOPE].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[GYROSCOPE]); } }); if (this.SensorSwitches.G.HasValue && (this.SensorSwitches.G.Value == 1 || this.SensorSwitches.G.Value == 3)) { this.SensorSwitches.G = 0; } } public async void NewCom(Compass sender, CompassReadingChangedEventArgs args) { var reading = args == null ? sender?.GetCurrentReading() : args.Reading; await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[COMPASS] = reading == null ? this[COMPASS].New(0, 0, 0, 0) : this[COMPASS].New( reading.HeadingMagneticNorth, reading.HeadingTrueNorth ?? 0, 0, 0); if (this[COMPASS].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[COMPASS]); } }); if (this.SensorSwitches.M.HasValue && (this.SensorSwitches.M.Value == 1 || this.SensorSwitches.M.Value == 3)) { this.SensorSwitches.M = 0; } } public async void NewLoc(Geolocator sender, PositionChangedEventArgs args) { Geoposition reading = null; try { reading = args == null ? (sender == null ? null : (await sender.GetGeopositionAsync())) : args.Position; } catch (UnauthorizedAccessException uae) { throw new UnsupportedSensorException("Geolocator not enabled : " + uae.Message); } await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[LOCATION] = reading == null ? this[LOCATION].New(0, 0, 0, 0) : this[LOCATION].New( reading.Coordinate.Point.Position.Latitude, reading.Coordinate.Point.Position.Longitude, reading.Coordinate.Point.Position.Altitude, 0); if (this[LOCATION].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[LOCATION]); } }); if (this.SensorSwitches.L.HasValue && (this.SensorSwitches.L.Value == 1 || this.SensorSwitches.L.Value == 3)) { this.SensorSwitches.L = 0; } } public async void NewQuan(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args) { var reading = args == null ? sender?.GetCurrentReading() : args.Reading; await this.dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { this[QUANTIZATION] = reading == null ? this[QUANTIZATION].New(0, 0, 0, 0) : this[QUANTIZATION].New( reading.Quaternion.X, reading.Quaternion.Y, reading.Quaternion.Z, reading.Quaternion.W); if (this[QUANTIZATION].IsChanged) { this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList")); this.OnSensorUpdated?.Invoke(this[QUANTIZATION]); } }); if (this.SensorSwitches.Q.HasValue && (this.SensorSwitches.Q.Value == 1 || this.SensorSwitches.Q.Value == 3)) { this.SensorSwitches.Q = 0; } } #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async void Start() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { try { this.ToggleAccelerometer(); } catch (Exception e) { throw new UnsupportedSensorException("Accelerometer error: " + e.Message); } try { this.ToggleGyrometer(); } catch (Exception e) { throw new UnsupportedSensorException("Gyrometer error: " + e.Message); } try { this.ToggleCompass(); } catch (Exception e) { throw new UnsupportedSensorException("Compass error: " + e.Message); } try { this.ToggleGeolocator(); } catch (Exception e) { throw new UnsupportedSensorException("Geolocator error: " + e.Message); } try { this.ToggleOrientation(); } catch (Exception e) { throw new UnsupportedSensorException("Orientation error: " + e.Message); } try { this.ToggleLightSensor(); } catch (Exception e) { throw new UnsupportedSensorException("LightSensor error: " + e.Message); } } private void ToggleLightSensor() { if (this.SensorSwitches.P != null) { if (this.SensorSwitches.P.Value > 0) { if (this.lightSensor == null) { this.lightSensor = LightSensor.GetDefault(); } if (this.lightSensor != null) { this[LIGHTSENSOR].Id = this.SensorSwitches.Id; this[LIGHTSENSOR].Delta = this.SensorSwitches.Delta; this.lightSensor.ReportInterval = Math.Max( Math.Max(baseMinimum, (uint)this.SensorSwitches.Interval), this.lightSensor.MinimumReportInterval); if (this.SensorSwitches.P.Value != 1) { this.lightSensor.ReadingChanged += this.NewLight; } if (this.SensorSwitches.P.Value != 3) { this.SensorSwitches.P = null; this.NewLight(this.lightSensor, null); } else { this.SensorSwitches.P = null; } } } else { if (this.lightSensor != null) { this.lightSensor.ReadingChanged -= this.NewLight; this.NewQuan(null, null); } this.SensorSwitches.P = null; } } } private void ToggleOrientation() { if (this.SensorSwitches.Q != null) { if (this.SensorSwitches.Q.Value > 0) { if (this.orientation == null) { this.orientation = OrientationSensor.GetDefault(); } if (this.orientation != null) { this[QUANTIZATION].Id = this.SensorSwitches.Id; this[QUANTIZATION].Delta = this.SensorSwitches.Delta; this.orientation.ReportInterval = Math.Max( Math.Max(baseMinimum, (uint)this.SensorSwitches.Interval), this.orientation.MinimumReportInterval); if (this.SensorSwitches.Q.Value != 1) { this.orientation.ReadingChanged += this.NewQuan; } if (this.SensorSwitches.Q.Value != 3) { this.SensorSwitches.Q = null; this.NewQuan(this.orientation, null); } else { this.SensorSwitches.Q = null; } } } else { if (this.orientation != null) { this.orientation.ReadingChanged -= this.NewQuan; this.NewQuan(null, null); } this.SensorSwitches.Q = null; } } } private void ToggleGeolocator() { if (this.SensorSwitches.L != null) { if (this.SensorSwitches.L.Value > 0) { if (this.geolocator == null) { this.geolocator = new Geolocator(); } if (this.geolocator != null) { this.geolocator.ReportInterval = 30 * 60 * 1000; this[LOCATION].Id = this.SensorSwitches.Id; this[LOCATION].Delta = this.SensorSwitches.Delta; if (this.SensorSwitches.L.Value != 1) { this.geolocator.PositionChanged += this.NewLoc; } if (this.SensorSwitches.L.Value != 3) { this.SensorSwitches.L = null; try { this.NewLoc(this.geolocator, null); } catch (UnsupportedSensorException use) { // record this.SensorSwitches.L = null; } } else { this.SensorSwitches.L = null; } } } else { if (this.geolocator != null) { this.geolocator.PositionChanged -= this.NewLoc; this.NewLoc(null, null); } this.SensorSwitches.L = null; } } } private void ToggleCompass() { if (this.SensorSwitches.M != null) { if (this.SensorSwitches.M.Value > 0) { if (this.compass == null) { this.compass = Compass.GetDefault(); } if (this.compass != null) { this.compass.ReportInterval = Math.Max( Math.Max(baseMinimum, (uint)this.SensorSwitches.Interval), this.compass.MinimumReportInterval); if (this.SensorSwitches.M.Value != 1) { this.compass.ReadingChanged += this.NewCom; } this[COMPASS].Id = this.SensorSwitches.Id; this[COMPASS].Delta = this.SensorSwitches.Delta; if (this.SensorSwitches.M.Value != 3) { this.SensorSwitches.M = null; this.NewCom(this.compass, null); } else { this.SensorSwitches.M = null; } } } else { if (this.compass != null) { this.compass.ReadingChanged -= this.NewCom; this.NewCom(null, null); } this.SensorSwitches.M = null; } } } private void ToggleGyrometer() { if (this.SensorSwitches.G != null) { if (this.SensorSwitches.G.Value > 0) { if (this.gyrometer == null) { this.gyrometer = Gyrometer.GetDefault(); } if (this.gyrometer != null) { this.gyrometer.ReportInterval = Math.Max( Math.Max(baseMinimum, (uint)this.SensorSwitches.Interval), this.gyrometer.MinimumReportInterval); if (this.SensorSwitches.G.Value != 1) { this.gyrometer.ReadingChanged += this.NewGyro; } this[GYROSCOPE].Id = this.SensorSwitches.Id; this[GYROSCOPE].Delta = this.SensorSwitches.Delta; if (this.SensorSwitches.G.Value != 3) { this.SensorSwitches.G = null; this.NewGyro(this.gyrometer, null); } else { this.SensorSwitches.G = null; } } } else { if (this.gyrometer != null) { this.gyrometer.ReadingChanged -= this.NewGyro; this.NewGyro(null, null); } this.SensorSwitches.G = null; } } } private void ToggleAccelerometer() { if (this.SensorSwitches.A != null) { if (this.SensorSwitches.A.Value > 0) { if (this.accelerometer == null) { this.accelerometer = Accelerometer.GetDefault(); } if (this.accelerometer != null) { this.accelerometer.ReportInterval = Math.Max( Math.Max(baseMinimum, (uint)this.SensorSwitches.Interval), this.accelerometer.MinimumReportInterval); if (this.SensorSwitches.A.Value != 1) { this.accelerometer.ReadingChanged += this.NewAcc; } this[ACCELERATOR].Id = this.SensorSwitches.Id; this[ACCELERATOR].Delta = this.SensorSwitches.Delta; if (this.SensorSwitches.A.Value != 3) { this.SensorSwitches.A = null; this.NewAcc(this.accelerometer, null); } else { this.SensorSwitches.A = null; } } } else { if (this.accelerometer != null) { this.accelerometer.ReadingChanged -= this.NewAcc; this.NewAcc(null, null); } this.SensorSwitches.A = null; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Utils; using Avalonia.Media; namespace AvaloniaEdit.Text { internal sealed class TextLineImpl : TextLine { private const int MaxCharactersPerLine = 10000; private readonly TextLineRun[] _runs; public override int FirstIndex { get; } public override int Length { get; } public override int TrailingWhitespaceLength { get; } public override double Width { get; } public override double WidthIncludingTrailingWhitespace { get; } public override double Height { get; } public override double Baseline { get; } internal static TextLineImpl Create(TextParagraphProperties paragraphProperties, int firstIndex, int paragraphLength, TextSource textSource) { var index = firstIndex; var visibleLength = 0; var widthLeft = paragraphLength > 0 ? paragraphLength : double.MaxValue; TextLineRun prevRun = null; var run = TextLineRun.Create(textSource, index, firstIndex, widthLeft); if (!run.IsEnd && run.Width <= widthLeft) { index += run.Length; widthLeft -= run.Width; prevRun = run; run = TextLineRun.Create(textSource, index, firstIndex, widthLeft); } var trailing = new TrailingInfo(); var runs = new List<TextLineRun>(2); if (prevRun != null) { visibleLength += AddRunReturnVisibleLength(runs, prevRun); } if (visibleLength >= MaxCharactersPerLine) { throw new NotSupportedException("Too many characters per line"); } while (true) { visibleLength += AddRunReturnVisibleLength(runs, run); index += run.Length; widthLeft -= run.Width; if (run.IsEnd || widthLeft <= 0) { trailing.SpaceWidth = 0; UpdateTrailingInfo(runs, trailing); return new TextLineImpl(paragraphProperties, firstIndex, runs, trailing); } run = TextLineRun.Create(textSource, index, firstIndex, widthLeft); } } private TextLineImpl(TextParagraphProperties paragraphProperties, int firstIndex, List<TextLineRun> runs, TrailingInfo trailing) { var top = 0.0; var height = 0.0; var index = 0; _runs = new TextLineRun[runs.Count]; foreach (var run in runs) { _runs[index++] = run; if (run.Length <= 0) continue; if (run.IsEnd) { trailing.Count += run.Length; } else { top = Math.Max(top, run.Height - run.Baseline); height = Math.Max(height, run.Height); Baseline = Math.Max(Baseline, run.Baseline); } Length += run.Length; WidthIncludingTrailingWhitespace += run.Width; } Height = height.IsClose(Baseline + top) ? height : Baseline; if (Height <= 0) { var fontSize = paragraphProperties.DefaultTextRunProperties.FontSize; Height = fontSize * TextLineRun.HeightFactor; Baseline = fontSize * TextLineRun.BaselineFactor; } FirstIndex = firstIndex; TrailingWhitespaceLength = trailing.Count; Width = WidthIncludingTrailingWhitespace - trailing.SpaceWidth; } private static void UpdateTrailingInfo(List<TextLineRun> runs, TrailingInfo trailing) { for (var index = (runs?.Count ?? 0) - 1; index >= 0; index--) { // ReSharper disable once PossibleNullReferenceException if (!runs[index].UpdateTrailingInfo(trailing)) { return; } } } private static int AddRunReturnVisibleLength(List<TextLineRun> runs, TextLineRun run) { if (run.Length > 0) { runs.Add(run); if (!run.IsEnd) { return run.Length; } } return 0; } public override void Draw(DrawingContext drawingContext, Point origin) { if (drawingContext == null) throw new ArgumentNullException(nameof(drawingContext)); if (_runs.Length == 0) { return; } double width = 0; var y = origin.Y; foreach (var run in _runs) { run.Draw(drawingContext, width + origin.X, y); width += run.Width; } } public override double GetDistanceFromCharacter(int firstIndex, int trailingLength) { double distance = 0; var index = firstIndex + (trailingLength != 0 ? 1 : 0) - FirstIndex; var runs = _runs; foreach (var run in runs) { distance += run.GetDistanceFromCharacter(index); if (index <= run.Length) { break; } index -= run.Length; } return distance; } public override (int firstIndex, int trailingLength) GetCharacterFromDistance(double distance) { var firstIndex = FirstIndex; if (distance < 0) { return (FirstIndex, 0); } (int firstIndex, int trailingLength) result = (FirstIndex, 0); foreach (var run in _runs) { if (!run.IsEnd) { firstIndex += result.trailingLength; result = run.GetCharacterFromDistance(distance); firstIndex += result.firstIndex; } if (distance <= run.Width) { break; } distance -= run.Width; } return (firstIndex, result.trailingLength); } public override Rect GetTextBounds(int firstIndex, int textLength) { if (textLength == 0) throw new ArgumentOutOfRangeException(nameof(textLength)); if (textLength < 0) { firstIndex += textLength; textLength = -textLength; } if (firstIndex < FirstIndex) { textLength += firstIndex - FirstIndex; firstIndex = FirstIndex; } if (firstIndex + textLength > FirstIndex + Length) { textLength = FirstIndex + Length - firstIndex; } var distance = GetDistanceFromCharacter(firstIndex, 0); var distanceToLast = GetDistanceFromCharacter(firstIndex + textLength, 0); return new Rect(distance, 0.0, distanceToLast - distance, Height); } public override IList<TextRun> GetTextRuns() { return _runs.Select(x => x.TextRun).ToArray(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Environment = System.Environment; using StreamWriter = System.IO.StreamWriter; namespace fgit.Running { public static class Shell { private static readonly object FileLocker = new object(); private static readonly object PipeLocker = new object(); public class ExecuteArgs { public string Executable { get; set; } public string Arguments { get; set; } public Dictionary<string, string> EnvVars { get; set; } public string WorkingDirectory { get; set; } } public class ExecuteResult { public string StdOut { get; set; } public string StdErr { get; set; } public int ExitCode { get; set; } public TimeSpan Duration { get; set; } } public interface IExecuteController { void OnStdoutReceived(string data); void OnStderrReceived(string data); void AboutToCleanup(string tempOutputFile, string tempErrorFile); } public class LiveOutput : IExecuteController { public static readonly IExecuteController Instance = new LiveOutput(); public void OnStdoutReceived(string data) { Console.WriteLine(data); } public void OnStderrReceived(string data) { Console.WriteLine(data); } public void AboutToCleanup(string tempOutputFile, string tempErrorFile) { } } public static string ExecuteAndCaptureOutput(NiceIO.NPath filename, string arguments, Dictionary<string, string> envVars = null) { return ExecuteAndCaptureOutput(filename.ToString(), arguments, envVars); } public static string ExecuteAndCaptureOutput (string filename, string arguments, Dictionary<string, string> envVars = null) { ExecuteArgs executeArgs = new ExecuteArgs { Executable = filename, Arguments = arguments, EnvVars = envVars}; return ExecuteAndCaptureOutput(executeArgs); } public static string ExecuteAndCaptureOutput(string filename, string arguments, string workingDirectory, Dictionary<string, string> envVars = null) { ExecuteArgs executeArgs = new ExecuteArgs { Executable = filename, Arguments = arguments, WorkingDirectory = workingDirectory, EnvVars = envVars }; return ExecuteAndCaptureOutput(executeArgs); } public static string ExecuteAndCaptureOutput(ExecuteArgs executeArgs) { var result = Execute(executeArgs); var allConsoleOutput = result.StdErr.Trim() + result.StdOut.Trim(); if (0 != result.ExitCode) { throw new Exception(string.Format( "Process {0} ended with exitcode {1}" + Environment.NewLine + "{2}" + Environment.NewLine, executeArgs.Executable, result.ExitCode, allConsoleOutput)); } return allConsoleOutput; } public static ExecuteResult ExecuteWithLiveOutput(ExecuteArgs executeArgs) { return Execute(executeArgs, LiveOutput.Instance); } public static ExecuteResult Execute(ExecuteArgs executeArgs, IExecuteController controller = null) { using (var p = NewProcess(executeArgs)) { FileStream fOut, fError; string tempOutputFile, tempErrorFile; lock (FileLocker) { tempOutputFile = Path.GetTempFileName(); tempErrorFile = Path.GetTempFileName(); fOut = File.Create(tempOutputFile); fError = File.Create(tempErrorFile); } var stopWatch = new Stopwatch(); stopWatch.Start(); using ( StreamWriter outputWriter = new StreamWriter(fOut, Encoding.UTF8), errorWriter = new StreamWriter(fError, Encoding.UTF8)) { p.OutputDataReceived += (sender, args) => { outputWriter.WriteLine(args.Data); if (controller != null) controller.OnStdoutReceived(args.Data); }; p.ErrorDataReceived += (sender, args) => { errorWriter.WriteLine(args.Data); if (controller != null) controller.OnStderrReceived(args.Data); }; lock (PipeLocker) { p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); } p.WaitForExit(); p.CancelErrorRead(); p.CancelOutputRead(); } string output; string error; lock (FileLocker) { if (controller != null) controller.AboutToCleanup(tempOutputFile, tempErrorFile); output = File.ReadAllText(tempOutputFile, Encoding.UTF8); File.Delete(tempOutputFile); error = File.ReadAllText(tempErrorFile, Encoding.UTF8); File.Delete(tempErrorFile); } stopWatch.Stop(); var result = new ExecuteResult() { ExitCode = p.ExitCode, StdOut = output, StdErr = error, Duration = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds) }; return result; } } public static Process StartProcess(string filename, string arguments) { var p = NewProcess(new ExecuteArgs { Executable = filename, Arguments = arguments}); p.Start(); return p; } static Process NewProcess(ExecuteArgs executeArgs) { var p = new Process { StartInfo = { Arguments = executeArgs.Arguments, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true, FileName = executeArgs.Executable, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, WorkingDirectory = executeArgs.WorkingDirectory, } }; if (executeArgs.EnvVars != null) foreach (var envVar in executeArgs.EnvVars) p.StartInfo.EnvironmentVariables.Add(envVar.Key, envVar.Value); return p; } } }
//! \file ImageGYU.cs //! \date Mon Nov 02 00:38:41 2015 //! \brief ExHIBIT engine image format. // // Copyright (C) 2015-2016 by morkt // // 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.ComponentModel.Composition; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Media.Imaging; using System.Windows.Media; using GameRes.Utility; using GameRes.Compression; using GameRes.Cryptography; using GameRes.Formats.Strings; using System.Collections; namespace GameRes.Formats.ExHibit { internal class GyuMetaData : ImageMetaData { public int Flags; public int CompressionMode; public uint Key; public int DataSize; public int AlphaSize; public int PaletteSize; } [Serializable] public class GyuMap : ResourceScheme { public Dictionary<string, Dictionary<int, uint>> NumericKeys; public Dictionary<string, Dictionary<string, uint>> StringKeys; } [Export(typeof(ImageFormat))] public class GyuFormat : ImageFormat { public override string Tag { get { return "GYU"; } } public override string Description { get { return "ExHIBIT engine image format"; } } public override uint Signature { get { return 0x1A555947; } } // 'GYU' GyuMap DefaultScheme = new GyuMap { NumericKeys = new Dictionary<string, Dictionary<int, uint>>(), StringKeys = new Dictionary<string, Dictionary<string, uint>>(), }; public override ResourceScheme Scheme { get { return DefaultScheme; } set { DefaultScheme = (GyuMap)value; } } public override ImageMetaData ReadMetaData (IBinaryStream stream) { stream.Position = 4; return new GyuMetaData { Flags = stream.ReadUInt16(), CompressionMode = stream.ReadUInt16(), Key = stream.ReadUInt32(), BPP = stream.ReadInt32(), Width = stream.ReadUInt32(), Height = stream.ReadUInt32(), DataSize = stream.ReadInt32(), AlphaSize = stream.ReadInt32(), PaletteSize = stream.ReadInt32(), }; } IDictionary CurrentMap = null; public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var meta = (GyuMetaData)info; if (0 == meta.Key) { object token = null; if (null == CurrentMap) CurrentMap = QueryScheme(); if (CurrentMap != null) { var name = Path.GetFileNameWithoutExtension (meta.FileName); int num; if (int.TryParse (name, out num) && CurrentMap.Contains (num)) token = num; else if (CurrentMap.Contains (name)) token = name; } if (null == token) { CurrentMap = null; throw new UnknownEncryptionScheme ("Unknown image encryption key"); } meta.Key = (uint)CurrentMap[token]; } var reader = new GyuReader (stream.AsStream, meta); reader.Unpack(); return ImageData.CreateFlipped (meta, reader.Format, reader.Palette, reader.Data, reader.Stride); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("GyuFormat.Write not implemented"); } private IDictionary QueryScheme () { var options = Query<GyuOptions> (arcStrings.GYUImageEncrypted); return options.Scheme; } public override ResourceOptions GetDefaultOptions () { return new GyuOptions { Scheme = GetScheme (Properties.Settings.Default.GYUTitle) }; } public override object GetAccessWidget () { var titles = DefaultScheme.NumericKeys.Keys.Concat (DefaultScheme.StringKeys.Keys).OrderBy (x => x); return new GUI.WidgetGYU (titles); } IDictionary GetScheme (string title) { Dictionary<int, uint> num_scheme = null; if (DefaultScheme.NumericKeys.TryGetValue (title, out num_scheme)) return num_scheme; Dictionary<string, uint> str_scheme = null; DefaultScheme.StringKeys.TryGetValue (title, out str_scheme); return str_scheme; } } internal sealed class GyuReader { GyuMetaData m_info; Stream m_input; byte[] m_output; int m_width; int m_height; public PixelFormat Format { get; private set; } public BitmapPalette Palette { get; private set; } public int Stride { get; private set; } public byte[] Data { get { return m_output; } } public GyuReader (Stream input, GyuMetaData info) { m_info = info; m_width = (int)info.Width; m_height = (int)info.Height; Stride = (m_width * info.BPP / 8 + 3) & ~3; m_input = input; if (0 != m_info.AlphaSize) Format = PixelFormats.Bgra32; else if (32 == m_info.BPP) Format = PixelFormats.Bgr32; else if (24 == m_info.BPP) Format = PixelFormats.Bgr24; else if (8 == m_info.BPP) Format = PixelFormats.Indexed8; else throw new NotSupportedException ("Not supported GYU color depth"); if (8 == m_info.BPP && 0 == m_info.PaletteSize) throw new InvalidFormatException(); } public void Unpack () { m_input.Position = 0x24; if (0 != m_info.PaletteSize) Palette = ImageFormat.ReadPalette (m_input, m_info.PaletteSize); var packed = new byte[m_info.DataSize]; if (packed.Length != m_input.Read (packed, 0, packed.Length)) throw new EndOfStreamException(); if (m_info.Key != 0xFFFFFFFF) Deobfuscate (packed, m_info.Key); if (0x0100 == m_info.CompressionMode) { m_output = packed; } else { m_output = new byte[Stride * m_height]; if (0x0800 == m_info.CompressionMode) UnpackGyu (packed); else UnpackLzss (packed); } if (0 != m_info.AlphaSize) ReadAlpha(); } void UnpackLzss (byte[] packed) { using (var mem = new MemoryStream (packed)) using (var lz = new LzssStream (mem)) if (m_output.Length != lz.Read (m_output, 0, m_output.Length)) throw new EndOfStreamException (); } void UnpackGyu (byte[] packed) { using (var mem = new MemoryStream (packed, 4, packed.Length-4)) using (var bits = new MsbBitStream (mem)) { int dst = 0; m_output[dst++] = (byte)mem.ReadByte(); while (dst < m_output.Length) { int b = bits.GetNextBit(); if (-1 == b) throw new EndOfStreamException(); if (1 == b) { m_output[dst++] = (byte)mem.ReadByte(); continue; } int count; int offset; if (1 == bits.GetNextBit()) { count = mem.ReadByte() << 8; count |= mem.ReadByte(); offset = -1 << 13 | count >> 3; count &= 7; if (0 != count) { ++count; } else { count = mem.ReadByte(); if (0 == count) break; } } else { count = 1 + bits.GetBits (2); offset = -1 << 8 | mem.ReadByte(); } Binary.CopyOverlapped (m_output, dst+offset, dst, ++count); dst += count; } } } void ReadAlpha () { int alpha_stride = (m_width + 3) & ~3; Stream alpha_stream; if (m_info.AlphaSize == alpha_stride * m_height) alpha_stream = new StreamRegion (m_input, m_input.Position, true); else alpha_stream = new LzssStream (m_input, LzssMode.Decompress, true); using (alpha_stream) { int src_stride = Stride; int new_stride = m_width * 4; bool extend_alpha = 3 != m_info.Flags; var alpha_line = new byte[alpha_stride]; var pixels = new byte[new_stride * m_height]; for (int y = 0; y < m_height; ++y) { int src = y * src_stride; int dst = y * new_stride; if (alpha_line.Length != alpha_stream.Read (alpha_line, 0, alpha_line.Length)) throw new EndOfStreamException(); for (int x = 0; x < m_width; ++x) { if (8 == m_info.BPP) { var color = Palette.Colors[m_output[src++]]; pixels[dst++] = color.B; pixels[dst++] = color.G; pixels[dst++] = color.R; } else { pixels[dst++] = m_output[src++]; pixels[dst++] = m_output[src++]; pixels[dst++] = m_output[src++]; } int alpha = alpha_line[x]; if (extend_alpha) alpha = alpha >= 0x10 ? 0xFF : alpha * 0x10; pixels[dst++] = (byte)alpha; } } Stride = new_stride; Palette = null; m_output = pixels; } } static void Deobfuscate (byte[] data, uint key) { var mt = new MersenneTwister (key); for (int n = 0; n < 10; ++n) { uint i1 = mt.Rand() % (uint)data.Length; uint i2 = mt.Rand() % (uint)data.Length; var tmp = data[i1]; data[i1] = data[i2]; data[i2] = tmp; } } } public class GyuOptions : ResourceOptions { public IDictionary Scheme; } }
//#define ASTAR_NoTagPenalty using UnityEngine; using Pathfinding.Serialization; namespace Pathfinding { public interface INavmeshHolder { Int3 GetVertex (int i); int GetVertexArrayIndex(int index); void GetTileCoordinates (int tileIndex, out int x, out int z); } /** Node represented by a triangle */ public class TriangleMeshNode : MeshNode { public TriangleMeshNode (AstarPath astar) : base(astar) {} public int v0, v1, v2; protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0]; public static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return _navmeshHolders[(int)graphIndex]; } public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) { if (_navmeshHolders.Length <= graphIndex) { INavmeshHolder[] gg = new INavmeshHolder[graphIndex+1]; for (int i=0;i<_navmeshHolders.Length;i++) gg[i] = _navmeshHolders[i]; _navmeshHolders = gg; } _navmeshHolders[graphIndex] = graph; } public void UpdatePositionFromVertices () { INavmeshHolder g = GetNavmeshHolder(GraphIndex); position = (g.GetVertex(v0) + g.GetVertex(v1) + g.GetVertex(v2)) * 0.333333f; } /** Return a number identifying a vertex. * This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should * not have the same vertex numbers. */ public int GetVertexIndex (int i) { return i == 0 ? v0 : (i == 1 ? v1 : v2); } /** Return a number specifying an index in the source vertex array. * The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant. * This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex. */ public int GetVertexArrayIndex (int i) { return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex (i == 0 ? v0 : (i == 1 ? v1 : v2)); } public override Int3 GetVertex (int i) { return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i)); } public override int GetVertexCount () { return 3; } public override Vector3 ClosestPointOnNode (Vector3 p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); return Pathfinding.Polygon.ClosestPointOnTriangle ((Vector3)g.GetVertex(v0), (Vector3)g.GetVertex(v1), (Vector3)g.GetVertex(v2), p); } public override Vector3 ClosestPointOnNodeXZ (Vector3 _p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); Int3 tp1 = g.GetVertex(v0); Int3 tp2 = g.GetVertex(v1); Int3 tp3 = g.GetVertex(v2); Int3 p = (Int3)_p; int oy = p.y; // Assumes the triangle vertices are laid out in (counter?)clockwise order tp1.y = 0; tp2.y = 0; tp3.y = 0; p.y = 0; if ((long)(tp2.x - tp1.x) * (long)(p.z - tp1.z) - (long)(p.x - tp1.x) * (long)(tp2.z - tp1.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp1, tp2, p)); return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor; } else if ((long)(tp3.x - tp2.x) * (long)(p.z - tp2.z) - (long)(p.x - tp2.x) * (long)(tp3.z - tp2.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp2, tp3, p)); return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor; } else if ((long)(tp1.x - tp3.x) * (long)(p.z - tp3.z) - (long)(p.x - tp3.x) * (long)(tp1.z - tp3.z) > 0) { float f = Mathf.Clamp01 (AstarMath.NearestPointFactor (tp3, tp1, p)); return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor; } else { return _p; } /* * Equivalent to the above, but the above uses manual inlining if (!Polygon.Left (tp1, tp2, p)) { float f = Mathf.Clamp01 (Mathfx.NearestPointFactor (tp1, tp2, p)); return new Vector3(tp1.x + (tp2.x-tp1.x)*f, oy, tp1.z + (tp2.z-tp1.z)*f)*Int3.PrecisionFactor; } else if (!Polygon.Left (tp2, tp3, p)) { float f = Mathf.Clamp01 (Mathfx.NearestPointFactor (tp2, tp3, p)); return new Vector3(tp2.x + (tp3.x-tp2.x)*f, oy, tp2.z + (tp3.z-tp2.z)*f)*Int3.PrecisionFactor; } else if (!Polygon.Left (tp3, tp1, p)) { float f = Mathf.Clamp01 (Mathfx.NearestPointFactor (tp3, tp1, p)); return new Vector3(tp3.x + (tp1.x-tp3.x)*f, oy, tp3.z + (tp1.z-tp3.z)*f)*Int3.PrecisionFactor; } else { return _p; }*/ /* Almost equivalent to the above, but this is slower Vector3 tp1 = (Vector3)g.GetVertex(v0); Vector3 tp2 = (Vector3)g.GetVertex(v1); Vector3 tp3 = (Vector3)g.GetVertex(v2); tp1.y = 0; tp2.y = 0; tp3.y = 0; _p.y = 0; return Pathfinding.Polygon.ClosestPointOnTriangle (tp1,tp2,tp3,_p);*/ } public override bool ContainsPoint (Int3 p) { INavmeshHolder g = GetNavmeshHolder(GraphIndex); Int3 a = g.GetVertex(v0); Int3 b = g.GetVertex(v1); Int3 c = g.GetVertex(v2); if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false; if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false; if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false; return true; //return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p); //return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p); } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { UpdateG (path,pathNode); handler.PushNode (pathNode); if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; PathNode otherPN = handler.GetPathNode (other); if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler); } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; bool flag2 = pathNode.flag2; for (int i=connections.Length-1;i >= 0;i--) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); //Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3 if (pathOther == pathNode.parent) { continue; } uint cost = connectionCosts[i]; if (flag2 || pathOther.flag2) { cost = path.GetConnectionSpecialCost (this,other,cost); } if (pathOther.pathID != handler.PathID) { //Might not be assigned pathOther.node = other; pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = cost; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one than the one already used if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = cost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+cost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = cost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } /** Returns the edge which is shared with \a other. * If no edge is shared, -1 is returned. * The edge is GetVertex(result) - GetVertex((result+1) % GetVertexCount()). * See GetPortal for the exact segment shared. * \note Might return that an edge is shared when the two nodes are in different tiles and adjacent on the XZ plane, but on the Y-axis. * Therefore it is recommended that you only test for neighbours of this node or do additional checking afterwards. */ public int SharedEdge (GraphNode other) { //Debug.Log ("SHARED"); int a, b; GetPortal(other, null, null, false, out a, out b); //Debug.Log ("/SHARED"); return a; } public override bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) { int aIndex, bIndex; return GetPortal (_other,left,right,backwards, out aIndex, out bIndex); } public bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) { aIndex = -1; bIndex = -1; //If the nodes are in different graphs, this function has no idea on how to find a shared edge. if (_other.GraphIndex != GraphIndex) return false; TriangleMeshNode other = _other as TriangleMeshNode; if (!backwards) { int first = -1; int second = -1; int av = GetVertexCount (); int bv = other.GetVertexCount (); /** \todo Maybe optimize with pa=av-1 instead of modulus... */ for (int a=0;a<av;a++) { int va = GetVertexIndex(a); for (int b=0;b<bv;b++) { if (va == other.GetVertexIndex((b+1)%bv) && GetVertexIndex((a+1) % av) == other.GetVertexIndex(b)) { first = a; second = b; a = av; break; } } } aIndex = first; bIndex = second; if (first != -1) { if (left != null) { //All triangles should be clockwise so second is the rightmost vertex (seen from this node) left.Add ((Vector3)GetVertex(first)); right.Add ((Vector3)GetVertex((first+1)%av)); } } else { for ( int i=0;i<connections.Length;i++) { if ( connections[i].GraphIndex != GraphIndex ) { NodeLink3Node mid = connections[i] as NodeLink3Node; if ( mid != null && mid.GetOther (this) == other ) { // We have found a node which is connected through a NodeLink3Node if ( left != null ) { mid.GetPortal ( other, left, right, false ); return true; } } } } return false; } } return true; } public override void SerializeNode (GraphSerializationContext ctx) { base.SerializeNode (ctx); ctx.writer.Write(v0); ctx.writer.Write(v1); ctx.writer.Write(v2); } public override void DeserializeNode (GraphSerializationContext ctx) { base.DeserializeNode (ctx); v0 = ctx.reader.ReadInt32(); v1 = ctx.reader.ReadInt32(); v2 = ctx.reader.ReadInt32(); } } public class ConvexMeshNode : MeshNode { public ConvexMeshNode (AstarPath astar) : base(astar) { indices = new int[0];//\todo Set indices to some reasonable value } private int[] indices; //private new Int3 position; static ConvexMeshNode () { //Should register to a delegate to receive updates whenever graph lists are changed } protected static INavmeshHolder[] navmeshHolders = new INavmeshHolder[0]; protected static INavmeshHolder GetNavmeshHolder (uint graphIndex) { return navmeshHolders[(int)graphIndex]; } /*public override Int3 Position { get { return position; } }*/ public void SetPosition (Int3 p) { position = p; } public int GetVertexIndex (int i) { return indices[i]; } public override Int3 GetVertex (int i) { return GetNavmeshHolder(GraphIndex).GetVertex (GetVertexIndex(i)); } public override int GetVertexCount () { return indices.Length; } public override Vector3 ClosestPointOnNode (Vector3 p) { throw new System.NotImplementedException (); } public override Vector3 ClosestPointOnNodeXZ (Vector3 p) { throw new System.NotImplementedException (); } public override void GetConnections (GraphNodeDelegate del) { if (connections == null) return; for (int i=0;i<connections.Length;i++) del (connections[i]); } public override void Open (Path path, PathNode pathNode, PathHandler handler) { if (connections == null) return; for (int i=0;i<connections.Length;i++) { GraphNode other = connections[i]; if (path.CanTraverse (other)) { PathNode pathOther = handler.GetPathNode (other); if (pathOther.pathID != handler.PathID) { pathOther.parent = pathNode; pathOther.pathID = handler.PathID; pathOther.cost = connectionCosts[i]; pathOther.H = path.CalculateHScore (other); other.UpdateG (path, pathOther); handler.PushNode (pathOther); } else { //If not we can test if the path from this node to the other one is a better one then the one already used uint tmpCost = connectionCosts[i]; if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) { pathOther.cost = tmpCost; pathOther.parent = pathNode; other.UpdateRecursiveG (path, pathOther,handler); //handler.PushNode (pathOther); } else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) { //Or if the path from the other node to this one is better pathNode.parent = pathOther; pathNode.cost = tmpCost; UpdateRecursiveG (path, pathNode,handler); //handler.PushNode (pathNode); } } } } } } /*public class ConvexMeshNode : GraphNode { //Vertices public int v1; public int v2; public int v3; public int GetVertexIndex (int i) { if (i == 0) { return v1; } else if (i == 1) { return v2; } else if (i == 2) { return v3; } else { throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices"); } } public int this[int i] { get { if (i == 0) { return v1; } else if (i == 1) { return v2; } else if (i == 2) { return v3; } else { throw new System.ArgumentOutOfRangeException ("A MeshNode only contains 3 vertices"); } } } public Vector3 ClosestPoint (Vector3 p, Int3[] vertices) { return Polygon.ClosestPointOnTriangle ((Vector3)vertices[v1],(Vector3)vertices[v2],(Vector3)vertices[v3],p); } }*/ }
// // 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 Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure.Common.Internals; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// The properties for the HDInsight linkedService. /// </summary> public partial class HDInsightOnDemandLinkedService : LinkedServiceProperties { private IList<string> _additionalLinkedServiceNames; /// <summary> /// Optional. Specify additional Azure storage accounts that need to be /// accessible from the cluster. /// </summary> public IList<string> AdditionalLinkedServiceNames { get { return this._additionalLinkedServiceNames; } set { this._additionalLinkedServiceNames = value; } } private int _clusterSize; /// <summary> /// Required. HDInsight cluster size. /// </summary> public int ClusterSize { get { return this._clusterSize; } set { this._clusterSize = value; } } private IDictionary<string, string> _coreConfiguration; /// <summary> /// Optional. Allows user to override default values for core /// configuration. /// </summary> public IDictionary<string, string> CoreConfiguration { get { return this._coreConfiguration; } set { this._coreConfiguration = value; } } private IDictionary<string, string> _hBaseConfiguration; /// <summary> /// Optional. Allows user to override default values for HBase /// configuration. /// </summary> public IDictionary<string, string> HBaseConfiguration { get { return this._hBaseConfiguration; } set { this._hBaseConfiguration = value; } } private IDictionary<string, string> _hdfsConfiguration; /// <summary> /// Optional. Allows user to override default values for Hdfs /// configuration. /// </summary> public IDictionary<string, string> HdfsConfiguration { get { return this._hdfsConfiguration; } set { this._hdfsConfiguration = value; } } private IDictionary<string, string> _hiveConfiguration; /// <summary> /// Optional. Allows user to override default values for HIVE /// configuration. /// </summary> public IDictionary<string, string> HiveConfiguration { get { return this._hiveConfiguration; } set { this._hiveConfiguration = value; } } private string _hiveCustomLibrariesContainer; /// <summary> /// Optional. The name of the blob container that contains custom jar /// files for HIVE consumption. /// </summary> public string HiveCustomLibrariesContainer { get { return this._hiveCustomLibrariesContainer; } set { this._hiveCustomLibrariesContainer = value; } } private string _linkedServiceName; /// <summary> /// Required. Storage service name. /// </summary> public string LinkedServiceName { get { return this._linkedServiceName; } set { this._linkedServiceName = value; } } private IDictionary<string, string> _mapReduceConfiguration; /// <summary> /// Optional. Allows user to override default values for mapreduce /// configuration. /// </summary> public IDictionary<string, string> MapReduceConfiguration { get { return this._mapReduceConfiguration; } set { this._mapReduceConfiguration = value; } } private IDictionary<string, string> _oozieConfiguration; /// <summary> /// Optional. Allows user to override default values for oozie /// configuration. /// </summary> public IDictionary<string, string> OozieConfiguration { get { return this._oozieConfiguration; } set { this._oozieConfiguration = value; } } private IDictionary<string, string> _stormConfiguration; /// <summary> /// Optional. Allows user to override default values for Storm /// configuration. /// </summary> public IDictionary<string, string> StormConfiguration { get { return this._stormConfiguration; } set { this._stormConfiguration = value; } } private TimeSpan _timeToLive; /// <summary> /// Required. Time to live. /// </summary> public TimeSpan TimeToLive { get { return this._timeToLive; } set { this._timeToLive = value; } } private string _version; /// <summary> /// Optional. HDInsight version. /// </summary> public string Version { get { return this._version; } set { this._version = value; } } private IDictionary<string, string> _yarnConfiguration; /// <summary> /// Optional. Allows user to override default values for YARN /// configuration. /// </summary> public IDictionary<string, string> YarnConfiguration { get { return this._yarnConfiguration; } set { this._yarnConfiguration = value; } } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class. /// </summary> public HDInsightOnDemandLinkedService() { this.AdditionalLinkedServiceNames = new LazyList<string>(); this.CoreConfiguration = new LazyDictionary<string, string>(); this.HBaseConfiguration = new LazyDictionary<string, string>(); this.HdfsConfiguration = new LazyDictionary<string, string>(); this.HiveConfiguration = new LazyDictionary<string, string>(); this.MapReduceConfiguration = new LazyDictionary<string, string>(); this.OozieConfiguration = new LazyDictionary<string, string>(); this.StormConfiguration = new LazyDictionary<string, string>(); this.YarnConfiguration = new LazyDictionary<string, string>(); } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class with required arguments. /// </summary> public HDInsightOnDemandLinkedService(int clusterSize, TimeSpan timeToLive, string linkedServiceName) : this() { if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } this.ClusterSize = clusterSize; this.TimeToLive = timeToLive; this.LinkedServiceName = linkedServiceName; } } }
/*! * CSharpVerbalExpressions v0.1 * https://github.com/VerbalExpressions/CSharpVerbalExpressions * * @psoholt * * Date: 2013-07-26 * * Additions and Refactoring * @alexpeta * * Date: 2013-08-06 */ using System; using System.Text; using System.Linq; using System.Text.RegularExpressions; namespace CSharpVerbalExpressions { public class VerbalExpressions { #region Statics /// <summary> /// Returns a default instance of VerbalExpressions /// having the Multiline option enabled /// </summary> public static VerbalExpressions DefaultExpression { get { return new VerbalExpressions(); } } #endregion Statics #region Private Members private readonly RegexCache regexCache = new RegexCache(); private readonly StringBuilder _prefixes = new StringBuilder(); private readonly StringBuilder _source = new StringBuilder(); private readonly StringBuilder _suffixes = new StringBuilder(); private RegexOptions _modifiers = RegexOptions.Multiline; #endregion Private Members #region Private Properties private string RegexString { get { return new StringBuilder().Append(_prefixes).Append(_source).Append(_suffixes).ToString();} } private Regex PatternRegex { get { return regexCache.Get(this.RegexString, _modifiers); } } #endregion Private Properties #region Public Methods #region Helpers public string Sanitize(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } return Regex.Escape(value); } public bool Test(string toTest) { return IsMatch(toTest); } public bool IsMatch(string toTest) { return PatternRegex.IsMatch(toTest); } public Regex ToRegex() { return PatternRegex; } public override string ToString() { return PatternRegex.ToString(); } public string Capture(string toTest, string groupName) { if (!Test(toTest)) return null; var match = PatternRegex.Match(toTest); return match.Groups[groupName].Value; } #endregion Helpers #region Expression Modifiers public VerbalExpressions Add(CommonRegex commonRegex) { return Add(commonRegex.Name, false); } public VerbalExpressions Add(string value, bool sanitize = true) { if (value == null) throw new ArgumentNullException("value must be provided"); value = sanitize ? Sanitize(value) : value; _source.Append(value); return this; } public VerbalExpressions StartOfLine(bool enable = true) { _prefixes.Append(enable ? "^" : String.Empty); return this; } public VerbalExpressions EndOfLine(bool enable = true) { _suffixes.Append(enable ? "$" : String.Empty); return this; } public VerbalExpressions Then(string value, bool sanitize = true) { var sanitizedValue = sanitize ? Sanitize(value) : value; value = string.Format("({0})", sanitizedValue); return Add(value, false); } public VerbalExpressions Then(CommonRegex commonRegex) { return Then(commonRegex.Name, false); } public VerbalExpressions Find(string value) { return Then(value); } public VerbalExpressions Maybe(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("({0})?", value); return Add(value, false); } public VerbalExpressions Maybe(CommonRegex commonRegex) { return Maybe(commonRegex.Name, sanitize: false); } public VerbalExpressions Anything() { return Add("(.*)", false); } public VerbalExpressions AnythingBut(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("([^{0}]*)", value); return Add(value, false); } public VerbalExpressions Something() { return Add("(.+)", false); } public VerbalExpressions SomethingBut(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("([^" + value + "]+)"); return Add(value, false); } public VerbalExpressions Replace(string value) { string whereToReplace = PatternRegex.ToString(); if (whereToReplace.Length != 0) { _source.Replace(whereToReplace, value); } return this; } public VerbalExpressions LineBreak() { return Add(@"(\n|(\r\n))", false); } public VerbalExpressions Br() { return LineBreak(); } public VerbalExpressions Tab() { return Add(@"\t"); } public VerbalExpressions Word() { return Add(@"\w+", false); } public VerbalExpressions AnyOf(string value, bool sanitize = true) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } value = sanitize ? Sanitize(value) : value; value = string.Format("[{0}]", value); return Add(value, false); } public VerbalExpressions Any(string value) { return AnyOf(value); } public VerbalExpressions Range(params object[] arguments) { if (object.ReferenceEquals(arguments, null)) { throw new ArgumentNullException("arguments"); } if (arguments.Length == 1) { throw new ArgumentOutOfRangeException("arguments"); } string[] sanitizedStrings = arguments.Select(argument => { if (object.ReferenceEquals(argument, null)) { return string.Empty; } string casted = argument.ToString(); if (string.IsNullOrEmpty(casted)) { return string.Empty; } else { return Sanitize(casted); } }) .Where(sanitizedString => !string.IsNullOrEmpty(sanitizedString)) .OrderBy(s => s) .ToArray(); if (sanitizedStrings.Length > 3) { throw new ArgumentOutOfRangeException("arguments"); } if (!sanitizedStrings.Any()) { return this; } bool hasOddNumberOfParams = (sanitizedStrings.Length % 2) > 0; StringBuilder sb = new StringBuilder("["); for (int _from = 0; _from < sanitizedStrings.Length; _from += 2) { int _to = _from + 1; if (sanitizedStrings.Length <= _to) { break; } sb.AppendFormat("{0}-{1}", sanitizedStrings[_from], sanitizedStrings[_to]); } sb.Append("]"); if (hasOddNumberOfParams) { sb.AppendFormat("|{0}", sanitizedStrings.Last()); } return Add(sb.ToString(), false); } public VerbalExpressions Multiple(string value, bool sanitize = true) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } value = sanitize ? this.Sanitize(value) : value; value = string.Format(@"({0})+", value); return Add(value, false); } public VerbalExpressions Or(CommonRegex commonRegex) { return Or(commonRegex.Name, false); } public VerbalExpressions Or(string value, bool sanitize = true) { _prefixes.Append("("); _suffixes.Insert(0, ")"); _source.Append(")|("); return Add(value, sanitize); } public VerbalExpressions BeginCapture() { return Add("(", false); } public VerbalExpressions BeginCapture(string groupName) { return Add("(?<", false).Add(groupName, true).Add(">", false); } public VerbalExpressions EndCapture() { return Add(")", false); } public VerbalExpressions RepeatPrevious(int n) { return Add("{" + n + "}", false); } public VerbalExpressions RepeatPrevious(int n, int m) { return Add("{" + n + "," + m + "}", false); } #endregion Expression Modifiers #region Expression Options Modifiers public VerbalExpressions AddModifier(char modifier) { switch (modifier) { case 'i': _modifiers |= RegexOptions.IgnoreCase; break; case 'x': _modifiers |= RegexOptions.IgnorePatternWhitespace; break; case 'm': _modifiers |= RegexOptions.Multiline; break; case 's': _modifiers |= RegexOptions.Singleline; break; } return this; } public VerbalExpressions RemoveModifier(char modifier) { switch (modifier) { case 'i': _modifiers &= ~RegexOptions.IgnoreCase; break; case 'x': _modifiers &= ~RegexOptions.IgnorePatternWhitespace; break; case 'm': _modifiers &= ~RegexOptions.Multiline; break; case 's': _modifiers &= ~RegexOptions.Singleline; break; } return this; } public VerbalExpressions WithAnyCase(bool enable = true) { if (enable) { AddModifier('i'); } else { RemoveModifier('i'); } return this; } public VerbalExpressions UseOneLineSearchOption(bool enable) { if (enable) { RemoveModifier('m'); } else { AddModifier('m'); } return this; } public VerbalExpressions WithOptions(RegexOptions options) { this._modifiers = options; return this; } #endregion Expression Options Modifiers #endregion Public Methods } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Transactions { using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Transactions; /// <summary> /// Grid cache transaction implementation. /// </summary> internal sealed class TransactionImpl : IDisposable { /** Metadatas. */ private object[] _metas; /** Unique transaction ID.*/ private readonly long _id; /** Cache. */ private readonly TransactionsImpl _txs; /** TX concurrency. */ private readonly TransactionConcurrency _concurrency; /** TX isolation. */ private readonly TransactionIsolation _isolation; /** Timeout. */ private readonly TimeSpan _timeout; /** TX label. */ private readonly string _label; /** Start time. */ private readonly DateTime _startTime; /** Owning thread ID. */ private readonly int _threadId; /** Originating node ID. */ private readonly Guid _nodeId; /** State holder. */ private StateHolder _state; // ReSharper disable once InconsistentNaming /** Transaction for this thread. */ [ThreadStatic] private static TransactionImpl THREAD_TX; /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> /// <param name="txs">Transactions.</param> /// <param name="concurrency">TX concurrency.</param> /// <param name="isolation">TX isolation.</param> /// <param name="timeout">Timeout.</param> /// <param name="label">TX label.</param> /// <param name="nodeId">The originating node identifier.</param> /// <param name="bindToThread">Bind transaction to current thread or not.</param> public TransactionImpl(long id, TransactionsImpl txs, TransactionConcurrency concurrency, TransactionIsolation isolation, TimeSpan timeout, string label, Guid nodeId, bool bindToThread = true) { _id = id; _txs = txs; _concurrency = concurrency; _isolation = isolation; _timeout = timeout; _label = label; _nodeId = nodeId; _startTime = DateTime.Now; _threadId = Thread.CurrentThread.ManagedThreadId; if (bindToThread) THREAD_TX = this; } /// <summary> /// Transaction assigned to this thread. /// </summary> public static Transaction Current { get { var tx = THREAD_TX; if (tx == null) return null; if (tx.IsClosed) { THREAD_TX = null; return null; } return new Transaction(tx); } } /// <summary> /// Executes prepare step of the two phase commit. /// </summary> public void Prepare() { lock (this) { ThrowIfClosed(); _txs.TxPrepare(this); } } /// <summary> /// Commits this tx and closes it. /// </summary> public void Commit() { lock (this) { ThrowIfClosed(); _state = new StateHolder(_txs.TxCommit(this)); } } /// <summary> /// Rolls this tx back and closes it. /// </summary> public void Rollback() { lock (this) { ThrowIfClosed(); _state = new StateHolder(_txs.TxRollback(this)); } } /// <summary> /// Sets the rollback only flag. /// </summary> public bool SetRollbackOnly() { lock (this) { ThrowIfClosed(); return _txs.TxSetRollbackOnly(this); } } /// <summary> /// Gets a value indicating whether this instance is rollback only. /// </summary> public bool IsRollbackOnly { get { lock (this) { var state0 = _state == null ? State : _state.State; return state0 == TransactionState.MarkedRollback || state0 == TransactionState.RollingBack || state0 == TransactionState.RolledBack; } } } /// <summary> /// Gets the state. /// </summary> public TransactionState State { get { lock (this) { return _state != null ? _state.State : _txs.TxState(this); } } } /// <summary> /// Gets the isolation. /// </summary> public TransactionIsolation Isolation { get { return _isolation; } } /// <summary> /// Gets the concurrency. /// </summary> public TransactionConcurrency Concurrency { get { return _concurrency; } } /// <summary> /// Gets the timeout. /// </summary> public TimeSpan Timeout { get { return _timeout; } } /// <summary> /// Label of current transaction. /// </summary> public string Label { get { return _label; } } /// <summary> /// Gets the start time. /// </summary> public DateTime StartTime { get { return _startTime; } } /// <summary> /// Gets the node identifier. /// </summary> public Guid NodeId { get { return _nodeId; } } /// <summary> /// Gets the thread identifier. /// </summary> public long ThreadId { get { return _threadId; } } /// <summary> /// Adds a new metadata. /// </summary> public void AddMeta<TV>(string name, TV val) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { int putIdx = -1; for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) { _metas[i + 1] = val; return; } if (_metas[i] == null && putIdx == -1) // Preserve empty space index. putIdx = i; } // No meta with the given name found. if (putIdx == -1) { // Extend array. putIdx = _metas.Length; object[] metas0 = new object[putIdx + 2]; Array.Copy(_metas, metas0, putIdx); _metas = metas0; } _metas[putIdx] = name; _metas[putIdx + 1] = val; } else _metas = new object[] { name, val }; } } /// <summary> /// Gets metadata by name. /// </summary> public TV Meta<TV>(string name) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) return (TV)_metas[i + 1]; } } return default(TV); } } /// <summary> /// Removes metadata by name. /// </summary> public TV RemoveMeta<TV>(string name) { if (name == null) throw new ArgumentException("Meta name cannot be null."); lock (this) { if (_metas != null) { for (int i = 0; i < _metas.Length; i += 2) { if (name.Equals(_metas[i])) { TV val = (TV)_metas[i + 1]; _metas[i] = null; _metas[i + 1] = null; return val; } } } return default(TV); } } /// <summary> /// Commits tx in async mode. /// </summary> internal Task CommitAsync() { lock (this) { ThrowIfClosed(); return CloseWhenComplete(_txs.CommitAsync(this)); } } /// <summary> /// Rolls tx back in async mode. /// </summary> internal Task RollbackAsync() { lock (this) { ThrowIfClosed(); return CloseWhenComplete(_txs.RollbackAsync(this)); } } /// <summary> /// Transaction ID. /// </summary> internal long Id { get { return _id; } } /** <inheritdoc /> */ public void Dispose() { try { Close(); } finally { GC.SuppressFinalize(this); } } /// <summary> /// Gets a value indicating whether this transaction is closed. /// </summary> private bool IsClosed { get { return _state != null; } } /// <summary> /// Gets the closed exception. /// </summary> private InvalidOperationException GetClosedException() { return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Transaction {0} is closed, state is {1}", Id, State)); } /// <summary> /// Creates a task via provided factory if IsClosed is false; otherwise, return a task with an error. /// </summary> internal Task GetTask(Func<Task> operationFactory) { lock (this) { return IsClosed ? GetExceptionTask() : operationFactory(); } } /// <summary> /// Gets the task that throws an exception. /// </summary> private Task GetExceptionTask() { var tcs = new TaskCompletionSource<object>(); tcs.SetException(GetClosedException()); return tcs.Task; } /// <summary> /// Closes the transaction and releases unmanaged resources. /// </summary> private void Close() { lock (this) { _state = _state ?? new StateHolder((TransactionState) _txs.TxClose(this)); } } /// <summary> /// Throws and exception if transaction is closed. /// </summary> private void ThrowIfClosed() { if (IsClosed) throw GetClosedException(); } /// <summary> /// Closes this transaction upon task completion. /// </summary> private Task CloseWhenComplete(Task task) { return task.ContWith(x => Close()); } /** <inheritdoc /> */ ~TransactionImpl() { Dispose(); } /// <summary> /// State holder. /// </summary> private class StateHolder { /** Current state. */ private readonly TransactionState _state; /// <summary> /// Constructor. /// </summary> /// <param name="state">State.</param> public StateHolder(TransactionState state) { _state = state; } /// <summary> /// Current state. /// </summary> public TransactionState State { get { return _state; } } } } }
// Python Tools for Visual Studio // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Windows; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.PythonTools.Profiling { /// <summary> /// Factory for creating our editor object. Extends from the IVsEditoryFactory interface /// </summary> [Guid(GuidList.guidEditorFactoryString)] sealed class ProfilingSessionEditorFactory : IVsEditorFactory, IDisposable { private readonly PythonProfilingPackage _editorPackage; private ServiceProvider _vsServiceProvider; public ProfilingSessionEditorFactory(PythonProfilingPackage package) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} constructor", this.ToString())); this._editorPackage = package; } /// <summary> /// Since we create a ServiceProvider which implements IDisposable we /// also need to implement IDisposable to make sure that the ServiceProvider's /// Dispose method gets called. /// </summary> public void Dispose() { if (_vsServiceProvider != null) { _vsServiceProvider.Dispose(); } } #region IVsEditorFactory Members /// <summary> /// Used for initialization of the editor in the environment /// </summary> /// <param name="psp">pointer to the service provider. Can be used to obtain instances of other interfaces /// </param> /// <returns></returns> public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { _vsServiceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } public object GetService(Type serviceType) { return _vsServiceProvider.GetService(serviceType); } // This method is called by the Environment (inside IVsUIShellOpenDocument:: // OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a // PHYSICAL view. A LOGICAL view identifies the purpose of the view that is // desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a // view appropriate for text view manipulation as by navigating to a find // result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type // of view implementation that an IVsEditorFactory can create. // // NOTE: Physical views are identified by a string of your choice with the // one constraint that the default/primary physical view for an editor // *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL). // // NOTE: It is essential that the implementation of MapLogicalView properly // validates that the LogicalView desired is actually supported by the editor. // If an unsupported LogicalView is requested then E_NOTIMPL must be returned. // // NOTE: The special Logical Views supported by an Editor Factory must also // be registered in the local registry hive. LOGVIEWID_Primary is implicitly // supported by all editor types and does not need to be registered. // For example, an editor that supports a ViewCode/ViewDesigner scenario // might register something like the following: // HKLM\Software\Microsoft\VisualStudio\<version>\Editors\ // {...guidEditor...}\ // LogicalViews\ // {...LOGVIEWID_TextView...} = s '' // {...LOGVIEWID_Code...} = s '' // {...LOGVIEWID_Debugging...} = s '' // {...LOGVIEWID_Designer...} = s 'Form' // public int MapLogicalView(ref Guid rguidLogicalView, out string pbstrPhysicalView) { pbstrPhysicalView = null; // initialize out parameter // we support only a single physical view if (VSConstants.LOGVIEWID_Primary == rguidLogicalView) return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView else return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values } public int Close() { return VSConstants.S_OK; } /// <summary> /// Used by the editor factory to create an editor instance. the environment first determines the /// editor factory with the highest priority for opening the file and then calls /// IVsEditorFactory.CreateEditorInstance. If the environment is unable to instantiate the document data /// in that editor, it will find the editor with the next highest priority and attempt to so that same /// thing. /// NOTE: The priority of our editor is 32 as mentioned in the attributes on the package class. /// /// Since our editor supports opening only a single view for an instance of the document data, if we /// are requested to open document data that is already instantiated in another editor, or even our /// editor, we return a value VS_E_INCOMPATIBLEDOCDATA. /// </summary> /// <param name="grfCreateDoc">Flags determining when to create the editor. Only open and silent flags /// are valid /// </param> /// <param name="pszMkDocument">path to the file to be opened</param> /// <param name="pszPhysicalView">name of the physical view</param> /// <param name="pvHier">pointer to the IVsHierarchy interface</param> /// <param name="itemid">Item identifier of this editor instance</param> /// <param name="punkDocDataExisting">This parameter is used to determine if a document buffer /// (DocData object) has already been created /// </param> /// <param name="ppunkDocView">Pointer to the IUnknown interface for the DocView object</param> /// <param name="ppunkDocData">Pointer to the IUnknown interface for the DocData object</param> /// <param name="pbstrEditorCaption">Caption mentioned by the editor for the doc window</param> /// <param name="pguidCmdUI">the Command UI Guid. Any UI element that is visible in the editor has /// to use this GUID. This is specified in the .vsct file /// </param> /// <param name="pgrfCDW">Flags for CreateDocumentWindow</param> /// <returns></returns> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public int CreateEditorInstance( uint grfCreateDoc, string pszMkDocument, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, System.IntPtr punkDocDataExisting, out System.IntPtr ppunkDocView, out System.IntPtr ppunkDocData, out string pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} CreateEditorInstace()", this.ToString())); // Initialize to null ppunkDocView = IntPtr.Zero; ppunkDocData = IntPtr.Zero; pguidCmdUI = GuidList.guidEditorFactory; pgrfCDW = 0; pbstrEditorCaption = null; // Validate inputs if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } if (punkDocDataExisting != IntPtr.Zero) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } // Create the Document (editor) var perfWin = _editorPackage.ShowPerformanceExplorer(); ProfilingTarget target; try { using (var fs = new FileStream(pszMkDocument, FileMode.Open)) { target = (ProfilingTarget)ProfilingTarget.Serializer.Deserialize(fs); fs.Close(); } } catch (IOException e) { MessageBox.Show(Strings.FailedToOpenPerformanceSessionFile.FormatUI(pszMkDocument, e.Message), Strings.ProductTitle); return VSConstants.E_FAIL; } catch (InvalidOperationException e) { MessageBox.Show(Strings.FailedToReadPerformanceSession.FormatUI(pszMkDocument, e.Message), Strings.ProductTitle); return VSConstants.E_FAIL; } perfWin.Sessions.OpenTarget( target, pszMkDocument ); pbstrEditorCaption = ""; return VSConstants.S_OK; } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using Humanizer; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Objects; using osuTK.Input; namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components { public class PathControlPointVisualiser : CompositeDrawable, IKeyBindingHandler<PlatformAction>, IHasContextMenu { internal readonly Container<PathControlPointPiece> Pieces; private readonly Container<PathControlPointConnectionPiece> connections; private readonly Slider slider; private readonly bool allowSelection; private InputManager inputManager; private IBindableList<PathControlPoint> controlPoints; public Action<List<PathControlPoint>> RemoveControlPointsRequested; public PathControlPointVisualiser(Slider slider, bool allowSelection) { this.slider = slider; this.allowSelection = allowSelection; RelativeSizeAxes = Axes.Both; InternalChildren = new Drawable[] { connections = new Container<PathControlPointConnectionPiece> { RelativeSizeAxes = Axes.Both }, Pieces = new Container<PathControlPointPiece> { RelativeSizeAxes = Axes.Both } }; } protected override void LoadComplete() { base.LoadComplete(); inputManager = GetContainingInputManager(); controlPoints = slider.Path.ControlPoints.GetBoundCopy(); controlPoints.ItemsAdded += addControlPoints; controlPoints.ItemsRemoved += removeControlPoints; addControlPoints(controlPoints); } private void addControlPoints(IEnumerable<PathControlPoint> controlPoints) { foreach (var point in controlPoints) { Pieces.Add(new PathControlPointPiece(slider, point).With(d => { if (allowSelection) d.RequestSelection = selectPiece; })); connections.Add(new PathControlPointConnectionPiece(slider, point)); } } private void removeControlPoints(IEnumerable<PathControlPoint> controlPoints) { foreach (var point in controlPoints) { Pieces.RemoveAll(p => p.ControlPoint == point); connections.RemoveAll(c => c.ControlPoint == point); } } protected override bool OnClick(ClickEvent e) { foreach (var piece in Pieces) { piece.IsSelected.Value = false; } return false; } public bool OnPressed(PlatformAction action) { switch (action.ActionMethod) { case PlatformActionMethod.Delete: return deleteSelected(); } return false; } public void OnReleased(PlatformAction action) { } private void selectPiece(PathControlPointPiece piece, MouseButtonEvent e) { if (e.Button == MouseButton.Left && inputManager.CurrentState.Keyboard.ControlPressed) piece.IsSelected.Toggle(); else { foreach (var p in Pieces) p.IsSelected.Value = p == piece; } } private bool deleteSelected() { List<PathControlPoint> toRemove = Pieces.Where(p => p.IsSelected.Value).Select(p => p.ControlPoint).ToList(); // Ensure that there are any points to be deleted if (toRemove.Count == 0) return false; RemoveControlPointsRequested?.Invoke(toRemove); // Since pieces are re-used, they will not point to the deleted control points while remaining selected foreach (var piece in Pieces) piece.IsSelected.Value = false; return true; } public MenuItem[] ContextMenuItems { get { if (!Pieces.Any(p => p.IsHovered)) return null; var selectedPieces = Pieces.Where(p => p.IsSelected.Value).ToList(); int count = selectedPieces.Count; if (count == 0) return null; List<MenuItem> items = new List<MenuItem>(); if (!selectedPieces.Contains(Pieces[0])) items.Add(createMenuItemForPathType(null)); // todo: hide/disable items which aren't valid for selected points items.Add(createMenuItemForPathType(PathType.Linear)); items.Add(createMenuItemForPathType(PathType.PerfectCurve)); items.Add(createMenuItemForPathType(PathType.Bezier)); items.Add(createMenuItemForPathType(PathType.Catmull)); return new MenuItem[] { new OsuMenuItem($"Delete {"control point".ToQuantity(count, count > 1 ? ShowQuantityAs.Numeric : ShowQuantityAs.None)}", MenuItemType.Destructive, () => deleteSelected()), new OsuMenuItem("Curve type") { Items = items } }; } } private MenuItem createMenuItemForPathType(PathType? type) { int totalCount = Pieces.Count(p => p.IsSelected.Value); int countOfState = Pieces.Where(p => p.IsSelected.Value).Count(p => p.ControlPoint.Type.Value == type); var item = new PathTypeMenuItem(type, () => { foreach (var p in Pieces.Where(p => p.IsSelected.Value)) p.ControlPoint.Type.Value = type; }); if (countOfState == totalCount) item.State.Value = TernaryState.True; else if (countOfState > 0) item.State.Value = TernaryState.Indeterminate; else item.State.Value = TernaryState.False; return item; } private class PathTypeMenuItem : TernaryStateMenuItem { public PathTypeMenuItem(PathType? type, Action action) : base(type == null ? "Inherit" : type.ToString().Humanize(), changeState, MenuItemType.Standard, _ => action?.Invoke()) { } private static TernaryState changeState(TernaryState state) => TernaryState.True; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using NGraphics.Custom.Codes; using NGraphics.Custom.Interfaces; using NGraphics.Custom.Models; using NGraphics.Custom.Models.Brushes; using NGraphics.Custom.Models.Elements; using NGraphics.Custom.Models.Transforms; using Group = NGraphics.Custom.Models.Elements.Group; using Path = NGraphics.Custom.Models.Elements.Path; namespace NGraphics.Custom.Parsers { public class SvgReader { private readonly IStylesParser _stylesParser; private readonly IValuesParser _valuesParser; // readonly XNamespace ns; public SvgReader(TextReader reader, IStylesParser stylesParser, IValuesParser valuesParser) { _stylesParser = stylesParser; _valuesParser = valuesParser; Read(XDocument.Load(reader)); } private static readonly char[] WS = {' ', '\t', '\n', '\r'}; private readonly Dictionary<string, XElement> defs = new Dictionary<string, XElement>(); public Graphic Graphic { get; private set; } private void Read(XDocument doc) { var svg = doc.Root; var ns = svg.Name.Namespace; // // Find the defs (gradients) // foreach (var d in svg.Descendants()) { var idA = d.Attribute("id"); if (idA != null) { defs[ReadString(idA).Trim()] = d; } } // // Get the dimensions // var widthA = svg.Attribute("width"); var heightA = svg.Attribute("height"); var width = _valuesParser.ReadNumber(widthA); var height = _valuesParser.ReadNumber(heightA); var size = new Size(width, height); var viewBox = new Rect(size); var viewBoxA = svg.Attribute("viewBox") ?? svg.Attribute("viewPort"); if (viewBoxA != null) { viewBox = ReadRectangle(viewBoxA.Value); } if (widthA != null && widthA.Value.Contains("%")) { size.Width *= viewBox.Width; } if (heightA != null && heightA.Value.Contains("%")) { size.Height *= viewBox.Height; } // // Add the elements // Graphic = new Graphic(size, viewBox); AddElements(Graphic.Children, svg.Elements(), null, null); } private void AddElements(IList<IDrawable> list, IEnumerable<XElement> es, Pen inheritPen, BaseBrush inheritBaseBrush) { foreach (var e in es) AddElement(list, e, inheritPen, inheritBaseBrush); } private void AddElement(IList<IDrawable> list, XElement e, Pen inheritPen, BaseBrush inheritBaseBrush) { Element element = null; var styleAttributedDictionary = e.Attributes().ToDictionary(k => k.Name.LocalName, v => v.Value); var pen = _stylesParser.GetPen(styleAttributedDictionary); var baseBrush = _stylesParser.GetBrush(styleAttributedDictionary,defs, pen); var style = ReadString(e.Attribute("style")); if (!string.IsNullOrWhiteSpace(style)) { ApplyStyle(style, ref pen, ref baseBrush); } pen = pen ?? inheritPen; baseBrush = baseBrush ?? inheritBaseBrush; //var id = ReadString (e.Attribute ("id")); // // Elements // switch (e.Name.LocalName) { case "text": { var x = _valuesParser.ReadNumber(e.Attribute("x")); var y = _valuesParser.ReadNumber(e.Attribute("y")); var text = e.Value.Trim(); var font = new Font(); element = new Text(text, new Rect(new Point(x, y), new Size(double.MaxValue, double.MaxValue)), font, TextAlignment.Left, pen, baseBrush); } break; case "rect": { var x = _valuesParser.ReadNumber(e.Attribute("x")); var y = _valuesParser.ReadNumber(e.Attribute("y")); var width = _valuesParser.ReadNumber(e.Attribute("width")); var height = _valuesParser.ReadNumber(e.Attribute("height")); element = new Rectangle(new Point(x, y), new Size(width, height), pen, baseBrush); } break; case "ellipse": { var cx = _valuesParser.ReadNumber(e.Attribute("cx")); var cy = _valuesParser.ReadNumber(e.Attribute("cy")); var rx = _valuesParser.ReadNumber(e.Attribute("rx")); var ry = _valuesParser.ReadNumber(e.Attribute("ry")); element = new Ellipse(new Point(cx - rx, cy - ry), new Size(2*rx, 2*ry), pen, baseBrush); } break; case "circle": { var cx = _valuesParser.ReadNumber(e.Attribute("cx")); var cy = _valuesParser.ReadNumber(e.Attribute("cy")); var rr = _valuesParser.ReadNumber(e.Attribute("r")); element = new Ellipse(new Point(cx - rr, cy - rr), new Size(2*rr, 2*rr), pen, baseBrush); } break; case "path": { var dA = e.Attribute("d"); if (dA != null && !string.IsNullOrWhiteSpace(dA.Value)) { var p = new Path(pen, baseBrush); SvgPathParser.Parse(p, dA.Value); element = p; } } break; case "g": { var g = new Group(); AddElements(g.Children, e.Elements(), pen, baseBrush); element = g; } break; case "use": { var href = ReadString(e.Attributes().FirstOrDefault(x => x.Name.LocalName == "href")); if (!string.IsNullOrWhiteSpace(href)) { XElement useE; if (defs.TryGetValue(href.Trim().Replace("#", ""), out useE)) { var useList = new List<IDrawable>(); AddElement(useList, useE, pen, baseBrush); element = useList.OfType<Element>().FirstOrDefault(); } } } break; case "title": Graphic.Title = ReadString(e); break; case "description": Graphic.Description = ReadString(e); break; case "defs": // Already read in earlier pass break; case "namedview": case "metadata": case "SVGTestCase": case "switch": break; default: throw new NotSupportedException("SVG element \"" + e.Name.LocalName + "\" is not supported"); } if (element != null) { element.Transform = ReadTransform(ReadString(e.Attribute("transform"))); list.Add(element); } } private void ApplyStyle(string style, ref Pen pen, ref BaseBrush baseBrush) { var stylesDictionary = _stylesParser.ParseStyleValues(style); pen = _stylesParser.GetPen(stylesDictionary); baseBrush = _stylesParser.GetBrush(stylesDictionary, defs, pen); } Transform ReadTransform(string raw) { if (string.IsNullOrWhiteSpace(raw)) return Transform.Identity; var s = raw.Trim(); var calls = s.Split(new[] { ')' }, StringSplitOptions.RemoveEmptyEntries); var t = Transform.Identity; foreach (var c in calls) { var args = c.Split(new[] { '(', ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var nt = Transform.Identity; switch (args[0]) { case "matrix": if (args.Length == 7) { nt = new Transform( _valuesParser.ReadNumber(args[1]), _valuesParser.ReadNumber(args[2]), _valuesParser.ReadNumber(args[3]), _valuesParser.ReadNumber(args[4]), _valuesParser.ReadNumber(args[5]), _valuesParser.ReadNumber(args[6])); } else { throw new NotSupportedException("Matrices are expected to have 6 elements, this one has " + (args.Length - 1)); } break; case "translate": if (args.Length >= 3) { nt = Transform.Translate(new Size(_valuesParser.ReadNumber(args[1]), _valuesParser.ReadNumber(args[2]))); } else if (args.Length >= 2) { nt = Transform.Translate(new Size(_valuesParser.ReadNumber(args[1]), 0)); } break; case "scale": if (args.Length >= 3) { nt = Transform.Scale(new Size(_valuesParser.ReadNumber(args[1]), _valuesParser.ReadNumber(args[2]))); } else if (args.Length >= 2) { var sx = _valuesParser.ReadNumber(args[1]); nt = Transform.Scale(new Size(sx, sx)); } break; case "rotate": var a = _valuesParser.ReadNumber(args[1]); if (args.Length >= 4) { var x = _valuesParser.ReadNumber(args[2]); var y = _valuesParser.ReadNumber(args[3]); var t1 = Transform.Translate(new Size(x, y)); var t2 = Transform.Rotate(a); var t3 = Transform.Translate(new Size(-x, -y)); nt = t1 * t2 * t3; } else { nt = Transform.Rotate(a); } break; default: throw new NotSupportedException("Can't transform " + args[0]); } t = t * nt; } return t; } private string ReadString(XElement e, string defaultValue = "") { if (e == null) return defaultValue; return e.Value ?? defaultValue; } private string ReadString(XAttribute a, string defaultValue = "") { if (a == null) return defaultValue; return a.Value ?? defaultValue; } private Rect ReadRectangle(string s) { var r = new Rect(); var p = s.Split(WS, StringSplitOptions.RemoveEmptyEntries); if (p.Length > 0) r.X = _valuesParser.ReadNumber(p[0]); if (p.Length > 1) r.Y = _valuesParser.ReadNumber(p[1]); if (p.Length > 2) r.Width = _valuesParser.ReadNumber(p[2]); if (p.Length > 3) r.Height = _valuesParser.ReadNumber(p[3]); return r; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XnaFlash.Actions; using XnaFlash.Actions.Objects; using XnaFlash.Content; using XnaFlash.Movie; using XnaFlash.Swf.Tags; using XnaVG; using XnaVG.Utils; namespace XnaFlash.Movie { public class RootMovieClip : MovieClip { private Random _random = new Random((int)DateTime.Now.Ticks); internal VGMatrixStack ButtonStack { get; private set; } public VGImage IdleCursor { get; set; } public VGImage HandCursor { get; set; } public GlobalScope GlobalScope { get; private set; } public bool MouseDown { get; private set; } public Button ActiveButton { get; set; } public bool Transparent { get; set; } public Vector2 MousePosition { get; private set; } public FlashDocument Document { get; private set; } public DateTime StartTime { get; private set; } public VGAntialiasing Antialiasing { get; private set; } public ISystemServices Services { get; private set; } public long Runtime { get { return (long)(DateTime.Now - StartTime).TotalMilliseconds; } } internal RootMovieClip(FlashDocument document, ISystemServices services) : base(null, document, null) { ButtonStack = new VGMatrixStack(32); Services = services; Transparent = true; Root = this; StartTime = DateTime.Now; Document = document; Antialiasing = VGAntialiasing.Faster; GlobalScope = new GlobalScope(this); Context.RootClip = this; Context.Scope.AddFirst(GlobalScope); } public bool? SetMouse(Vector2 mouse, bool down) { bool? res = null; if (MousePosition != mouse) { ButtonStack.Clear(); MousePosition = mouse; res = OnMouseMove(); } if (MouseDown != down) { MouseDown = down; if (ActiveButton != null) { if (down) ActiveButton.OnMouseDown(); else ActiveButton.OnMouseUp(); } } return res; } public void Draw(VGSurface surface) { using (var draw = Services.VectorDevice.BeginRendering(surface, new DisplayState(), true)) { draw.State.ResetDefaultValues(); draw.State.SetAntialiasing(Antialiasing); draw.State.SetProjection(Width, Height); draw.State.NonScalingStroke = true; draw.State.MaskingEnabled = false; draw.State.FillRule = VGFillRule.EvenOdd; draw.State.ColorTransformationEnabled = true; draw.Device.GraphicsDevice.Clear( ClearOptions.Stencil | ClearOptions.Target | ClearOptions.DepthBuffer, Transparent ? Color.Transparent.ToVector4() : Document.BackgroundColor.ToVector4(), 0f, 0); (this as IDrawable).Draw(draw); } } public int GetRandom(int max) { return _random.Next(max); } public void ToggleQuality() { switch (Antialiasing) { case VGAntialiasing.None: Antialiasing = VGAntialiasing.Faster; break; case VGAntialiasing.Faster: Antialiasing = VGAntialiasing.Better; break; case VGAntialiasing.Better: Antialiasing = VGAntialiasing.Best; break; default: Antialiasing = VGAntialiasing.None; break; } } public void StopSounds() { } public void Trace(string message, params object[] args) { Services.Log(message, args); } public void StartDrag(MovieClip clip, bool lockCenter, Rectangle? constraint) { } public void EndDrag() { } public override bool OnMouseMove() { return _displayList.OnMouseMove(); } public override void SetName(string name) { } public override string GetRootedPath(bool slashes) { return slashes ? "" : "_root"; } #region Native Properties public override float X { get { return 0f; } set { } } public override float Y { get { return 0f; } set { } } public override float XScale { get { return 100f; } set { } } public override float YScale { get { return 100f; } set { } } public override ushort TotalFrames { get { return Document.FrameCount; } } public override float Alpha { get { return 1f; } set { } } public override float Width { get { return Document.Width; } set { } } public override float Height { get { return Document.Height; } set { } } public override float Rotation { get { return 0f; } set { } } public override string Name { get { return "_root"; } } public override string DropTarget { get { return null; } } public override bool FocusRect { get { return false; } set { } } public override float SoundBufTime { get { return 0f; } set { } } public override int HighQuality { get { switch (Antialiasing) { case VGAntialiasing.None: return 0; case VGAntialiasing.Faster: return 1; case VGAntialiasing.Best: return 3; default: return 2; } } set { switch (value) { case 0: Antialiasing = VGAntialiasing.None; break; case 1: Antialiasing = VGAntialiasing.Faster; break; case 3: Antialiasing = VGAntialiasing.Best; break; default: Antialiasing = VGAntialiasing.Better; break; } } } public override string Quality { get { switch (Antialiasing) { case VGAntialiasing.None: return "LOW"; case VGAntialiasing.Faster: return "MEDIUM"; case VGAntialiasing.Best: return "BEST"; default: return "HIGH"; } } set { switch (value) { case "LOW": Antialiasing = VGAntialiasing.None; break; case "MEDIUM": Antialiasing = VGAntialiasing.Faster; break; case "BEST": Antialiasing = VGAntialiasing.Best; break; default: Antialiasing = VGAntialiasing.Better; break; } } } public override string Url { get { return Document.Name; } } public override float MouseX { get { return MousePosition.X; } } public override float MouseY { get { return MousePosition.Y; } } #endregion } }
/* ************************************************************************* ** Custom classes used by C# ************************************************************************* */ using System; using System.Diagnostics; using System.IO; #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) using System.Management; #endif using System.Text; using System.Text.RegularExpressions; using System.Threading; using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace CleanSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { static int atoi( byte[] inStr ) { return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) ); } static int atoi( string inStr ) { int i; for ( i = 0; i < inStr.Length; i++ ) { if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) break; } int result = 0; #if WINDOWS_MOBILE try { result = Int32.Parse(inStr.Substring(0, i)); } catch { } return result; #else return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); #endif } static void fprintf( TextWriter tw, string zFormat, params object[] ap ) { tw.Write( sqlite3_mprintf( zFormat, ap ) ); } static void printf( string zFormat, params object[] ap ) { Console.Out.Write( sqlite3_mprintf( zFormat, ap ) ); } //Byte Buffer Testing static int memcmp( byte[] bA, byte[] bB, int Limit ) { if ( bA.Length < Limit ) return ( bA.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( bA[i] != bB[i] ) return ( bA[i] < bB[i] ) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp( string A, byte[] bB, int Limit ) { if ( A.Length < Limit ) return ( A.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; char[] cA = A.ToCharArray(); for ( int i = 0; i < Limit; i++ ) { if ( cA[i] != bB[i] ) return ( cA[i] < bB[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Offset, byte[] b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit ) { if ( a.Length < Aoffset + Limit ) return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1; if ( b.Length < Boffset + Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Aoffset] != b[i + Boffset] ) return ( a[i + Aoffset] < b[i + Boffset] ) ? -1 : 1; } return 0; } static int memcmp( byte[] a, int Offset, string b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //String Testing static int memcmp( string A, string B, int Limit ) { if ( A.Length < Limit ) return ( A.Length < B.Length ) ? -1 : +1; if ( B.Length < Limit ) return +1; int rc; if ( ( rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal ) ) == 0 ) return 0; return rc < 0 ? -1 : +1; } // ---------------------------- // ** Builtin Functions // ---------------------------- static Regex oRegex = null; /* ** The regexp() function. two arguments are both strings ** Collating sequences are not used. */ static void regexpFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zTest; /* The input string A */ string zRegex; /* The regex string B */ Debug.Assert( argc == 2 ); UNUSED_PARAMETER( argc ); zRegex = sqlite3_value_text( argv[0] ); zTest = sqlite3_value_text( argv[1] ); if ( zTest == null || String.IsNullOrEmpty( zRegex ) ) { sqlite3_result_int( context, 0 ); return; } if ( oRegex == null || oRegex.ToString() == zRegex ) { oRegex = new Regex( zRegex, RegexOptions.IgnoreCase ); } sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 ); } // ---------------------------- // ** Convertion routines // ---------------------------- static Object lock_va_list = new Object(); static string vaFORMAT; static int vaNEXT; static void va_start( object[] ap, string zFormat ) { vaFORMAT = zFormat; vaNEXT = 0; } static Boolean va_arg( object[] ap, Boolean sysType ) { return Convert.ToBoolean( ap[vaNEXT++] ); } static Byte[] va_arg( object[] ap, Byte[] sysType ) { return (Byte[])ap[vaNEXT++]; } static Byte[][] va_arg( object[] ap, Byte[][] sysType ) { if ( ap[vaNEXT] == null ) { { vaNEXT++; return null; } } else { return (Byte[][])ap[vaNEXT++]; } } static Char va_arg( object[] ap, Char sysType ) { if ( ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0 ) { vaNEXT++; return (char)'0'; } else { if ( ap[vaNEXT] is Int64 ) if ( (i64)ap[vaNEXT] == 0 ) { vaNEXT++; return (char)'0'; } else return (char)( (i64)ap[vaNEXT++] ); else return (char)ap[vaNEXT++]; } } static Double va_arg( object[] ap, Double sysType ) { return Convert.ToDouble( ap[vaNEXT++] ); } static dxLog va_arg( object[] ap, dxLog sysType ) { return (dxLog)ap[vaNEXT++]; } static Int64 va_arg( object[] ap, Int64 sysType ) { if ( ap[vaNEXT] is System.Int64) return Convert.ToInt64( ap[vaNEXT++] ); else return (Int64)( ap[vaNEXT++].GetHashCode() ); } static Int32 va_arg( object[] ap, Int32 sysType ) { if ( Convert.ToInt64( ap[vaNEXT] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT] ) > Int32.MaxValue ) ) return (Int32)( Convert.ToUInt32( ap[vaNEXT++] ) - System.UInt32.MaxValue - 1 ); else return (Int32)Convert.ToInt32( ap[vaNEXT++] ); } static Int32[] va_arg( object[] ap, Int32[] sysType ) { if ( ap[vaNEXT] == null ) { { vaNEXT++; return null; } } else { return (Int32[])ap[vaNEXT++]; } } static MemPage va_arg( object[] ap, MemPage sysType ) { return (MemPage)ap[vaNEXT++]; } static Object va_arg( object[] ap, Object sysType ) { return (Object)ap[vaNEXT++]; } static sqlite3 va_arg( object[] ap, sqlite3 sysType ) { return (sqlite3)ap[vaNEXT++]; } static sqlite3_mem_methods va_arg( object[] ap, sqlite3_mem_methods sysType ) { return (sqlite3_mem_methods)ap[vaNEXT++]; } static sqlite3_mutex_methods va_arg( object[] ap, sqlite3_mutex_methods sysType ) { return (sqlite3_mutex_methods)ap[vaNEXT++]; } static SrcList va_arg( object[] ap, SrcList sysType ) { return (SrcList)ap[vaNEXT++]; } static String va_arg( object[] ap, String sysType ) { if ( ap.Length < vaNEXT - 1 || ap[vaNEXT] == null ) { vaNEXT++; return "NULL"; } else { if ( ap[vaNEXT] is Byte[] ) if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT] ).Length ) == "\0" ) { vaNEXT++; return ""; } else return Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT++] ).Length ); else if ( ap[vaNEXT] is Int32 ) { vaNEXT++; return null; } else if ( ap[vaNEXT] is StringBuilder ) return (String)ap[vaNEXT++].ToString(); else if ( ap[vaNEXT] is Char ) return ( (Char)ap[vaNEXT++] ).ToString(); else return (String)ap[vaNEXT++]; } } static Token va_arg( object[] ap, Token sysType ) { return (Token)ap[vaNEXT++]; } static UInt32 va_arg( object[] ap, UInt32 sysType ) { if ( ap[vaNEXT].GetType().IsClass ) { return (UInt32)ap[vaNEXT++].GetHashCode(); } else { return (UInt32)Convert.ToUInt32( ap[vaNEXT++] ); } } static UInt64 va_arg( object[] ap, UInt64 sysType ) { if ( ap[vaNEXT].GetType().IsClass ) { return (UInt64)ap[vaNEXT++].GetHashCode(); } else { return (UInt64)Convert.ToUInt64( ap[vaNEXT++] ); } } static void_function va_arg( object[] ap, void_function sysType ) { return (void_function)ap[vaNEXT++]; } static void va_end( ref string[] ap ) { ap = null; vaNEXT = -1; vaFORMAT = ""; } static void va_end( ref object[] ap ) { ap = null; vaNEXT = -1; vaFORMAT = ""; } public static tm localtime( time_t baseTime ) { System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime( System.DateTime date ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64( timeSpan.TotalSeconds ); } public static System.DateTime ToCSharpTime( long unixTime ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) ); } public class tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector( StringBuilder diskPath ) { #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher( "select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove( diskPath.Length - 1, 1 ) + "'" ); try { foreach ( ManagementObject moLogDisk in mosLogicalDisks.Get() ) { ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher( "select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'" ); foreach ( ManagementObject moPDisk in mosDiskDrives.Get() ) { return int.Parse( moPDisk["BytesPerSector"].ToString() ); } } } catch { } return 4096; #else return 4096; #endif } static void SWAP<T>( ref T A, ref T B ) { T t = A; A = B; B = t; } static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert( argc <= 1 ); Mem pMem = sqlite3_aggregate_context( context, 1 );//sizeof(*p)); if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if ( p.Context == null ) p.Context = pMem; if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) ) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type( argv[0] ); if ( p != null && type != SQLITE_NULL ) { p.cnt++; if ( type == SQLITE_INTEGER ) { i64 v = sqlite3_value_int64( argv[0] ); if ( v == 40 || v == 41 ) { sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 ); return; } else { p.iSum += v; if ( !( p.approx | p.overflow != 0 ) ) { i64 iNewSum = p.iSum + v; int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double( argv[0] ); p.approx = true; } } } } static void x_CountFinalize( sqlite3_context context ) { SumCtx p; Mem pMem = sqlite3_aggregate_context( context, 0 ); p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { if ( p.overflow != 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); } else if ( p.approx ) { sqlite3_result_double( context, p.rSum ); } else if ( p.iSum == 42 ) { sqlite3_result_error( context, "x_count totals to 42", -1 ); } else { sqlite3_result_int64( context, p.iSum ); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } static long InterlockedIncrement( long location ) { Interlocked.Increment( ref location ); return location; } static void EnterCriticalSection( Object mtx ) { //long mid = mtx.GetHashCode(); //int tid = Thread.CurrentThread.ManagedThreadId; //long ticks = cnt++; //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); Monitor.Enter( mtx ); } static void InitializeCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Enter( mtx ); } static void DeleteCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); Monitor.Exit( mtx ); } static void LeaveCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Exit( mtx ); } #endif // Miscellaneous Windows Constants //#define ERROR_FILE_NOT_FOUND 2L //#define ERROR_HANDLE_DISK_FULL 39L //#define ERROR_NOT_SUPPORTED 50L //#define ERROR_DISK_FULL 112L const long ERROR_FILE_NOT_FOUND = 2L; const long ERROR_HANDLE_DISK_FULL = 39L; const long ERROR_NOT_SUPPORTED = 50L; const long ERROR_DISK_FULL = 112L; private class SQLite3UpperToLower { static int[] sqlite3UpperToLower = new int[] { #if SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif }; public int this[int index] { get { if ( index < sqlite3UpperToLower.Length ) return sqlite3UpperToLower[index]; else return index; } } public int this[u32 index] { get { if ( index < sqlite3UpperToLower.Length ) return sqlite3UpperToLower[index]; else return (int)index; } } } static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; } }
using System.Collections.Generic; using Lucene.Net.Documents; using Lucene.Net.Index; using NUnit.Framework; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search.Similarities { /* * 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 Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SpanOrQuery = Lucene.Net.Search.Spans.SpanOrQuery; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using Term = Lucene.Net.Index.Term; using TextField = TextField; /// <summary> /// Tests against all the similarities we have /// </summary> [TestFixture] public class TestSimilarity2 : LuceneTestCase { internal IList<Similarity> sims; [SetUp] public override void SetUp() { base.SetUp(); sims = new List<Similarity>(); sims.Add(new DefaultSimilarity()); sims.Add(new BM25Similarity()); // TODO: not great that we dup this all with TestSimilarityBase foreach (BasicModel basicModel in TestSimilarityBase.BASIC_MODELS) { foreach (AfterEffect afterEffect in TestSimilarityBase.AFTER_EFFECTS) { foreach (Normalization normalization in TestSimilarityBase.NORMALIZATIONS) { sims.Add(new DFRSimilarity(basicModel, afterEffect, normalization)); } } } foreach (Distribution distribution in TestSimilarityBase.DISTRIBUTIONS) { foreach (Lambda lambda in TestSimilarityBase.LAMBDAS) { foreach (Normalization normalization in TestSimilarityBase.NORMALIZATIONS) { sims.Add(new IBSimilarity(distribution, lambda, normalization)); } } } sims.Add(new LMDirichletSimilarity()); sims.Add(new LMJelinekMercerSimilarity(0.1f)); sims.Add(new LMJelinekMercerSimilarity(0.7f)); } /// <summary> /// because of stupid things like querynorm, its possible we computeStats on a field that doesnt exist at all /// test this against a totally empty index, to make sure sims handle it /// </summary> [Test] public virtual void TestEmptyIndex() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; Assert.AreEqual(0, @is.Search(new TermQuery(new Term("foo", "bar")), 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// similar to the above, but ORs the query with a real field </summary> [Test] public virtual void TestEmptyField() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewTextField("foo", "bar", Field.Store.NO)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; BooleanQuery query = new BooleanQuery(true); query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD); query.Add(new TermQuery(new Term("bar", "baz")), Occur.SHOULD); Assert.AreEqual(1, @is.Search(query, 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// similar to the above, however the field exists, but we query with a term that doesnt exist too </summary> [Test] public virtual void TestEmptyTerm() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewTextField("foo", "bar", Field.Store.NO)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; BooleanQuery query = new BooleanQuery(true); query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD); query.Add(new TermQuery(new Term("foo", "baz")), Occur.SHOULD); Assert.AreEqual(1, @is.Search(query, 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// make sure we can retrieve when norms are disabled </summary> [Test] public virtual void TestNoNorms() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.OmitNorms = true; ft.Freeze(); doc.Add(NewField("foo", "bar", ft)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; BooleanQuery query = new BooleanQuery(true); query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD); Assert.AreEqual(1, @is.Search(query, 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// make sure all sims work if TF is omitted </summary> [Test] public virtual void TestOmitTF() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = IndexOptions.DOCS_ONLY; ft.Freeze(); Field f = NewField("foo", "bar", ft); doc.Add(f); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; BooleanQuery query = new BooleanQuery(true); query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD); Assert.AreEqual(1, @is.Search(query, 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// make sure all sims work if TF and norms is omitted </summary> [Test] public virtual void TestOmitTFAndNorms() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.IndexOptions = IndexOptions.DOCS_ONLY; ft.OmitNorms = true; ft.Freeze(); Field f = NewField("foo", "bar", ft); doc.Add(f); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; BooleanQuery query = new BooleanQuery(true); query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD); Assert.AreEqual(1, @is.Search(query, 10).TotalHits); } ir.Dispose(); dir.Dispose(); } /// <summary> /// make sure all sims work with spanOR(termX, termY) where termY does not exist </summary> [Test] public virtual void TestCrazySpans() { // The problem: "normal" lucene queries create scorers, returning null if terms dont exist // this means they never score a term that does not exist. // however with spans, there is only one scorer for the whole hierarchy: // inner queries are not real queries, their boosts are ignored, etc. Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); doc.Add(NewField("foo", "bar", ft)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); foreach (Similarity sim in sims) { @is.Similarity = sim; SpanTermQuery s1 = new SpanTermQuery(new Term("foo", "bar")); SpanTermQuery s2 = new SpanTermQuery(new Term("foo", "baz")); Query query = new SpanOrQuery(s1, s2); TopDocs td = @is.Search(query, 10); Assert.AreEqual(1, td.TotalHits); float score = td.ScoreDocs[0].Score; Assert.IsTrue(score >= 0.0f); Assert.IsFalse(float.IsInfinity(score), "inf score for " + sim); } ir.Dispose(); dir.Dispose(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.CodeAnalysis.Editor.Extensibility.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Moq; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { public class InteractiveNavigateToTests : AbstractNavigateToTests { protected override string Language => "csharp"; protected override TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider) => TestWorkspace.CreateCSharp(content, parseOptions: Options.Script); [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NoItemsForEmptyFile() { await TestAsync("", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClass() { await TestAsync( @"class Foo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindNestedClass() { await TestAsync( @"class Foo { class Bar { internal class DogBed { } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMemberInANestedClass() { await TestAsync( @"class Foo { class Bar { class DogBed { public void Method() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{FeaturesResources.type_space}Foo.Bar.DogBed"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericClassWithConstraints() { await TestAsync( @"using System.Collections; class Foo<T> where T : IEnumerable { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericMethodWithConstraints() { await TestAsync( @"using System; class Foo<U> { public void Bar<T>(T item) where T : IComparable<T> { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{FeaturesResources.type_space}Foo<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialClass() { await TestAsync( @"public partial class Foo { int a; } partial class Foo { int b; }", async w => { var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindTypesInMetadata() { await TestAsync( @"using System; Class Program { FileStyleUriParser f; }", async w => { var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(items.Count(), 0); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassInNamespace() { await TestAsync( @"namespace Bar { class Foo { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStruct() { await TestAsync( @"struct Bar { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnum() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnumMember() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstField() { await TestAsync( @"class Foo { const int bar = 7; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimIdentifier() { await TestAsync( @"class Foo { string @string; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("string")).Single(); VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindIndexer() { var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEvent() { var program = "class Foo { public event EventHandler ChangedEventHandler; }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindAutoProperty() { await TestAsync( @"class Foo { int Bar { get; set; } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethod() { await TestAsync( @"class Foo { void DoSomething(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedMethod() { await TestAsync( @"class Foo { void DoSomething(int a, string b) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstructor() { await TestAsync( @"class Foo { public Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedConstructor() { await TestAsync( @"class Foo { public Foo(int i) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStaticConstructor() { await TestAsync( @"class Foo { static Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethods() { await TestAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Bar"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodDefinitionOnly() { await TestAsync( @"partial class Foo { partial void Bar(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindOverriddenMembers() { var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Name"); VerifyNavigateToResultItems(expecteditems, items); var item = items.ElementAt(0); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}DogBed", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); item = items.ElementAt(1); itemDisplay = item.DisplayFactory.CreateItemDisplay(item); unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}Foo", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindInterface() { await TestAsync( @"public interface IFoo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("IF")).Single(); VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface, displayName: "IFoo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindDelegateInNamespace() { await TestAsync( @"namespace Foo { delegate void DoStuff(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate, displayName: "DoStuff"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindLambdaExpression() { await TestAsync( @"using System; class Foo { Func<int, int> sqr = x => x * x; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task OrderingOfConstructorsAndTypes() { await TestAsync( @"class C1 { C1(int i) { } } class C2 { C2(float f) { } static C2() { } }", async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), }; var items = (await _aggregator.GetItemsAsync("C")).ToList(); items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task StartStopSanity() { // Verify that multiple calls to start/stop and dispose don't blow up await TestAsync( @"public class Foo { }", async w => { // Do one set of queries Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Do the same query again, make sure nothing was left over Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Dispose the provider _provider.Dispose(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DescriptionItems() { var code = "public\r\nclass\r\nFoo\r\n{ }"; await TestAsync(code, async w => { var item = (await _aggregator.GetItemsAsync("F")).Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var descriptionItems = itemDisplay.DescriptionItems; Action<string, string> assertDescription = (label, value) => { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); }; assertDescription("File:", w.Documents.Single().Name); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest1() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 }; var items = await _aggregator.GetItemsAsync("GK"); Assert.Equal(expecteditems.Count(), items.Count()); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest2() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("GKW"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest3() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest4() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest5() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest7() { ////Diff from dev10 var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K*W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest8() { ////Diff from dev10 var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using 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> /// VirtualNetworksOperations operations. /// </summary> internal partial class VirtualNetworksOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworksOperations { /// <summary> /// Initializes a new instance of the VirtualNetworksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal VirtualNetworksOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified virtual network by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualNetwork>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Checks whether a private IP address is available for use. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='ipAddress'> /// The private IP address to be verified. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ipAddress", ipAddress); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckIPAddressAvailability", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (ipAddress != null) { _queryParameters.Add(string.Format("ipAddress={0}", System.Uri.EscapeDataString(ipAddress))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPAddressAvailabilityResult>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<IPAddressAvailabilityResult>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _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 != 202 && (int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } 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; } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.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 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualNetwork>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </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<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkWatchersOperations operations. /// </summary> public partial interface INetworkWatchersOperations { /// <summary> /// Creates or updates a network watcher in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the network watcher resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkWatcher>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NetworkWatcher parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified network watcher by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NetworkWatcher>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified network watcher resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network watchers by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<NetworkWatcher>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all network watchers by subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<NetworkWatcher>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the current network topology by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the representation of topology. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Topology>> GetTopologyWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TopologyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Verify IP flow from the specified VM to a location given the /// currently configured NSG rules. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the IP flow to be verified. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VerificationIPFlowResult>> VerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the next hop from the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the source and destination endpoint. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NextHopResult>> GetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the configured and effective security group rules on the /// specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the VM to check security groups for. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SecurityGroupViewResult>> GetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiate troubleshooting on a specified resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the resource to troubleshoot. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TroubleshootingResult>> GetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the last completed troubleshooting result on a specified /// resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the resource to query the troubleshooting /// result. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TroubleshootingResult>> GetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Configures flow log on a specified resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the network watcher resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the configuration of flow log. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<FlowLogInformation>> SetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Queries status of flow log on a specified resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the network watcher resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define a resource to query flow log status. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<FlowLogInformation>> GetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified network watcher resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Verify IP flow from the specified VM to a location given the /// currently configured NSG rules. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the IP flow to be verified. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VerificationIPFlowResult>> BeginVerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the next hop from the specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the source and destination endpoint. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NextHopResult>> BeginGetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the configured and effective security group rules on the /// specified VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='parameters'> /// Parameters that define the VM to check security groups for. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SecurityGroupViewResult>> BeginGetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiate troubleshooting on a specified resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the resource to troubleshoot. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TroubleshootingResult>> BeginGetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the last completed troubleshooting result on a specified /// resource /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the resource to query the troubleshooting /// result. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<TroubleshootingResult>> BeginGetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Configures flow log on a specified resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the network watcher resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define the configuration of flow log. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<FlowLogInformation>> BeginSetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Queries status of flow log on a specified resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the network watcher resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher resource. /// </param> /// <param name='parameters'> /// Parameters that define a resource to query flow log status. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<FlowLogInformation>> BeginGetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using System.Threading.Tasks; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Geoprocessing; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.AnalyzeHotspots { [Register("AnalyzeHotspots")] [ArcGISRuntime.Samples.Shared.Attributes.ClassFile("DateSelectionViewController.cs")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Analyze hotspots", category: "Geoprocessing", description: "Use a geoprocessing service and a set of features to identify statistically significant hot spots and cold spots.", instructions: "Select a date range (between 1998-01-01 and 1998-05-31) from the dialog and tap on Analyze. The results will be shown on the map upon successful completion of the `GeoprocessingJob`.", tags: new[] { "Geoprocessing", "GeoprocessingJob", "GeoprocessingParameters", "GeoprocessingResult" })] public class AnalyzeHotspots : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIBarButtonItem _configureButton; private UIBarButtonItem _startButton; private DateSelectionViewController _selectionView; private UIActivityIndicatorView _progressBar; // URL for the geoprocessing service. private const string HotspotUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/GPServer/911%20Calls%20Hotspot"; // The geoprocessing task for hot spots analysis. private GeoprocessingTask _hotspotTask; // The job that handles the communication between the application and the geoprocessing task. private GeoprocessingJob _hotspotJob; public AnalyzeHotspots() { Title = "Analyze hotspots"; } private async void Initialize() { // Create and show a map with a topographic basemap. _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic); try { // Create a new geoprocessing task. _hotspotTask = await GeoprocessingTask.CreateAsync(new Uri(HotspotUrl)); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show(); } } private async void OnRunAnalysisClicked(object sender, EventArgs e) { // Clear any existing results. _myMapView.Map.OperationalLayers.Clear(); // Show the animating progress bar . _progressBar.StartAnimating(); // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis. DateTime fromDate = (DateTime) _selectionView.StartPicker.Date; DateTime toDate = (DateTime) _selectionView.EndPicker.Date; // The end date must be at least one day after the start date. if (toDate <= fromDate.AddDays(1)) { // Show error message. UIAlertController alert = UIAlertController.Create("Invalid date range", "Please enter a valid date range. There has to be at least one day in between To and From dates.", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); // Stop the progress bar from animating (which also hides it as well). _progressBar.StopAnimating(); return; } // Create the parameters that are passed to the used geoprocessing task. GeoprocessingParameters hotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit); // Construct the date query. string myQueryString = $"(\"DATE\" > date '{fromDate:yyyy-MM-dd 00:00:00}' AND \"DATE\" < date '{toDate:yyy-MM-dd 00:00:00}')"; // Add the query that contains the date range used in the analysis. hotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString)); // Create job that handles the communication between the application and the geoprocessing task. _hotspotJob = _hotspotTask.CreateJob(hotspotParameters); try { // Execute the geoprocessing analysis and wait for the results. GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync(); // Add results to a map using map server from a geoprocessing task. // Load to get access to full extent. await analysisResult.MapImageLayer.LoadAsync(); // Add the analysis layer to the map view. _myMapView.Map.OperationalLayers.Add(analysisResult.MapImageLayer); // Zoom to the results. await _myMapView.SetViewpointAsync(new Viewpoint(analysisResult.MapImageLayer.FullExtent)); } catch (TaskCanceledException) { // This is thrown if the task is canceled. Ignore. } catch (Exception ex) { // Display error messages if the geoprocessing task fails. if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null) { // Report error. UIAlertController alert = UIAlertController.Create("Geoprocessing Error", _hotspotJob.Error.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } else { // Report error. UIAlertController alert = UIAlertController.Create("Sample error", ex.ToString(), UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } } finally { // Stop the progress bar from animating (which also hides it). _progressBar.StopAnimating(); } } private void ShowConfiguration(object sender, EventArgs e) { NavigationController.PushViewController(_selectionView, true); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _selectionView = new DateSelectionViewController(); _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _configureButton = new UIBarButtonItem(); _configureButton.Title = "Configure"; _startButton = new UIBarButtonItem(); _startButton.Title = "Run analysis"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { _configureButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _startButton }; // Hide the activity indicator (progress bar) when stopped. _progressBar = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge) { BackgroundColor = UIColor.FromWhiteAlpha(0, .5f), HidesWhenStopped = true, TranslatesAutoresizingMaskIntoConstraints = false }; // Add the views. View.AddSubviews(_myMapView, toolbar, _progressBar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), _progressBar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _progressBar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _progressBar.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _progressBar.BottomAnchor.ConstraintEqualTo(View.BottomAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _startButton.Clicked += OnRunAnalysisClicked; _configureButton.Clicked += ShowConfiguration; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _startButton.Clicked -= OnRunAnalysisClicked; _configureButton.Clicked -= ShowConfiguration; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System { public static class __AppDomainSetup { public static IObservable<System.Byte[]> GetConfigurationBytes( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.GetConfigurationBytes()); } public static IObservable<System.Reactive.Unit> SetConfigurationBytes( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Byte[]> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.SetConfigurationBytes(valueLambda)); } public static IObservable<System.Reactive.Unit> SetCompatibilitySwitches( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Collections.Generic.IEnumerable<System.String>> switches) { return ObservableExt.ZipExecute(AppDomainSetupValue, switches, (AppDomainSetupValueLambda, switchesLambda) => AppDomainSetupValueLambda.SetCompatibilitySwitches(switchesLambda)); } public static IObservable<System.Reactive.Unit> SetNativeFunction( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> functionName, IObservable<System.Int32> functionVersion, IObservable<System.IntPtr> functionPointer) { return ObservableExt.ZipExecute(AppDomainSetupValue, functionName, functionVersion, functionPointer, (AppDomainSetupValueLambda, functionNameLambda, functionVersionLambda, functionPointerLambda) => AppDomainSetupValueLambda.SetNativeFunction(functionNameLambda, functionVersionLambda, functionPointerLambda)); } public static IObservable<System.String> get_AppDomainManagerAssembly( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.AppDomainManagerAssembly); } public static IObservable<System.String> get_AppDomainManagerType( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.AppDomainManagerType); } public static IObservable<System.String[]> get_PartialTrustVisibleAssemblies( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.PartialTrustVisibleAssemblies); } public static IObservable<System.String> get_ApplicationBase( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ApplicationBase); } public static IObservable<System.String> get_ConfigurationFile( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ConfigurationFile); } public static IObservable<System.String> get_TargetFrameworkName( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.TargetFrameworkName); } public static IObservable<System.String> get_DynamicBase( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.DynamicBase); } public static IObservable<System.Boolean> get_DisallowPublisherPolicy( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.DisallowPublisherPolicy); } public static IObservable<System.Boolean> get_DisallowBindingRedirects( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.DisallowBindingRedirects); } public static IObservable<System.Boolean> get_DisallowCodeDownload( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.DisallowCodeDownload); } public static IObservable<System.Boolean> get_DisallowApplicationBaseProbing( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.DisallowApplicationBaseProbing); } public static IObservable<System.String> get_ApplicationName( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ApplicationName); } public static IObservable<System.AppDomainInitializer> get_AppDomainInitializer( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.AppDomainInitializer); } public static IObservable<System.String[]> get_AppDomainInitializerArguments( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.AppDomainInitializerArguments); } public static IObservable<System.Runtime.Hosting.ActivationArguments> get_ActivationArguments( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ActivationArguments); } public static IObservable<System.Security.Policy.ApplicationTrust> get_ApplicationTrust( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ApplicationTrust); } public static IObservable<System.String> get_PrivateBinPath( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.PrivateBinPath); } public static IObservable<System.String> get_PrivateBinPathProbe( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.PrivateBinPathProbe); } public static IObservable<System.String> get_ShadowCopyDirectories( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ShadowCopyDirectories); } public static IObservable<System.String> get_ShadowCopyFiles( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.ShadowCopyFiles); } public static IObservable<System.String> get_CachePath( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.CachePath); } public static IObservable<System.String> get_LicenseFile( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.LicenseFile); } public static IObservable<System.LoaderOptimization> get_LoaderOptimization( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.LoaderOptimization); } public static IObservable<System.Boolean> get_SandboxInterop( this IObservable<System.AppDomainSetup> AppDomainSetupValue) { return Observable.Select(AppDomainSetupValue, (AppDomainSetupValueLambda) => AppDomainSetupValueLambda.SandboxInterop); } public static IObservable<System.Reactive.Unit> set_AppDomainManagerAssembly( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.AppDomainManagerAssembly = valueLambda); } public static IObservable<System.Reactive.Unit> set_AppDomainManagerType( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.AppDomainManagerType = valueLambda); } public static IObservable<System.Reactive.Unit> set_PartialTrustVisibleAssemblies( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String[]> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.PartialTrustVisibleAssemblies = valueLambda); } public static IObservable<System.Reactive.Unit> set_ApplicationBase( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ApplicationBase = valueLambda); } public static IObservable<System.Reactive.Unit> set_ConfigurationFile( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ConfigurationFile = valueLambda); } public static IObservable<System.Reactive.Unit> set_TargetFrameworkName( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.TargetFrameworkName = valueLambda); } public static IObservable<System.Reactive.Unit> set_DynamicBase( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.DynamicBase = valueLambda); } public static IObservable<System.Reactive.Unit> set_DisallowPublisherPolicy( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.DisallowPublisherPolicy = valueLambda); } public static IObservable<System.Reactive.Unit> set_DisallowBindingRedirects( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.DisallowBindingRedirects = valueLambda); } public static IObservable<System.Reactive.Unit> set_DisallowCodeDownload( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.DisallowCodeDownload = valueLambda); } public static IObservable<System.Reactive.Unit> set_DisallowApplicationBaseProbing( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.DisallowApplicationBaseProbing = valueLambda); } public static IObservable<System.Reactive.Unit> set_ApplicationName( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ApplicationName = valueLambda); } public static IObservable<System.Reactive.Unit> set_AppDomainInitializer( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.AppDomainInitializer> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.AppDomainInitializer = valueLambda); } public static IObservable<System.Reactive.Unit> set_AppDomainInitializerArguments( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String[]> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.AppDomainInitializerArguments = valueLambda); } public static IObservable<System.Reactive.Unit> set_ActivationArguments( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Runtime.Hosting.ActivationArguments> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ActivationArguments = valueLambda); } public static IObservable<System.Reactive.Unit> set_ApplicationTrust( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Security.Policy.ApplicationTrust> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ApplicationTrust = valueLambda); } public static IObservable<System.Reactive.Unit> set_PrivateBinPath( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.PrivateBinPath = valueLambda); } public static IObservable<System.Reactive.Unit> set_PrivateBinPathProbe( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.PrivateBinPathProbe = valueLambda); } public static IObservable<System.Reactive.Unit> set_ShadowCopyDirectories( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ShadowCopyDirectories = valueLambda); } public static IObservable<System.Reactive.Unit> set_ShadowCopyFiles( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.ShadowCopyFiles = valueLambda); } public static IObservable<System.Reactive.Unit> set_CachePath( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.CachePath = valueLambda); } public static IObservable<System.Reactive.Unit> set_LicenseFile( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.LicenseFile = valueLambda); } public static IObservable<System.Reactive.Unit> set_LoaderOptimization( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.LoaderOptimization> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.LoaderOptimization = valueLambda); } public static IObservable<System.Reactive.Unit> set_SandboxInterop( this IObservable<System.AppDomainSetup> AppDomainSetupValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(AppDomainSetupValue, value, (AppDomainSetupValueLambda, valueLambda) => AppDomainSetupValueLambda.SandboxInterop = valueLambda); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the ConConsultaDiagnostico class. /// </summary> [Serializable] public partial class ConConsultaDiagnosticoCollection : ActiveList<ConConsultaDiagnostico, ConConsultaDiagnosticoCollection> { public ConConsultaDiagnosticoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ConConsultaDiagnosticoCollection</returns> public ConConsultaDiagnosticoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ConConsultaDiagnostico o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the CON_ConsultaDiagnostico table. /// </summary> [Serializable] public partial class ConConsultaDiagnostico : ActiveRecord<ConConsultaDiagnostico>, IActiveRecord { #region .ctors and Default Settings public ConConsultaDiagnostico() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ConConsultaDiagnostico(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ConConsultaDiagnostico(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ConConsultaDiagnostico(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_ConsultaDiagnostico", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdConsultaDiagnostico = new TableSchema.TableColumn(schema); colvarIdConsultaDiagnostico.ColumnName = "idConsultaDiagnostico"; colvarIdConsultaDiagnostico.DataType = DbType.Int32; colvarIdConsultaDiagnostico.MaxLength = 0; colvarIdConsultaDiagnostico.AutoIncrement = true; colvarIdConsultaDiagnostico.IsNullable = false; colvarIdConsultaDiagnostico.IsPrimaryKey = true; colvarIdConsultaDiagnostico.IsForeignKey = false; colvarIdConsultaDiagnostico.IsReadOnly = false; colvarIdConsultaDiagnostico.DefaultSetting = @""; colvarIdConsultaDiagnostico.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdConsultaDiagnostico); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = true; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdConsulta = new TableSchema.TableColumn(schema); colvarIdConsulta.ColumnName = "idConsulta"; colvarIdConsulta.DataType = DbType.Int32; colvarIdConsulta.MaxLength = 0; colvarIdConsulta.AutoIncrement = false; colvarIdConsulta.IsNullable = true; colvarIdConsulta.IsPrimaryKey = false; colvarIdConsulta.IsForeignKey = true; colvarIdConsulta.IsReadOnly = false; colvarIdConsulta.DefaultSetting = @""; colvarIdConsulta.ForeignKeyTableName = "CON_Consulta"; schema.Columns.Add(colvarIdConsulta); TableSchema.TableColumn colvarPrincipal = new TableSchema.TableColumn(schema); colvarPrincipal.ColumnName = "principal"; colvarPrincipal.DataType = DbType.Boolean; colvarPrincipal.MaxLength = 0; colvarPrincipal.AutoIncrement = false; colvarPrincipal.IsNullable = true; colvarPrincipal.IsPrimaryKey = false; colvarPrincipal.IsForeignKey = false; colvarPrincipal.IsReadOnly = false; colvarPrincipal.DefaultSetting = @""; colvarPrincipal.ForeignKeyTableName = ""; schema.Columns.Add(colvarPrincipal); TableSchema.TableColumn colvarCODCIE10 = new TableSchema.TableColumn(schema); colvarCODCIE10.ColumnName = "CODCIE10"; colvarCODCIE10.DataType = DbType.Int32; colvarCODCIE10.MaxLength = 0; colvarCODCIE10.AutoIncrement = false; colvarCODCIE10.IsNullable = true; colvarCODCIE10.IsPrimaryKey = false; colvarCODCIE10.IsForeignKey = true; colvarCODCIE10.IsReadOnly = false; colvarCODCIE10.DefaultSetting = @""; colvarCODCIE10.ForeignKeyTableName = "Sys_CIE10"; schema.Columns.Add(colvarCODCIE10); TableSchema.TableColumn colvarPrimerConsulta = new TableSchema.TableColumn(schema); colvarPrimerConsulta.ColumnName = "PrimerConsulta"; colvarPrimerConsulta.DataType = DbType.Int32; colvarPrimerConsulta.MaxLength = 0; colvarPrimerConsulta.AutoIncrement = false; colvarPrimerConsulta.IsNullable = false; colvarPrimerConsulta.IsPrimaryKey = false; colvarPrimerConsulta.IsForeignKey = false; colvarPrimerConsulta.IsReadOnly = false; colvarPrimerConsulta.DefaultSetting = @"((0))"; colvarPrimerConsulta.ForeignKeyTableName = ""; schema.Columns.Add(colvarPrimerConsulta); TableSchema.TableColumn colvarIdNivelDeAbordaje = new TableSchema.TableColumn(schema); colvarIdNivelDeAbordaje.ColumnName = "idNivelDeAbordaje"; colvarIdNivelDeAbordaje.DataType = DbType.Int32; colvarIdNivelDeAbordaje.MaxLength = 0; colvarIdNivelDeAbordaje.AutoIncrement = false; colvarIdNivelDeAbordaje.IsNullable = true; colvarIdNivelDeAbordaje.IsPrimaryKey = false; colvarIdNivelDeAbordaje.IsForeignKey = false; colvarIdNivelDeAbordaje.IsReadOnly = false; colvarIdNivelDeAbordaje.DefaultSetting = @""; colvarIdNivelDeAbordaje.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNivelDeAbordaje); TableSchema.TableColumn colvarIdTipoPrestacionSaludMental = new TableSchema.TableColumn(schema); colvarIdTipoPrestacionSaludMental.ColumnName = "idTipoPrestacionSaludMental"; colvarIdTipoPrestacionSaludMental.DataType = DbType.Int32; colvarIdTipoPrestacionSaludMental.MaxLength = 0; colvarIdTipoPrestacionSaludMental.AutoIncrement = false; colvarIdTipoPrestacionSaludMental.IsNullable = true; colvarIdTipoPrestacionSaludMental.IsPrimaryKey = false; colvarIdTipoPrestacionSaludMental.IsForeignKey = false; colvarIdTipoPrestacionSaludMental.IsReadOnly = false; colvarIdTipoPrestacionSaludMental.DefaultSetting = @""; colvarIdTipoPrestacionSaludMental.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoPrestacionSaludMental); TableSchema.TableColumn colvarIdTiempoInsumido = new TableSchema.TableColumn(schema); colvarIdTiempoInsumido.ColumnName = "idTiempoInsumido"; colvarIdTiempoInsumido.DataType = DbType.Int32; colvarIdTiempoInsumido.MaxLength = 0; colvarIdTiempoInsumido.AutoIncrement = false; colvarIdTiempoInsumido.IsNullable = true; colvarIdTiempoInsumido.IsPrimaryKey = false; colvarIdTiempoInsumido.IsForeignKey = false; colvarIdTiempoInsumido.IsReadOnly = false; colvarIdTiempoInsumido.DefaultSetting = @""; colvarIdTiempoInsumido.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTiempoInsumido); TableSchema.TableColumn colvarIdDemanda = new TableSchema.TableColumn(schema); colvarIdDemanda.ColumnName = "idDemanda"; colvarIdDemanda.DataType = DbType.Int32; colvarIdDemanda.MaxLength = 0; colvarIdDemanda.AutoIncrement = false; colvarIdDemanda.IsNullable = true; colvarIdDemanda.IsPrimaryKey = false; colvarIdDemanda.IsForeignKey = false; colvarIdDemanda.IsReadOnly = false; colvarIdDemanda.DefaultSetting = @""; colvarIdDemanda.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdDemanda); TableSchema.TableColumn colvarRecursoHumano = new TableSchema.TableColumn(schema); colvarRecursoHumano.ColumnName = "RecursoHumano"; colvarRecursoHumano.DataType = DbType.AnsiString; colvarRecursoHumano.MaxLength = 20; colvarRecursoHumano.AutoIncrement = false; colvarRecursoHumano.IsNullable = true; colvarRecursoHumano.IsPrimaryKey = false; colvarRecursoHumano.IsForeignKey = false; colvarRecursoHumano.IsReadOnly = false; colvarRecursoHumano.DefaultSetting = @""; colvarRecursoHumano.ForeignKeyTableName = ""; schema.Columns.Add(colvarRecursoHumano); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_ConsultaDiagnostico",schema); } } #endregion #region Props [XmlAttribute("IdConsultaDiagnostico")] [Bindable(true)] public int IdConsultaDiagnostico { get { return GetColumnValue<int>(Columns.IdConsultaDiagnostico); } set { SetColumnValue(Columns.IdConsultaDiagnostico, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int? IdEfector { get { return GetColumnValue<int?>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdConsulta")] [Bindable(true)] public int? IdConsulta { get { return GetColumnValue<int?>(Columns.IdConsulta); } set { SetColumnValue(Columns.IdConsulta, value); } } [XmlAttribute("Principal")] [Bindable(true)] public bool? Principal { get { return GetColumnValue<bool?>(Columns.Principal); } set { SetColumnValue(Columns.Principal, value); } } [XmlAttribute("CODCIE10")] [Bindable(true)] public int? CODCIE10 { get { return GetColumnValue<int?>(Columns.CODCIE10); } set { SetColumnValue(Columns.CODCIE10, value); } } [XmlAttribute("PrimerConsulta")] [Bindable(true)] public int PrimerConsulta { get { return GetColumnValue<int>(Columns.PrimerConsulta); } set { SetColumnValue(Columns.PrimerConsulta, value); } } [XmlAttribute("IdNivelDeAbordaje")] [Bindable(true)] public int? IdNivelDeAbordaje { get { return GetColumnValue<int?>(Columns.IdNivelDeAbordaje); } set { SetColumnValue(Columns.IdNivelDeAbordaje, value); } } [XmlAttribute("IdTipoPrestacionSaludMental")] [Bindable(true)] public int? IdTipoPrestacionSaludMental { get { return GetColumnValue<int?>(Columns.IdTipoPrestacionSaludMental); } set { SetColumnValue(Columns.IdTipoPrestacionSaludMental, value); } } [XmlAttribute("IdTiempoInsumido")] [Bindable(true)] public int? IdTiempoInsumido { get { return GetColumnValue<int?>(Columns.IdTiempoInsumido); } set { SetColumnValue(Columns.IdTiempoInsumido, value); } } [XmlAttribute("IdDemanda")] [Bindable(true)] public int? IdDemanda { get { return GetColumnValue<int?>(Columns.IdDemanda); } set { SetColumnValue(Columns.IdDemanda, value); } } [XmlAttribute("RecursoHumano")] [Bindable(true)] public string RecursoHumano { get { return GetColumnValue<string>(Columns.RecursoHumano); } set { SetColumnValue(Columns.RecursoHumano, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysCIE10 ActiveRecord object related to this ConConsultaDiagnostico /// /// </summary> public DalSic.SysCIE10 SysCIE10 { get { return DalSic.SysCIE10.FetchByID(this.CODCIE10); } set { SetColumnValue("CODCIE10", value.Id); } } /// <summary> /// Returns a ConConsultum ActiveRecord object related to this ConConsultaDiagnostico /// /// </summary> public DalSic.ConConsultum ConConsultum { get { return DalSic.ConConsultum.FetchByID(this.IdConsulta); } set { SetColumnValue("idConsulta", value.IdConsulta); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varIdEfector,int? varIdConsulta,bool? varPrincipal,int? varCODCIE10,int varPrimerConsulta,int? varIdNivelDeAbordaje,int? varIdTipoPrestacionSaludMental,int? varIdTiempoInsumido,int? varIdDemanda,string varRecursoHumano) { ConConsultaDiagnostico item = new ConConsultaDiagnostico(); item.IdEfector = varIdEfector; item.IdConsulta = varIdConsulta; item.Principal = varPrincipal; item.CODCIE10 = varCODCIE10; item.PrimerConsulta = varPrimerConsulta; item.IdNivelDeAbordaje = varIdNivelDeAbordaje; item.IdTipoPrestacionSaludMental = varIdTipoPrestacionSaludMental; item.IdTiempoInsumido = varIdTiempoInsumido; item.IdDemanda = varIdDemanda; item.RecursoHumano = varRecursoHumano; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdConsultaDiagnostico,int? varIdEfector,int? varIdConsulta,bool? varPrincipal,int? varCODCIE10,int varPrimerConsulta,int? varIdNivelDeAbordaje,int? varIdTipoPrestacionSaludMental,int? varIdTiempoInsumido,int? varIdDemanda,string varRecursoHumano) { ConConsultaDiagnostico item = new ConConsultaDiagnostico(); item.IdConsultaDiagnostico = varIdConsultaDiagnostico; item.IdEfector = varIdEfector; item.IdConsulta = varIdConsulta; item.Principal = varPrincipal; item.CODCIE10 = varCODCIE10; item.PrimerConsulta = varPrimerConsulta; item.IdNivelDeAbordaje = varIdNivelDeAbordaje; item.IdTipoPrestacionSaludMental = varIdTipoPrestacionSaludMental; item.IdTiempoInsumido = varIdTiempoInsumido; item.IdDemanda = varIdDemanda; item.RecursoHumano = varRecursoHumano; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdConsultaDiagnosticoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdConsultaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn PrincipalColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn CODCIE10Column { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn PrimerConsultaColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdNivelDeAbordajeColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdTipoPrestacionSaludMentalColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn IdTiempoInsumidoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn IdDemandaColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn RecursoHumanoColumn { get { return Schema.Columns[10]; } } #endregion #region Columns Struct public struct Columns { public static string IdConsultaDiagnostico = @"idConsultaDiagnostico"; public static string IdEfector = @"idEfector"; public static string IdConsulta = @"idConsulta"; public static string Principal = @"principal"; public static string CODCIE10 = @"CODCIE10"; public static string PrimerConsulta = @"PrimerConsulta"; public static string IdNivelDeAbordaje = @"idNivelDeAbordaje"; public static string IdTipoPrestacionSaludMental = @"idTipoPrestacionSaludMental"; public static string IdTiempoInsumido = @"idTiempoInsumido"; public static string IdDemanda = @"idDemanda"; public static string RecursoHumano = @"RecursoHumano"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using BLToolkit.Common; namespace BLToolkit.Aspects { public delegate bool IsCacheableParameterType(Type parameterType); /// <summary> /// http://www.bltoolkit.net/Doc/Aspects/index.htm /// </summary> [System.Diagnostics.DebuggerStepThrough] public class CacheAspect : Interceptor { #region Init public CacheAspect() { _registeredAspects.Add(this); } private MethodInfo _methodInfo; private int? _instanceMaxCacheTime; private bool? _instanceIsWeak; // BVChanges: adding _object field private object _object; public override void Init(CallMethodInfo info, string configString) { base.Init(info, configString); info.CacheAspect = this; _methodInfo = info.MethodInfo; string[] ps = configString.Split(';'); foreach (string p in ps) { string[] vs = p.Split('='); if (vs.Length == 2) { switch (vs[0].ToLower().Trim()) { case "maxcachetime": _instanceMaxCacheTime = int. Parse(vs[1].Trim()); break; case "isweak": _instanceIsWeak = bool.Parse(vs[1].Trim()); break; } } } } private static readonly IList _registeredAspects = ArrayList.Synchronized(new ArrayList()); private static IList RegisteredAspects { get { return _registeredAspects; } } public static CacheAspect GetAspect(MethodInfo methodInfo) { lock (RegisteredAspects.SyncRoot) foreach (CacheAspect aspect in RegisteredAspects) if (aspect._methodInfo == methodInfo) return aspect; return null; } #endregion #region Overrides protected override void BeforeCall(InterceptCallInfo info) { if (!IsEnabled) return; IDictionary cache = Cache; lock (cache.SyncRoot) { CompoundValue key = GetKey(info); CacheAspectItem item = GetItem(cache, key); if (item != null && !item.IsExpired) { info.InterceptResult = InterceptResult.Return; info.ReturnValue = item.ReturnValue; if (item.RefValues != null) { ParameterInfo[] pis = info.CallMethodInfo.Parameters; int n = 0; for (int i = 0; i < pis.Length; i++) if (pis[i].ParameterType.IsByRef) info.ParameterValues[i] = item.RefValues[n++]; } info.Cached = true; } else { info.Items["CacheKey"] = key; } } } protected override void AfterCall(InterceptCallInfo info) { if (!IsEnabled) return; IDictionary cache = Cache; lock (cache.SyncRoot) { _object = info.Object; // BVChanges: adding _object field CompoundValue key = (CompoundValue)info.Items["CacheKey"]; if (key == null) return; int maxCacheTime = _instanceMaxCacheTime ?? MaxCacheTime; bool isWeak = _instanceIsWeak ?? IsWeak; CacheAspectItem item = new CacheAspectItem(); item.ReturnValue = info.ReturnValue; item.MaxCacheTime = maxCacheTime == int.MaxValue || maxCacheTime < 0? DateTime.MaxValue: DateTime.Now.AddMilliseconds(maxCacheTime); ParameterInfo[] pis = info.CallMethodInfo.Parameters; int n = 0; foreach (ParameterInfo pi in pis) if (pi.ParameterType.IsByRef) n++; if (n > 0) { item.RefValues = new object[n]; n = 0; for (int i = 0; i < pis.Length; i++) if (pis[i].ParameterType.IsByRef) item.RefValues[n++] = info.ParameterValues[i]; } cache[key] = isWeak? (object)new WeakReference(item): item; } } #endregion #region Global Parameters private static bool _isEnabled = true; public static bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; } } private static int _maxCacheTime = int.MaxValue; public static int MaxCacheTime { get { return _maxCacheTime; } set { _maxCacheTime = value; } } private static bool _isWeak; public static bool IsWeak { get { return _isWeak; } set { _isWeak = value; } } #endregion #region IsCacheableParameterType private static IsCacheableParameterType _isCacheableParameterType = IsCacheableParameterTypeInternal; public static IsCacheableParameterType IsCacheableParameterType { get { return _isCacheableParameterType; } set { _isCacheableParameterType = value ?? IsCacheableParameterTypeInternal; } } private static bool IsCacheableParameterTypeInternal(Type parameterType) { return parameterType.IsValueType || parameterType == typeof(string); } #endregion #region Cache private IDictionary _cache; public IDictionary Cache { get { return _cache ?? (_cache = CreateCache()); } } protected virtual CacheAspectItem CreateCacheItem(InterceptCallInfo info) { return new CacheAspectItem(); } protected virtual IDictionary CreateCache() { return Hashtable.Synchronized(new Hashtable()); } // BVChanges: static -> virtual protected /*static*/ virtual CompoundValue GetKey(InterceptCallInfo info) { ParameterInfo[] parInfo = info.CallMethodInfo.Parameters; object[] parValues = info.ParameterValues; object[] keyValues = new object[parValues.Length]; bool[] cacheParams = info.CallMethodInfo.CacheableParameters; if (cacheParams == null) { info.CallMethodInfo.CacheableParameters = cacheParams = new bool[parInfo.Length]; for (int i = 0; i < parInfo.Length; i++) cacheParams[i] = IsCacheableParameterType(parInfo[i].ParameterType); } for (int i = 0; i < parValues.Length; i++) keyValues[i] = cacheParams[i] ? parValues[i] : null; return new CompoundValue(keyValues); } protected static CacheAspectItem GetItem(IDictionary cache, CompoundValue key) { object obj = cache[key]; if (obj == null) return null; WeakReference wr = obj as WeakReference; if (wr == null) return (CacheAspectItem)obj; obj = wr.Target; if (obj != null) return (CacheAspectItem)obj; cache.Remove(key); return null; } /// <summary> /// Clear a method call cache. /// </summary> /// <param name="methodInfo">The <see cref="MethodInfo"/> representing cached method.</param> public static void ClearCache(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); CacheAspect aspect = GetAspect(methodInfo); if (aspect != null) CleanupThread.ClearCache(aspect.Cache); } // BVChanges: ClearAllCache begin public static void ClearAllCache(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); lock (RegisteredAspects.SyncRoot) { foreach (CacheAspect aspect in RegisteredAspects) { if (aspect._methodInfo == methodInfo) { CleanupThread.ClearCache(aspect.Cache); } } } } // BVChanges: ClearAllCache end /// <summary> /// Clear a method call cache. /// </summary> /// <param name="declaringType">The method declaring type.</param> /// <param name="methodName">The method name.</param> /// <param name="types">An array of <see cref="System.Type"/> objects representing /// the number, order, and type of the parameters for the method to get.-or- /// An empty array of the type <see cref="System.Type"/> (for example, <see cref="System.Type.EmptyTypes"/>) /// to get a method that takes no parameters.</param> public static void ClearCache(Type declaringType, string methodName, params Type[] types) { ClearCache(GetMethodInfo(declaringType, methodName, types)); } public static void ClearCache(Type declaringType) { if (declaringType == null) throw new ArgumentNullException("declaringType"); if (declaringType.IsAbstract) declaringType = TypeBuilder.TypeFactory.GetType(declaringType); lock (RegisteredAspects.SyncRoot) foreach (CacheAspect aspect in RegisteredAspects) if (aspect._methodInfo.DeclaringType == declaringType) CleanupThread.ClearCache(aspect.Cache); } // BVChanges: adding ClearCache public static void ClearCache(Type declaringType, object accessor) { if (declaringType == null) throw new ArgumentNullException("declaringType"); if (declaringType.IsAbstract) declaringType = TypeBuilder.TypeFactory.GetType(declaringType); lock (RegisteredAspects.SyncRoot) foreach (CacheAspect aspect in RegisteredAspects) if (aspect._methodInfo.DeclaringType == declaringType) if (aspect._object == accessor) CleanupThread.ClearCache(aspect.Cache); } public static MethodInfo GetMethodInfo(Type declaringType, string methodName, params Type[] parameterTypes) { if (declaringType == null) throw new ArgumentNullException("declaringType"); if (declaringType.IsAbstract) declaringType = TypeBuilder.TypeFactory.GetType(declaringType); if (parameterTypes == null) parameterTypes = Type.EmptyTypes; MethodInfo methodInfo = declaringType.GetMethod( methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null); if (methodInfo == null) { methodInfo = declaringType.GetMethod( methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null) throw new ArgumentException(string.Format("Method '{0}.{1}' not found.", declaringType.FullName, methodName)); } return methodInfo; } /// <summary> /// Clear all cached method calls. /// </summary> public static void ClearCache() { CleanupThread.ClearCache(); } #endregion #region Cleanup Thread public class CleanupThread { private CleanupThread() {} internal static void Init() { AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; Start(); } static void CurrentDomain_DomainUnload(object sender, EventArgs e) { Stop(); } static Timer _timer; static readonly object _syncTimer = new object(); private static void Start() { if (_timer == null) lock (_syncTimer) if (_timer == null) { TimeSpan interval = TimeSpan.FromSeconds(10); _timer = new Timer(Cleanup, null, interval, interval); } } private static void Stop() { if (_timer != null) lock (_syncTimer) if (_timer != null) { _timer.Dispose(); _timer = null; } } private static void Cleanup(object state) { if (!Monitor.TryEnter(RegisteredAspects.SyncRoot, 10)) { // The Cache is busy, skip this turn. // return; } DateTime start = DateTime.Now; int objectsInCache = 0; try { _workTimes++; List<DictionaryEntry> list = new List<DictionaryEntry>(); foreach (CacheAspect aspect in RegisteredAspects) { IDictionary cache = aspect.Cache; lock (cache.SyncRoot) { foreach (DictionaryEntry de in cache) { WeakReference wr = de.Value as WeakReference; bool isExpired; if (wr != null) { CacheAspectItem ca = wr.Target as CacheAspectItem; isExpired = ca == null || ca.IsExpired; } else { isExpired = ((CacheAspectItem)de.Value).IsExpired; } if (isExpired) list.Add(de); } foreach (DictionaryEntry de in list) { cache.Remove(de.Key); _objectsExpired++; } list.Clear(); objectsInCache += cache.Count; } } _objectsInCache = objectsInCache; } finally { _workTime += DateTime.Now - start; Monitor.Exit(RegisteredAspects.SyncRoot); } } private static int _workTimes; public static int WorkTimes { get { return _workTimes; } } private static TimeSpan _workTime; public static TimeSpan WorkTime { get { return _workTime; } } private static int _objectsExpired; public static int ObjectsExpired { get { return _objectsExpired; } } private static int _objectsInCache; public static int ObjectsInCache { get { return _objectsInCache; } } public static void UnregisterCache(IDictionary cache) { lock (RegisteredAspects.SyncRoot) RegisteredAspects.Remove(cache); } public static void ClearCache(IDictionary cache) { lock (RegisteredAspects.SyncRoot) lock (cache.SyncRoot) { _objectsExpired += cache.Count; cache.Clear(); } } public static void ClearCache() { lock (RegisteredAspects.SyncRoot) { foreach (CacheAspect aspect in RegisteredAspects) { _objectsExpired += aspect.Cache.Count; aspect.Cache.Clear(); } } } } static CacheAspect() { CleanupThread.Init(); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Unmanaged { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Apache.Ignite.Core.Common; using JNI = IgniteJniNativeMethods; /// <summary> /// Unmanaged utility classes. /// </summary> internal static unsafe class UnmanagedUtils { /** Interop factory ID for .Net. */ private const int InteropFactoryId = 1; /// <summary> /// Initializer. /// </summary> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] static UnmanagedUtils() { var platform = Environment.Is64BitProcess ? "x64" : "x86"; var resName = string.Format("{0}.{1}", platform, IgniteUtils.FileIgniteJniDll); var path = IgniteUtils.UnpackEmbeddedResource(resName, IgniteUtils.FileIgniteJniDll); var ptr = NativeMethods.LoadLibrary(path); if (ptr == IntPtr.Zero) { var err = Marshal.GetLastWin32Error(); throw new IgniteException(string.Format("Failed to load {0} from {1}: [{2}]", IgniteUtils.FileIgniteJniDll, path, IgniteUtils.FormatWin32Error(err))); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; JNI.SetConsoleHandler(UnmanagedCallbacks.ConsoleWriteHandler); } /// <summary> /// Handles the DomainUnload event of the current AppDomain. /// </summary> private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { // Clean the handler to avoid JVM crash. var removedCnt = JNI.RemoveConsoleHandler(UnmanagedCallbacks.ConsoleWriteHandler); Debug.Assert(removedCnt == 1); } /// <summary> /// No-op initializer used to force type loading and static constructor call. /// </summary> internal static void Initialize() { // No-op. } #region NATIVE METHODS: PROCESSOR internal static void IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName, bool clientMode, bool userLogger) { using (var mem = IgniteManager.Memory.Allocate().GetStream()) { mem.WriteBool(clientMode); mem.WriteBool(userLogger); sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath); sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { // OnStart receives the same InteropProcessor as here (just as another GlobalRef) and stores it. // Release current reference immediately. void* res = JNI.IgnitionStart(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId, mem.SynchronizeOutput()); JNI.Release(res); } finally { Marshal.FreeHGlobal(new IntPtr(cfgPath0)); Marshal.FreeHGlobal(new IntPtr(gridName0)); } } } internal static bool IgnitionStop(void* ctx, string gridName, bool cancel) { sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { return JNI.IgnitionStop(ctx, gridName0, cancel); } finally { Marshal.FreeHGlobal(new IntPtr(gridName0)); } } internal static void IgnitionStopAll(void* ctx, bool cancel) { JNI.IgnitionStopAll(ctx, cancel); } internal static void ProcessorReleaseStart(IUnmanagedTarget target) { JNI.ProcessorReleaseStart(target.Context, target.Target); } internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target) { void* res = JNI.ProcessorProjection(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorCache(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorCreateCache(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, long memPtr) { void* res = JNI.ProcessorCreateCacheFromConfig(target.Context, target.Target, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorGetOrCreateCache(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, long memPtr) { void* res = JNI.ProcessorGetOrCreateCacheFromConfig(target.Context, target.Target, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCreateNearCache(IUnmanagedTarget target, string name, long memPtr) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorCreateNearCache(target.Context, target.Target, name0, memPtr); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorGetOrCreateNearCache(IUnmanagedTarget target, string name, long memPtr) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorGetOrCreateNearCache(target.Context, target.Target, name0, memPtr); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static void ProcessorDestroyCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { JNI.ProcessorDestroyCache(target.Context, target.Target, name0); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorAffinity(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepBinary) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = JNI.ProcessorDataStreamer(target.Context, target.Target, name0, keepBinary); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target) { void* res = JNI.ProcessorTransactions(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = JNI.ProcessorCompute(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = JNI.ProcessorMessage(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = JNI.ProcessorEvents(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = JNI.ProcessorServices(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target) { void* res = JNI.ProcessorExtensions(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorExtension(IUnmanagedTarget target, int id) { void* res = JNI.ProcessorExtension(target.Context, target.Target, id); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorAtomicLong(IUnmanagedTarget target, string name, long initialValue, bool create) { var name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { var res = JNI.ProcessorAtomicLong(target.Context, target.Target, name0, initialValue, create); return res == null ? null : target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorAtomicSequence(IUnmanagedTarget target, string name, long initialValue, bool create) { var name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { var res = JNI.ProcessorAtomicSequence(target.Context, target.Target, name0, initialValue, create); return res == null ? null : target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorAtomicReference(IUnmanagedTarget target, string name, long memPtr, bool create) { var name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { var res = JNI.ProcessorAtomicReference(target.Context, target.Target, name0, memPtr, create); return res == null ? null : target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static void ProcessorGetIgniteConfiguration(IUnmanagedTarget target, long memPtr) { JNI.ProcessorGetIgniteConfiguration(target.Context, target.Target, memPtr); } internal static void ProcessorGetCacheNames(IUnmanagedTarget target, long memPtr) { JNI.ProcessorGetCacheNames(target.Context, target.Target, memPtr); } internal static bool ProcessorLoggerIsLevelEnabled(IUnmanagedTarget target, int level) { return JNI.ProcessorLoggerIsLevelEnabled(target.Context, target.Target, level); } internal static void ProcessorLoggerLog(IUnmanagedTarget target, int level, string message, string category, string errorInfo) { var message0 = IgniteUtils.StringToUtf8Unmanaged(message); var category0 = IgniteUtils.StringToUtf8Unmanaged(category); var errorInfo0 = IgniteUtils.StringToUtf8Unmanaged(errorInfo); try { JNI.ProcessorLoggerLog(target.Context, target.Target, level, message0, category0, errorInfo0); } finally { Marshal.FreeHGlobal(new IntPtr(message0)); Marshal.FreeHGlobal(new IntPtr(category0)); Marshal.FreeHGlobal(new IntPtr(errorInfo0)); } } internal static IUnmanagedTarget ProcessorBinaryProcessor(IUnmanagedTarget target) { void* res = JNI.ProcessorBinaryProcessor(target.Context, target.Target); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: TARGET internal static long TargetInLongOutLong(IUnmanagedTarget target, int opType, long memPtr) { return JNI.TargetInLongOutLong(target.Context, target.Target, opType, memPtr); } internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr) { return JNI.TargetInStreamOutLong(target.Context, target.Target, opType, memPtr); } internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr) { JNI.TargetInStreamOutStream(target.Context, target.Target, opType, inMemPtr, outMemPtr); } internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr) { void* res = JNI.TargetInStreamOutObject(target.Context, target.Target, opType, inMemPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget TargetInObjectStreamOutObjectStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr) { void* res = JNI.TargetInObjectStreamOutObjectStream(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr); if (res == null) return null; return target.ChangeTarget(res); } internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr) { JNI.TargetOutStream(target.Context, target.Target, opType, memPtr); } internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType) { void* res = JNI.TargetOutObject(target.Context, target.Target, opType); return target.ChangeTarget(res); } internal static void TargetInStreamAsync(IUnmanagedTarget target, int opType, long memPtr) { JNI.TargetInStreamAsync(target.Context, target.Target, opType, memPtr); } #endregion #region NATIVE METHODS: MISCELANNEOUS internal static void Reallocate(long memPtr, int cap) { int res = JNI.Reallocate(memPtr, cap); if (res != 0) throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr + ", capacity=" + cap + ']'); } internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target) { void* target0 = JNI.Acquire(ctx.NativeContext, target); return new UnmanagedTarget(ctx, target0); } internal static void Release(IUnmanagedTarget target) { JNI.Release(target.Target); } internal static void ThrowToJava(void* ctx, Exception e) { char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message); try { JNI.ThrowToJava(ctx, msgChars); } finally { Marshal.FreeHGlobal(new IntPtr(msgChars)); } } internal static int HandlersSize() { return JNI.HandlersSize(); } internal static void* CreateContext(void* opts, int optsLen, void* cbs) { return JNI.CreateContext(opts, optsLen, cbs); } internal static void DeleteContext(void* ctx) { JNI.DeleteContext(ctx); } internal static void DestroyJvm(void* ctx) { JNI.DestroyJvm(ctx); } #endregion } }
using UnityEngine; using System.Collections.Generic; public class MegaCacheMatFaces { public List<int> tris = new List<int>(); } public class MegaCacheFace { public MegaCacheFace(Vector3 _v0, Vector3 _v1, Vector3 _v2, Vector3 _n0, Vector3 _n1, Vector3 _n2, Vector2 _uv0, Vector2 _uv1, Vector2 _uv2, int _sg, int _mid) { v30 = _v0; v31 = _v1; v32 = _v2; uv0 = _uv0; uv1 = _uv1; uv2 = _uv2; n0 = _n0; n1 = _n1; n2 = _n2; smthgrp = _sg; mtlid = _mid; } public int v0,v1,v2; public Vector3 v30; public Vector3 v31; public Vector3 v32; public Vector3 n0 = Vector3.zero; public Vector3 n1 = Vector3.zero; public Vector3 n2 = Vector3.zero; public Vector2 uv0; public Vector2 uv1; public Vector2 uv2; public Vector2 uv10; public Vector2 uv11; public Vector2 uv12; public Color col1; public Color col2; public Color col3; public int smthgrp; public int mtlid; public Vector3 faceNormal = Vector3.zero; public int t0,t1,t2; } public class MegaCacheMeshConstructor { static public List<Vector3> verts = new List<Vector3>(); static public List<Vector3> norms = new List<Vector3>(); static public List<Vector2> uvs = new List<Vector2>(); static public List<int> tris = new List<int>(); static public List<MegaCacheMatFaces> matfaces = new List<MegaCacheMatFaces>(); public class MegaCacheFaceGrid { public List<int> verts = new List<int>(); } static public MegaCacheFaceGrid[,,] checkgrid; static public Vector3 min; static public Vector3 max; static public Vector3 size; static public int subdivs = 16; //16; static public void BuildGrid(Vector3[] verts) { checkgrid = new MegaCacheFaceGrid[subdivs, subdivs, subdivs]; min = verts[0]; max = verts[0]; for ( int i = 1; i < verts.Length; i++ ) { Vector3 p = verts[i]; if ( p.x < min.x ) min.x = p.x; if ( p.x > max.x ) max.x = p.x; if ( p.y < min.y ) min.y = p.y; if ( p.y > max.y ) max.y = p.y; if ( p.z < min.z ) min.z = p.z; if ( p.z > max.z ) max.z = p.z; } size = max - min; } static public void BuildTangents(Mesh mesh) { int triangleCount = mesh.triangles.Length; int vertexCount = mesh.vertices.Length; Vector3[] tan1 = new Vector3[vertexCount]; Vector3[] tan2 = new Vector3[vertexCount]; Vector4[] tangents = new Vector4[vertexCount]; Vector3[] verts = mesh.vertices; Vector2[] uvs = mesh.uv; Vector3[] norms = mesh.normals; int[] tris = mesh.triangles; if ( uvs.Length > 0 ) { for ( int a = 0; a < triangleCount; a += 3 ) { long i1 = tris[a]; long i2 = tris[a + 1]; long i3 = tris[a + 2]; Vector3 v1 = verts[i1]; Vector3 v2 = verts[i2]; Vector3 v3 = verts[i3]; Vector2 w1 = uvs[i1]; Vector2 w2 = uvs[i2]; Vector2 w3 = uvs[i3]; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float r = 1.0f / (s1 * t2 - s2 * t1); Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for ( int a = 0; a < vertexCount; a++ ) { Vector3 n = norms[a].normalized; Vector3 t = tan1[a].normalized; Vector3.OrthoNormalize(ref n, ref t); tangents[a].x = t.x; tangents[a].y = t.y; tangents[a].z = t.z; tangents[a].w = (Vector3.Dot(Vector3.Cross(n, t), tan2[a]) < 0.0f) ? -1.0f : 1.0f; tangents[a] = tangents[a].normalized; } mesh.tangents = tangents; } } } public class MegaCacheMeshConstructorOBJ : MegaCacheMeshConstructor { static int FindVertGrid(Vector3 p, Vector3 n, Vector2 uv) { int sd = subdivs - 1; int gx = 0; int gy = 0; int gz = 0; if ( size.x > 0.0f ) gx = (int)(sd * ((p.x - min.x) / size.x)); if ( size.y > 0.0f ) gy = (int)(sd * ((p.y - min.y) / size.y)); if ( size.z > 0.0f ) gz = (int)(sd * ((p.z - min.z) / size.z)); MegaCacheFaceGrid fg = checkgrid[gx, gy, gz]; if ( fg == null ) { fg = new MegaCacheFaceGrid(); checkgrid[gx, gy, gz] = fg; } for ( int i = 0; i < fg.verts.Count; i++ ) { int ix = fg.verts[i]; if ( verts[ix].x == p.x && verts[ix].y == p.y && verts[ix].z == p.z ) { if ( norms[ix].x == n.x && norms[ix].y == n.y && norms[ix].z == n.z ) { if ( uvs[ix].x == uv.x && uvs[ix].y == uv.y ) return ix; } } } fg.verts.Add(verts.Count); verts.Add(p); norms.Add(n); uvs.Add(uv); return verts.Count - 1; } static public void Construct(List<MegaCacheFace> faces, Mesh mesh, Vector3[] meshverts, bool optimize, bool recalc, bool tangents) { mesh.Clear(); if ( meshverts == null || meshverts.Length == 0 || faces.Count == 0 ) return; verts.Clear(); norms.Clear(); uvs.Clear(); tris.Clear(); matfaces.Clear(); BuildGrid(meshverts); int maxmat = 0; for ( int i = 0; i < faces.Count; i++ ) { if ( faces[i].mtlid > maxmat ) maxmat = faces[i].mtlid; } maxmat++; for ( int i = 0; i < maxmat; i++ ) matfaces.Add(new MegaCacheMatFaces()); for ( int i = 0; i < faces.Count; i++ ) { int mtlid = faces[i].mtlid; int v0 = FindVertGrid(faces[i].v30, faces[i].n0, faces[i].uv0); int v1 = FindVertGrid(faces[i].v31, faces[i].n1, faces[i].uv1); int v2 = FindVertGrid(faces[i].v32, faces[i].n2, faces[i].uv2); matfaces[mtlid].tris.Add(v0); matfaces[mtlid].tris.Add(v1); matfaces[mtlid].tris.Add(v2); } mesh.vertices = verts.ToArray(); mesh.subMeshCount = matfaces.Count; if ( recalc ) mesh.RecalculateNormals(); else mesh.normals = norms.ToArray(); mesh.uv = uvs.ToArray(); for ( int i = 0; i < matfaces.Count; i++ ) mesh.SetTriangles(matfaces[i].tris.ToArray(), i); if ( tangents ) BuildTangents(mesh); if ( optimize ) ; mesh.RecalculateBounds(); checkgrid = null; } } public class MegaCacheMeshConstructorOBJNoUV : MegaCacheMeshConstructor { static int FindVertGrid(Vector3 p, Vector3 n) { int sd = subdivs - 1; int gx = 0; int gy = 0; int gz = 0; if ( size.x > 0.0f ) gx = (int)(sd * ((p.x - min.x) / size.x)); if ( size.y > 0.0f ) gy = (int)(sd * ((p.y - min.y) / size.y)); if ( size.z > 0.0f ) gz = (int)(sd * ((p.z - min.z) / size.z)); MegaCacheFaceGrid fg = checkgrid[gx, gy, gz]; if ( fg == null ) { fg = new MegaCacheFaceGrid(); checkgrid[gx, gy, gz] = fg; } for ( int i = 0; i < fg.verts.Count; i++ ) { int ix = fg.verts[i]; if ( verts[ix].x == p.x && verts[ix].y == p.y && verts[ix].z == p.z ) { if ( norms[ix].x == n.x && norms[ix].y == n.y && norms[ix].z == n.z ) return ix; } } fg.verts.Add(verts.Count); verts.Add(p); norms.Add(n); return verts.Count - 1; } static public void Construct(List<MegaCacheFace> faces, Mesh mesh, Vector3[] meshverts, bool optimize, bool recalc, bool tangents) { mesh.Clear(); if ( meshverts == null || meshverts.Length == 0 || faces.Count == 0 ) return; verts.Clear(); norms.Clear(); tris.Clear(); matfaces.Clear(); BuildGrid(meshverts); int maxmat = 0; for ( int i = 0; i < faces.Count; i++ ) { if ( faces[i].mtlid > maxmat ) maxmat = faces[i].mtlid; } maxmat++; for ( int i = 0; i < maxmat; i++ ) { matfaces.Add(new MegaCacheMatFaces()); } for ( int i = 0; i < faces.Count; i++ ) { int mtlid = faces[i].mtlid; int v0 = FindVertGrid(faces[i].v30, faces[i].n0); int v1 = FindVertGrid(faces[i].v31, faces[i].n1); int v2 = FindVertGrid(faces[i].v32, faces[i].n2); matfaces[mtlid].tris.Add(v0); matfaces[mtlid].tris.Add(v1); matfaces[mtlid].tris.Add(v2); } mesh.vertices = verts.ToArray(); mesh.subMeshCount = matfaces.Count; if ( recalc ) mesh.RecalculateNormals(); else mesh.normals = norms.ToArray(); for ( int i = 0; i < matfaces.Count; i++ ) mesh.SetTriangles(matfaces[i].tris.ToArray(), i); if ( tangents ) BuildTangents(mesh); if ( optimize ) ; mesh.RecalculateBounds(); checkgrid = null; } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> #region using System; using System.Diagnostics; #endregion namespace Aphysoft.Share.Html { /// <summary> /// Represents an HTML attribute. /// </summary> [DebuggerDisplay("Name: {OriginalName}, Value: {Value}")] public class HtmlAttribute : IComparable { #region Fields private int _line; internal int _lineposition; internal string _name; internal int _namelength; internal int _namestartindex; internal HtmlDocument _ownerdocument; // attribute can exists without a node internal HtmlNode _ownernode; private AttributeValueQuote _quoteType = AttributeValueQuote.DoubleQuote; internal int _streamposition; internal string _value; internal int _valuelength; internal int _valuestartindex; #endregion #region Constructors internal HtmlAttribute(HtmlDocument ownerdocument) { _ownerdocument = ownerdocument; } #endregion #region Properties /// <summary> /// Gets the line number of this attribute in the document. /// </summary> public int Line { get { return _line; } internal set { _line = value; } } /// <summary> /// Gets the column number of this attribute in the document. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the qualified name of the attribute. /// </summary> public string Name { get { if (_name == null) { _name = _ownerdocument._text.Substring(_namestartindex, _namelength); } return _name.ToLower(); } set { if (value == null) { throw new ArgumentNullException("value"); } _name = value; if (_ownernode != null) { _ownernode._innerchanged = true; _ownernode._outerchanged = true; } } } /// <summary> /// Name of attribute with original case /// </summary> public string OriginalName { get { return _name; } } /// <summary> /// Gets the HTML document to which this attribute belongs. /// </summary> public HtmlDocument OwnerDocument { get { return _ownerdocument; } } /// <summary> /// Gets the HTML node to which this attribute belongs. /// </summary> public HtmlNode OwnerNode { get { return _ownernode; } } /// <summary> /// Specifies what type of quote the data should be wrapped in /// </summary> public AttributeValueQuote QuoteType { get { return _quoteType; } set { _quoteType = value; } } /// <summary> /// Gets the stream position of this attribute in the document, relative to the start of the document. /// </summary> public int StreamPosition { get { return _streamposition; } } /// <summary> /// Gets or sets the value of the attribute. /// </summary> public string Value { get { if (_value == null) { _value = _ownerdocument._text.Substring(_valuestartindex, _valuelength); } return _value; } set { _value = value; if (_ownernode != null) { _ownernode._innerchanged = true; _ownernode._outerchanged = true; } } } internal string XmlName { get { return HtmlDocument.GetXmlName(Name); } } internal string XmlValue { get { return Value; } } /// <summary> /// Gets a valid XPath string that points to this Attribute /// </summary> public string XPath { get { string basePath = (OwnerNode == null) ? "/" : OwnerNode.XPath + "/"; return basePath + GetRelativeXpath(); } } #endregion #region IComparable Members /// <summary> /// Compares the current instance with another attribute. Comparison is based on attributes' name. /// </summary> /// <param name="obj">An attribute to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the names comparison.</returns> public int CompareTo(object obj) { HtmlAttribute att = obj as HtmlAttribute; if (att == null) { throw new ArgumentException("obj"); } return Name.CompareTo(att.Name); } #endregion #region Public Methods /// <summary> /// Creates a duplicate of this attribute. /// </summary> /// <returns>The cloned attribute.</returns> public HtmlAttribute Clone() { HtmlAttribute att = new HtmlAttribute(_ownerdocument); att.Name = Name; att.Value = Value; return att; } /// <summary> /// Removes this attribute from it's parents collection /// </summary> public void Remove() { _ownernode.Attributes.Remove(this); } #endregion #region Private Methods private string GetRelativeXpath() { if (OwnerNode == null) return Name; int i = 1; foreach (HtmlAttribute node in OwnerNode.Attributes) { if (node.Name != Name) continue; if (node == this) break; i++; } return "@" + Name + "[" + i + "]"; } #endregion } /// <summary> /// An Enum representing different types of Quotes used for surrounding attribute values /// </summary> public enum AttributeValueQuote { /// <summary> /// A single quote mark ' /// </summary> SingleQuote, /// <summary> /// A double quote mark " /// </summary> DoubleQuote } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; public class Stringmm { public static int size; public static Random rand; public static void InitMatrix2D(out String[,] m, out String[][] refm) { int i, j, temp; i = 0; m = new String[size, size]; refm = new String[size][]; for (int k = 0; k < refm.Length; k++) refm[k] = new String[size]; while (i < size) { j = 0; while (j < size) { temp = rand.Next(); temp = temp - (temp / 120) * 120 - 60; m[i, j] = Convert.ToString(temp); refm[i][j] = Convert.ToString(temp); j++; } i++; } } public static void InnerProduct2D(out String res, ref String[,] a, ref String[,] b, int row, int col) { int i; res = ""; int temp1, temp2, temp3; temp3 = 0; i = 0; while (i < size) { temp1 = Convert.ToInt32(a[row, i]); temp2 = Convert.ToInt32(b[i, col]); temp3 = temp3 + temp1 * temp2; res = Convert.ToString(temp3); i++; } } public static void InnerProduct2DRef(out String res, ref String[][] a, ref String[][] b, int row, int col) { int i; res = ""; int temp1, temp2, temp3; temp3 = 0; i = 0; while (i < size) { temp1 = Convert.ToInt32(a[row][i]); temp2 = Convert.ToInt32(b[i][col]); temp3 = temp3 + temp1 * temp2; res = Convert.ToString(temp3); i++; } } public static void Init3DMatrix(String[,,] m, String[][] refm) { int i, j, temp; i = 0; while (i < size) { j = 0; while (j < size) { temp = rand.Next(); temp = temp - (temp / 120) * 120 - 60; m[i, 0, j] = Convert.ToString(temp); refm[i][j] = Convert.ToString(temp); j++; } i++; } } public static void InnerProduct3D(out String res, String[,,] a, String[,,] b, int row, int col) { int i; res = ""; int temp1, temp2, temp3; temp3 = 0; i = 0; while (i < size) { temp1 = Convert.ToInt32(a[row, 0, i]); temp2 = Convert.ToInt32(b[i, 0, col]); temp3 = temp3 + temp1 * temp2; res = Convert.ToString(temp3); i++; } } public static void InnerProduct3DRef(out String res, String[][] a, String[][] b, int row, int col) { int i; res = ""; int temp1, temp2, temp3; temp3 = 0; i = 0; while (i < size) { temp1 = Convert.ToInt32(a[row][i]); temp2 = Convert.ToInt32(b[i][col]); temp3 = temp3 + temp1 * temp2; res = Convert.ToString(temp3); i++; } } public static int Main() { bool pass = false; rand = new Random(); size = rand.Next(2, 10); Console.WriteLine(); Console.WriteLine("2D Array"); Console.WriteLine("Testing inner product of {0} by {0} matrices", size); Console.WriteLine("Matrix element stores string data converted from random integer"); Console.WriteLine("array set/get, ref/out param are used"); String[,] ima2d = new String[size, size]; String[,] imb2d = new String[size, size]; String[,] imr2d = new String[size, size]; String[][] refa2d = new String[size][]; String[][] refb2d = new String[size][]; String[][] refr2d = new String[size][]; for (int k = 0; k < refr2d.Length; k++) refr2d[k] = new String[size]; InitMatrix2D(out ima2d, out refa2d); InitMatrix2D(out imb2d, out refb2d); int m = 0; int n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct2D(out imr2d[m, n], ref ima2d, ref imb2d, m, n); InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr2d[i, j] != refr2d[i][j]) { Console.WriteLine("i={0}, j={1}, imr2d[i,j] {2}!=refr2d[i][j] {3}", i, j, imr2d[i, j], refr2d[i][j]); pass = false; } } Console.WriteLine(); Console.WriteLine("3D Array"); Console.WriteLine("Testing inner product of one slice of two 3D matrices"); Console.WriteLine("Matrix element stores string data converted from random integer"); String[,,] ima3d = new String[size, 2, size]; String[,,] imb3d = new String[size, 3, size]; String[,,] imr3d = new String[size, size, size]; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) imr3d[i, j, 0] = ""; String[][] refa3d = new String[size][]; String[][] refb3d = new String[size][]; String[][] refr3d = new String[size][]; for (int k = 0; k < refa3d.Length; k++) refa3d[k] = new String[size]; for (int k = 0; k < refb3d.Length; k++) refb3d[k] = new String[size]; for (int k = 0; k < refr3d.Length; k++) refr3d[k] = new String[size]; Init3DMatrix(ima3d, refa3d); Init3DMatrix(imb3d, refb3d); m = 0; n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct3D(out imr3d[m, n, 0], ima3d, imb3d, m, n); InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr3d[i, j, 0] != refr3d[i][j]) { Console.WriteLine("i={0}, j={1}, imr3d[i,j,0] {2}!=refr3d[i][j] {3}", i, j, imr3d[i, j, 0], refr3d[i][j]); pass = false; } } Console.WriteLine(); if (pass) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
//--------------------------------------------------------------------------- // // <copyright file="SaveFileDialog.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // SaveFileDialog is a sealed class derived from FileDialog that // implements File Save dialog-specific functions. It contains // the actual commdlg.dll call to GetSaveFileName() as well as // additional properties relevant only to save dialogs. // // // History: // t-benja 7/7/2005 Created // //--------------------------------------------------------------------------- namespace Microsoft.Win32 { using MS.Internal.AppModel; using MS.Internal.Interop; using MS.Internal.PresentationFramework; using MS.Win32; using System; using System.Collections.Generic; using System.IO; using System.Security; using System.Security.Permissions; using System.Windows; /// <summary> /// Represents a common dialog box that allows the user to specify options /// for saving a file. This class cannot be inherited. /// </summary> public sealed class SaveFileDialog : FileDialog { //--------------------------------------------------- // // Constructors // //--------------------------------------------------- #region Constructors // We add a constructor for our SaveFileDialog since we have // additional initialization tasks to do in addition to the // ones that FileDialog's constructor takes care of. /// <summary> /// Initializes a new instance of the SaveFileDialog class. /// </summary> /// <SecurityNote> /// Critical: Creates a dialog that can be used to open a file. /// PublicOk: It is okay to set the options to their defaults. The /// ctor does not show the dialog. /// </SecurityNote> [SecurityCritical] public SaveFileDialog() : base() { Initialize(); } #endregion Constructors //--------------------------------------------------- // // Public Methods // //--------------------------------------------------- #region Public Methods /// <summary> /// Opens the file selected by the user with read-only permission. /// </summary> /// The filename used to open the file is the first element of the /// FileNamesInternal array. /// <exception cref="System.InvalidOperationException"> /// Thrown if there are no filenames stored in the SaveFileDialog. /// </exception> /// <Remarks> /// Callers must have UIPermission.AllWindows to call this API. /// </Remarks> /// <SecurityNote> /// Critical: Opens files on the users machine. /// PublicOk: Demands UIPermission.AllWindows /// </SecurityNote> [SecurityCritical] public Stream OpenFile() { SecurityHelper.DemandUIWindowPermission(); // Extract the first filename from the FileNamesInternal list. // We can do this safely because FileNamesInternal never returns // null - if _fileNames is null, FileNamesInternal returns new string[0]; string filename = FileNamesInternal.Length > 0 ? FileNamesInternal[0] : null; // If we got an empty or null filename, throw an exception to // tell the user we don't have any files to open. if (String.IsNullOrEmpty(filename)) { throw new InvalidOperationException(SR.Get(SRID.FileNameMustNotBeNull)); } // Create a new FileStream from the file and return it. // in this case I deviate from the try finally protocol because this is the last statement and the permission is reverted // when the function exits (new FileIOPermission(FileIOPermissionAccess.Append | FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, filename)).Assert();//BlessedAssert return new FileStream(filename, FileMode.Create, FileAccess.ReadWrite); } // // We override the FileDialog implementation to set a default // for OFN_FILEMUSTEXIST in addition to the other option flags // defined in FileDialog. /// <summary> /// Resets all properties to their default values. /// </summary> /// <Remarks> /// Callers must have UIPermission.AllWindows to call this API. /// </Remarks> /// <SecurityNote> /// Critical: Calls base.Reset() and Initialize(), both of which are SecurityCritical /// PublicOk: Demands UIPermission.AllWindows /// </SecurityNote> [SecurityCritical] public override void Reset() { SecurityHelper.DemandUIWindowPermission(); // it is VERY important that the base.reset() call remain here // and be located at the top of this function. // Since most of the initialization for this class is actually // done in the FileDialog class, we must call that implementation // before we can finish with the Initialize() call specific to our // derived class. base.Reset(); Initialize(); } #endregion Public Methods //--------------------------------------------------- // // Public Properties // //--------------------------------------------------- #region Public Properties // OFN_CREATEPROMPT // If the user specifies a file that does not exist, this flag causes our code // to prompt the user for permission to create the file. If the user chooses // to create the file, the dialog box closes and the function returns the // specified name; otherwise, the dialog box remains open. // /// <summary> /// Gets or sets a value indicating whether the dialog box prompts the user for /// permission to create a file if the user specifies a file that does not exist. /// </summary> /// <Remarks> /// Callers must have UIPermission.AllWindows to call this API. /// </Remarks> /// <SecurityNote> /// Critical: We do not want a Partially trusted application to have the ability /// to disable this prompt. /// PublicOk: Demands UIPermission.AllWindows /// </SecurityNote> public bool CreatePrompt { get { return GetOption(NativeMethods.OFN_CREATEPROMPT); } [SecurityCritical] set { SecurityHelper.DemandUIWindowPermission(); SetOption(NativeMethods.OFN_CREATEPROMPT, value); } } // OFN_OVERWRITEPROMPT // Causes our code to generate a message box if the selected file already // exists. The user must confirm whether to overwrite the file. // /// <summary> /// Gets or sets a value indicating whether the Save As dialog box displays a /// warning if the user specifies a file name that already exists. /// </summary> /// <Remarks> /// Callers must have UIPermission.AllWindows to call this API. /// </Remarks> /// <SecurityNote> /// Critical: We do not want a Partially trusted application to have the ability /// to disable this prompt. /// PublicOk: Demands UIPermission.AllWindows /// </SecurityNote> public bool OverwritePrompt { get { return GetOption(NativeMethods.OFN_OVERWRITEPROMPT); } [SecurityCritical] set { SecurityHelper.DemandUIWindowPermission(); SetOption(NativeMethods.OFN_OVERWRITEPROMPT, value); } } #endregion Public Properties //--------------------------------------------------- // // Public Events // //--------------------------------------------------- //#region Public Events //#endregion Public Events //--------------------------------------------------- // // Protected Methods // //--------------------------------------------------- //#region Protected Methods //#endregion Protected Methods //--------------------------------------------------- // // Internal Methods // //--------------------------------------------------- #region Internal Methods /// <summary> /// PromptUserIfAppropriate overrides a virtual function from FileDialog that show /// message boxes (like "Do you want to overwrite this file") necessary after /// the Save button is pressed in a file dialog. /// /// Return value is false if we showed a dialog box and true if we did not. /// (in other words, true if it's OK to continue with the save process and /// false if we need to return the user to the dialog to make another selection.) /// </summary> /// <remarks> /// We first call the base class implementation to deal with any messages handled there. /// Then, if OFN_OVERWRITEPROMPT (for a message box if the selected file already exists) /// or OFN_CREATEPROMPT (for a message box if a file is specified that does not exist) /// flags are set, we check to see if it is appropriate to show the dialog(s) in this /// method. If so, we then call PromptFileOverwrite or PromptFileCreate, respectively. /// </remarks> /// <SecurityNote> /// Critical: due to call to PromptFileNotFound, which /// displays a message box with focus restore. /// </SecurityNote> [SecurityCritical] internal override bool PromptUserIfAppropriate(string fileName) { // First, call the FileDialog implementation of PromptUserIfAppropriate // so any processing that happens there can occur. If it returns false, // we'll stop processing (to avoid showing more than one message box // before returning control to the user) and return false as well. if (!base.PromptUserIfAppropriate(fileName)) { return false; } // we use unrestricted file io because to extract the path from the file name // we need to assert path discovery except we do not know the path bool fExist; (new FileIOPermission(PermissionState.Unrestricted)).Assert();//BlessedAssert try { fExist = File.Exists(Path.GetFullPath(fileName)); } finally { FileIOPermission.RevertAssert(); } // If the file does not exist, check if OFN_CREATEPROMPT is // set. If so, display the appropriate message box and act // on the user's choice. // Note that File.Exists requires a full path as a parameter. if (CreatePrompt && !fExist) { if (!PromptFileCreate(fileName)) { return false; } } // If the file already exists, check if OFN_OVERWRITEPROMPT is // set. If so, display the appropriate message box and act // on the user's choice. // Note that File.Exists requires a full path as a parameter. if (OverwritePrompt && fExist) { if (!PromptFileOverwrite(fileName)) { return false; } } // Since all dialog boxes we showed resulted in a positive outcome, // returning true allows the file dialog box to close. return true; } /// <summary> /// Performs the actual call to display a file save dialog. /// </summary> /// <remarks> /// The call chain is ShowDialog > RunDialog > /// RunFileDialog (this function). In /// FileDialog.RunDialog, we created the OPENFILENAME /// structure - so all this function needs to do is /// call GetSaveFileName and process the result code. /// </remarks> /// <exception cref="InvalidOperationException"> /// Thrown if there is an invalid filename, if /// a subclass failure occurs or if the buffer length /// allocated to store the filenames occurs. /// </exception> /// <SecurityNote> /// Critical: Makes a call to UnsafeNativeMethods.GetSaveFileName() /// </SecurityNote> [SecurityCritical] internal override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) { bool result = false; // Make the actual call to GetSaveFileName. This function // blocks on GetSaveFileName until the entire dialog display // is completed - any interaction we have with the dialog // while it's open takes place through our HookProc. The // return value is a bool; true = success. result = UnsafeNativeMethods.GetSaveFileName(ofn); if (!result) // result was 0 (false), so an error occurred. { // Something may have gone wrong - check for error conditions // by calling CommDlgExtendedError to get the specific error. int errorCode = UnsafeNativeMethods.CommDlgExtendedError(); // Throw an appropriate exception if we know what happened: switch (errorCode) { // FNERR_INVALIDFILENAME is usually triggered when an invalid initial filename is specified case NativeMethods.FNERR_INVALIDFILENAME: throw new InvalidOperationException(SR.Get(SRID.FileDialogInvalidFileName, SafeFileName)); case NativeMethods.FNERR_SUBCLASSFAILURE: throw new InvalidOperationException(SR.Get(SRID.FileDialogSubClassFailure)); // note for FNERR_BUFFERTOOSMALL: // This error likely indicates a problem with our buffer size growing code; // take a look at that part of HookProc if customers report this error message is occurring. case NativeMethods.FNERR_BUFFERTOOSMALL: throw new InvalidOperationException(SR.Get(SRID.FileDialogBufferTooSmall)); /* * According to MSDN, the following errors can also occur, but we do not handle them as * they are very unlikely, and if they do occur, they indicate a catastrophic failure. * Most are related to features we do not wrap in our implementation. * * CDERR_DIALOGFAILURE * CDERR_FINDRESFAILURE * CDERR_INITIALIZATION * CDERR_LOADRESFAILURE * CDERR_LOADSTRFAILURE * CDERR_LOCKRESFAILURE * CDERR_MEMALLOCFAILURE * CDERR_MEMLOCKFAILURE * CDERR_NOHINSTANCE * CDERR_NOHOOK * CDERR_NOTEMPLATE * CDERR_STRUCTSIZE */ } } return result; } // <SecurityNote> // Critical, as it calls methods on COM interface IFileDialog. // </SecurityNote> [SecurityCritical] internal override string[] ProcessVistaFiles(IFileDialog dialog) { IShellItem item = dialog.GetResult(); return new [] { item.GetDisplayName(SIGDN.DESKTOPABSOLUTEPARSING) }; } // <SecurityNote> // Critical, as it creates a new RCW. // This requires unmanaged code permissions, but they are asserted if the caller has UI permissions // (e.g. local intranet XBAP). // TreatAsSafe, as it returns the managed COM interface, and not a handle. // Calls on the interface will still be treated with security scrutiny. // </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override IFileDialog CreateVistaDialog() { SecurityHelper.DemandUIWindowPermission(); new SecurityPermission(PermissionState.Unrestricted).Assert(); return (IFileDialog)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID.FileSaveDialog))); } #endregion Internal Methods //--------------------------------------------------- // // Internal Properties // //--------------------------------------------------- //#region Internal Properties //#endregion Internal Properties //--------------------------------------------------- // // Internal Events // //--------------------------------------------------- //#region Internal Events //#endregion Internal Events //--------------------------------------------------- // // Private Methods // //--------------------------------------------------- #region Private Methods // Provides the actual implementation of initialization tasks. // Initialize() is called from both the constructor and the // public Reset() function to set default values for member // variables and for the options bitmask. // // We only perform SaveFileDialog() specific reset tasks here; // it's the calling code's responsibility to ensure that the // base is initialized first. /// <SecurityNote> /// Critical: Calls SecurityCritical member (SetOption) /// </SecurityNote> [SecurityCritical] private void Initialize() { // OFN_OVERWRITEPROMPT // Causes the Save As dialog box to generate a message box if // the selected file already exists. The user must confirm // whether to overwrite the file. Default is true. SetOption(NativeMethods.OFN_OVERWRITEPROMPT, true); } /// <summary> /// Prompts the user with a System.Windows.MessageBox /// when a file is about to be created. This method is /// invoked when the CreatePrompt property is true and the specified file /// does not exist. A return value of false prevents the dialog from closing. /// </summary> /// <SecurityNote> /// Critical: Calls SecurityCritical MessageBoxWithFocusRestore. /// </SecurityNote> [SecurityCritical] private bool PromptFileCreate(string fileName) { return MessageBoxWithFocusRestore(SR.Get(SRID.FileDialogCreatePrompt, fileName), MessageBoxButton.YesNo, MessageBoxImage.Warning); } /// <summary> /// Prompts the user when a file is about to be overwritten. This method is /// invoked when the "overwritePrompt" property is true and the specified /// file already exists. A return value of false prevents the dialog from /// closing. /// </summary> /// <SecurityNote> /// Critical: Calls SecurityCritical MessageBoxWithFocusRestore. /// </SecurityNote> [SecurityCritical] private bool PromptFileOverwrite(string fileName) { return MessageBoxWithFocusRestore(SR.Get(SRID.FileDialogOverwritePrompt, fileName), MessageBoxButton.YesNo, MessageBoxImage.Warning); } #endregion Private Methods //--------------------------------------------------- // // Private Properties // //--------------------------------------------------- //#region Private Properties //#endregion Private Properties //--------------------------------------------------- // // Private Fields // //--------------------------------------------------- //#region Private Fields //#endregion Private Fields } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class TableViewGenerator : ViewGenerator { // tableBody to use for this instance of the ViewGenerator; private TableControlBody _tableBody; internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) { _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } } internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) { _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } List<MshParameter> rawMshParameterList = null; if (parameters != null) rawMshParameterList = parameters.mshParameterList; // check if we received properties from the command line if (rawMshParameterList != null && rawMshParameterList.Count > 0) { this.activeAssociationList = AssociationManager.ExpandTableParameters(rawMshParameterList, so); return; } // we did not get any properties: // try to get properties from the default property set of the object this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); if (this.activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(so)) { activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, new PSPropertyExpression(RemotingConstants.ComputerNameNoteProperty))); } return; } // we failed to get anything from the default property set this.activeAssociationList = AssociationManager.ExpandAll(so); if (this.activeAssociationList.Count > 0) { // Remove PSComputerName and PSShowComputerName from the display as needed. AssociationManager.HandleComputerNameProperties(so, activeAssociationList); FilterActiveAssociationList(); return; } // we were unable to retrieve any properties, so we leave an empty list this.activeAssociationList = new List<MshResolvedExpressionParameterAssociation>(); } /// <summary> /// Let the view prepare itself for RemoteObjects. This will add "ComputerName" to the /// table columns. /// </summary> /// <param name="so"></param> internal override void PrepareForRemoteObjects(PSObject so) { Diagnostics.Assert(so != null, "so cannot be null"); // make sure computername property exists. Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] != null, "PrepareForRemoteObjects cannot be called when the object does not contain ComputerName property."); if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) { // dont change the original format definition in the database..just make a copy and work // with the copy _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl.Copy(); TableRowItemDefinition cnRowDefinition = new TableRowItemDefinition(); PropertyTokenBase propToken = new FieldPropertyToken(); propToken.expression = new ExpressionToken(RemotingConstants.ComputerNameNoteProperty, false); cnRowDefinition.formatTokenList.Add(propToken); _tableBody.defaultDefinition.rowItemDefinitionList.Add(cnRowDefinition); // add header only if there are other header definitions if (_tableBody.header.columnHeaderDefinitionList.Count > 0) { TableColumnHeaderDefinition cnHeaderDefinition = new TableColumnHeaderDefinition(); cnHeaderDefinition.label = new TextToken(); cnHeaderDefinition.label.text = RemotingConstants.ComputerNameNoteProperty; _tableBody.header.columnHeaderDefinitionList.Add(cnHeaderDefinition); } } } internal override FormatStartData GenerateStartData(PSObject so) { FormatStartData startFormat = base.GenerateStartData(so); if (this.dataBaseInfo.view != null) startFormat.shapeInfo = GenerateTableHeaderInfoFromDataBaseInfo(so); else startFormat.shapeInfo = GenerateTableHeaderInfoFromProperties(so); return startFormat; } /// <summary> /// Method to filter resolved expressions as per table view needs. /// For v1.0, table view supports only 10 properties. /// /// This method filters and updates "activeAssociationList" instance property. /// </summary> /// <returns>None.</returns> /// <remarks>This method updates "activeAssociationList" instance property.</remarks> private void FilterActiveAssociationList() { // we got a valid set of properties from the default property set // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default const int nMax = 10; if (activeAssociationList.Count > nMax) { List<MshResolvedExpressionParameterAssociation> tmp = this.activeAssociationList; this.activeAssociationList = new List<MshResolvedExpressionParameterAssociation>(); for (int k = 0; k < nMax; k++) this.activeAssociationList.Add(tmp[k]); } return; } private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) { TableHeaderInfo thi = new TableHeaderInfo(); bool dummy; List<TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(_tableBody, so, out dummy); thi.hideHeader = this.HideHeaders; thi.repeatHeader = this.RepeatHeader; int col = 0; foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { TableColumnInfo ci = new TableColumnInfo(); TableColumnHeaderDefinition colHeader = null; if (_tableBody.header.columnHeaderDefinitionList.Count > 0) colHeader = _tableBody.header.columnHeaderDefinitionList[col]; if (colHeader != null) { ci.width = colHeader.width; ci.alignment = colHeader.alignment; if (colHeader.label != null) ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(colHeader.label); } if (ci.alignment == TextAlignment.Undefined) { ci.alignment = rowItem.alignment; } if (ci.label == null) { FormatToken token = null; if (rowItem.formatTokenList.Count > 0) token = rowItem.formatTokenList[0]; if (token != null) { FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { ci.label = fpt.expression.expressionValue; } else { TextToken tt = token as TextToken; if (tt != null) { ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } } else { ci.label = string.Empty; } } thi.tableColumnInfoList.Add(ci); col++; } return thi; } private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) { TableHeaderInfo thi = new TableHeaderInfo(); thi.hideHeader = this.HideHeaders; for (int k = 0; k < this.activeAssociationList.Count; k++) { MshResolvedExpressionParameterAssociation a = this.activeAssociationList[k]; TableColumnInfo ci = new TableColumnInfo(); // set the label of the column if (a.OriginatingParameter != null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) ci.propertyName = (string)key; } if (ci.propertyName == null) { ci.propertyName = this.activeAssociationList[k].ResolvedExpression.ToString(); } // set the width of the table if (a.OriginatingParameter != null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.WidthEntryKey); if (key != AutomationNull.Value) ci.width = (int)key; else { ci.width = 0; // let Column Width Manager decide the width } } else { ci.width = 0; // let Column Width Manager decide the width } // set the alignment if (a.OriginatingParameter != null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.AlignmentEntryKey); if (key != AutomationNull.Value) ci.alignment = (int)key; else ci.alignment = ComputeDefaultAlignment(so, a.ResolvedExpression); } else { ci.alignment = ComputeDefaultAlignment(so, a.ResolvedExpression); } thi.tableColumnInfoList.Add(ci); } return thi; } private bool HideHeaders { get { // first check command line, it takes the precedence if (this.parameters != null && this.parameters.shapeParameters != null) { TableSpecificParameters tableSpecific = (TableSpecificParameters)this.parameters.shapeParameters; if (tableSpecific != null && tableSpecific.hideHeaders.HasValue) { return tableSpecific.hideHeaders.Value; } } // if we have a view, get the value out of it if (this.dataBaseInfo.view != null) { return _tableBody.header.hideHeader; } return false; } } private bool RepeatHeaders { get { if (this.parameters != null) { return this.parameters.repeatHeader; } return false; } } private static int ComputeDefaultAlignment(PSObject so, PSPropertyExpression ex) { List<PSPropertyExpressionResult> rList = ex.GetValues(so); if ((rList.Count == 0) || (rList[0].Exception != null)) return TextAlignment.Left; object val = rList[0].Result; if (val == null) return TextAlignment.Left; PSObject soVal = PSObject.AsPSObject(val); var typeNames = soVal.InternalTypeNames; if (string.Equals(PSObjectHelper.PSObjectIsOfExactType(typeNames), "System.String", StringComparison.OrdinalIgnoreCase)) return TextAlignment.Left; if (DefaultScalarTypes.IsTypeInList(typeNames)) return TextAlignment.Right; return TextAlignment.Left; } internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit) { FormatEntryData fed = new FormatEntryData(); TableRowEntry tre; if (this.dataBaseInfo.view != null) { tre = GenerateTableRowEntryFromDataBaseInfo(so, enumerationLimit); } else { tre = GenerateTableRowEntryFromFromProperties(so, enumerationLimit); // get the global setting for multiline tre.multiLine = this.dataBaseInfo.db.defaultSettingsSection.MultilineTables; } fed.formatEntryInfo = tre; // override from command line, if there if (this.parameters != null && this.parameters.shapeParameters != null) { TableSpecificParameters tableSpecific = (TableSpecificParameters)this.parameters.shapeParameters; if (tableSpecific != null && tableSpecific.multiLine.HasValue) { tre.multiLine = tableSpecific.multiLine.Value; } } return fed; } private List<TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so, out bool multiLine) { multiLine = tableBody.defaultDefinition.multiLine; if (tableBody.optionalDefinitionList.Count == 0) { // we do not have any override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // see if we have an override that matches TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } if (matchingRowDefinition == null) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) { match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typesWithoutPrefix); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // the overriding row definition takes the precedence if (matchingRowDefinition.multiLine) multiLine = matchingRowDefinition.multiLine; // we have an override, we need to compute the merge of the active cells List<TableRowItemDefinition> activeRowItemDefinitionList = new List<TableRowItemDefinition>(); int col = 0; foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) { // check if the row is an override or not if (rowItem.formatTokenList.Count == 0) { // it's a place holder, use the default activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]); } else { // use the override activeRowItemDefinitionList.Add(rowItem); } col++; } return activeRowItemDefinitionList; } private TableRowEntry GenerateTableRowEntryFromDataBaseInfo(PSObject so, int enumerationLimit) { TableRowEntry tre = new TableRowEntry(); List<TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(_tableBody, so, out tre.multiLine); foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { FormatPropertyField fpf = GenerateFormatPropertyField(rowItem.formatTokenList, so, enumerationLimit); // get the alignment from the row entry // NOTE: if it's not set, the alignment sent with the header will prevail fpf.alignment = rowItem.alignment; tre.formatPropertyFieldList.Add(fpf); } return tre; } private TableRowEntry GenerateTableRowEntryFromFromProperties(PSObject so, int enumerationLimit) { TableRowEntry tre = new TableRowEntry(); for (int k = 0; k < this.activeAssociationList.Count; k++) { FormatPropertyField fpf = new FormatPropertyField(); FieldFormattingDirective directive = null; if (activeAssociationList[k].OriginatingParameter != null) { directive = activeAssociationList[k].OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, this.activeAssociationList[k].ResolvedExpression, directive); tre.formatPropertyFieldList.Add(fpf); } return tre; } } }
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 computer store. /// </summary> public class ComputerStore_Core : TypeCore, IStore { public ComputerStore_Core() { this._TypeId = 68; this._Id = "ComputerStore"; this._Schema_Org_Url = "http://schema.org/ComputerStore"; string label = ""; GetLabel(out label, "ComputerStore", typeof(ComputerStore_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,252}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{252}; 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); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprEtnium class. /// </summary> [Serializable] public partial class AprEtniumCollection : ActiveList<AprEtnium, AprEtniumCollection> { public AprEtniumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprEtniumCollection</returns> public AprEtniumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprEtnium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_Etnia table. /// </summary> [Serializable] public partial class AprEtnium : ActiveRecord<AprEtnium>, IActiveRecord { #region .ctors and Default Settings public AprEtnium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprEtnium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprEtnium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprEtnium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_Etnia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEtnia = new TableSchema.TableColumn(schema); colvarIdEtnia.ColumnName = "idEtnia"; colvarIdEtnia.DataType = DbType.Int32; colvarIdEtnia.MaxLength = 0; colvarIdEtnia.AutoIncrement = true; colvarIdEtnia.IsNullable = false; colvarIdEtnia.IsPrimaryKey = true; colvarIdEtnia.IsForeignKey = false; colvarIdEtnia.IsReadOnly = false; colvarIdEtnia.DefaultSetting = @""; colvarIdEtnia.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEtnia); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @"('')"; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_Etnia",schema); } } #endregion #region Props [XmlAttribute("IdEtnia")] [Bindable(true)] public int IdEtnia { get { return GetColumnValue<int>(Columns.IdEtnia); } set { SetColumnValue(Columns.IdEtnia, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { AprEtnium item = new AprEtnium(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEtnia,string varNombre) { AprEtnium item = new AprEtnium(); item.IdEtnia = varIdEtnia; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEtniaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdEtnia = @"idEtnia"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Norm.Attributes; using Norm.Configuration; using System.Text.RegularExpressions; namespace Norm.BSON { /// <summary> /// Convenience methods for type reflection. /// </summary> /// <remarks> /// This was formerly "Norm.BSON.TypeHelper" but the name was in conflict with a BCL type, so it has been changed to "ReflectionHelper" /// </remarks> public class ReflectionHelper { private static readonly object _lock = new object(); private static readonly IDictionary<Type, ReflectionHelper> _cachedTypeLookup = new Dictionary<Type, ReflectionHelper>(); private static readonly Type _ignoredType = typeof(MongoIgnoreAttribute); private readonly IDictionary<string, MagicProperty> _properties; private readonly Type _type; static ReflectionHelper() { //register to be notified of type configuration changes. MongoConfiguration.TypeConfigurationChanged += new Action<Type>(TypeConfigurationChanged); } static void TypeConfigurationChanged(Type theType) { //clear the cache to prevent ReflectionHelper from getting the wrong thing. if (_cachedTypeLookup.ContainsKey(theType)) { _cachedTypeLookup.Remove(theType); } } /// <summary> /// A regex that gets everything up tot the first backtick, useful when searching for a good starting name. /// </summary> private static readonly Regex _rxGenericTypeNameFinder = new Regex("[^`]+", RegexOptions.Compiled); /// <summary> /// Given a type, this will produce a mongodb save version of the name, for example: /// /// Product&lt;UKSupplier&gt; will become "Product_UKSupplier" - this is helpful for generic typed collections. /// </summary> /// <param name="t"></param> public static string GetScrubbedGenericName(Type t) { String retval = t.Name; if (t.IsGenericType) { retval = _rxGenericTypeNameFinder.Match(t.Name).Value; foreach (var a in t.GetGenericArguments()) { retval += "_" + GetScrubbedGenericName(a); } } return retval; } /// <summary> /// Returns the PropertyInfo for properties defined as Instance, Public, NonPublic, or FlattenHierarchy /// </summary> /// <param retval="type">The type.</param> public static PropertyInfo[] GetProperties(Type type) { return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); } public static PropertyInfo[] GetInterfaceProperties(Type type) { List<PropertyInfo> interfaceProperties; Type[] interfaces = type.GetInterfaces(); if (interfaces.Count() != 0) { interfaceProperties = new List<PropertyInfo>(); foreach (Type nextInterface in interfaces) { PropertyInfo[] intProps = GetProperties(nextInterface); interfaceProperties.AddRange(intProps); } return interfaceProperties.ToArray(); } return null; } /// <summary> /// Initializes a new instance of the <see cref="ReflectionHelper"/> class. /// </summary> /// <param retval="type">The type.</param> public ReflectionHelper(Type type) { _type = type; var properties = GetProperties(type); _properties = LoadMagicProperties(properties, new IdPropertyFinder(type, properties).IdProperty); if (typeof(IExpando).IsAssignableFrom(type)) { this.IsExpando = true; } } /// <summary> /// The get helper for type. /// </summary> /// <param retval="type">The type.</param> /// <returns></returns> public static ReflectionHelper GetHelperForType(Type type) { ReflectionHelper helper; if (!_cachedTypeLookup.TryGetValue(type, out helper)) { lock (_lock) { if (!_cachedTypeLookup.TryGetValue(type, out helper)) { helper = new ReflectionHelper(type); _cachedTypeLookup[type] = helper; } } } return helper; } /// <summary> /// Lifted from AutoMaper. Finds a property using a lambda expression /// (i.e. x => x.Name) /// </summary> /// <param retval="lambdaExpression">The lambda expression.</param> /// <returns>Property retval</returns> public static string FindProperty(LambdaExpression lambdaExpression) { Expression expressionToCheck = lambdaExpression; var done = false; while (!done) { switch (expressionToCheck.NodeType) { case ExpressionType.Convert: expressionToCheck = ((UnaryExpression)expressionToCheck).Operand; break; case ExpressionType.Lambda: expressionToCheck = ((LambdaExpression)expressionToCheck).Body; break; case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)expressionToCheck; if (memberExpression.Expression.NodeType != ExpressionType.Parameter && memberExpression.Expression.NodeType != ExpressionType.Convert) { throw new ArgumentException( string.Format("Expression '{0}' must resolve to top-level member.", lambdaExpression), "lambdaExpression"); } return memberExpression.Member.Name; default: done = true; break; } } return null; } /// <summary> /// Finds a property. /// </summary> /// <param retval="type">The type.</param> /// <param retval="retval">The retval.</param> /// <returns></returns> public static PropertyInfo FindProperty(Type type, string name) { return type.GetProperties().Where(p => p.Name == name).First(); } /// <summary> /// indicates if this type implements "IExpando" /// </summary> public bool IsExpando { get; private set; } /// <summary> /// Gets all properties. /// </summary> /// <returns></returns> public ICollection<MagicProperty> GetProperties() { return _properties.Values; } /// <summary> /// Returns the magic property for the specified retval, or null if it doesn't exist. /// </summary> /// <param retval="retval">The retval.</param> /// <returns></returns> public MagicProperty FindProperty(string name) { return _properties.ContainsKey(name) ? _properties[name] : null; } /// <summary> /// Finds the id property. /// </summary> /// <returns></returns> public MagicProperty FindIdProperty() { return _properties.ContainsKey("$_id") ? _properties["$_id"] : _properties.ContainsKey("$id") ? _properties["$id"] : null; } ///<summary> /// Returns the property defined as the Id for the entity either by convention or explicitly. ///</summary> ///<param retval="type">The type.</param> ///<returns></returns> public static PropertyInfo FindIdProperty(Type type) { return new IdPropertyFinder(type).IdProperty; } /// <summary> /// Loads magic properties. /// </summary> /// <param retval="properties">The properties.</param> /// <param retval="idProperty">The id property.</param> /// <returns></returns> private static IDictionary<string, MagicProperty> LoadMagicProperties(IEnumerable<PropertyInfo> properties, PropertyInfo idProperty) { var magic = new Dictionary<string, MagicProperty>(StringComparer.CurrentCultureIgnoreCase); foreach (var property in properties) { if (property.GetCustomAttributes(_ignoredType, true).Length > 0 || property.GetIndexParameters().Length > 0) { continue; } //HACK: this is a latent BUG, if MongoConfiguration is altered after stashing the type helper, we die. var alias = MongoConfiguration.GetPropertyAlias(property.DeclaringType, property.Name); var name = (property == idProperty && alias != "$id") ? "$_id" : alias; magic.Add(name, new MagicProperty(property, property.DeclaringType)); } return magic; } /// <summary> /// Determines the discriminator to use when serialising the type /// </summary> /// <returns></returns> public string GetTypeDiscriminator() { var discriminatingType = MongoDiscriminatedAttribute.GetDiscriminatingTypeFor(_type); if (discriminatingType != null) { return String.Join(",", _type.AssemblyQualifiedName.Split(','), 0, 2); } return null; } /// <summary> /// Apply default values to the properties in the instance /// </summary> /// <param retval="typeHelper"></param> /// <param retval="instance"></param> public void ApplyDefaultValues(object instance) { // error check. if (instance != null) { // get all the properties foreach (var prop in this.GetProperties()) { // see if the property has a DefaultValue attribute if (prop.HasDefaultValue) { // set the default value for the property. prop.Setter(instance, prop.GetDefaultValue()); } } } } } }
using System; using System.Data; using System.Web; using System.Web.SessionState; using System.IO; using System.Text; using System.Threading; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; #region change history /// 03-09-2009: C02: LLEWIS: changes to handle errors if DataTable(s) is null in /// ExportData methods #endregion namespace Lewis.Xml.Converters { # region Summary /// <summary> /// Exports datatable to CSV or Excel format. /// This uses DataSet's XML features and XSLT for exporting. /// /// C#.Net Example to be used in WebForms /// ------------------------------------- /// using MyLib.ExportData; /// /// private void btnExport_Click(object sender, System.EventArgs e) /// { /// try /// { /// // Declarations /// DataSet dsUsers = ((DataSet) Session["dsUsers"]).Copy( ); /// Lewis.XML.ExportData.Export export = new Lewis.XML.ExportData.Export("Web"); /// string FileName = "UserList.csv"; /// int[] ColList = {2, 3, 4, 5, 6}; /// export.ExportData(dsUsers.Tables[0], ColList, Export.ExportFormat.CSV, FileName); /// } /// catch(Exception Ex) /// { /// lblError.Text = Ex.Message; /// } /// } /// </summary> # endregion // Summary public class Export { public enum ExportFormat : int {CSV = 1, Excel = 2, XML = 3}; // Export format enumeration System.Web.HttpResponse response; private string appType; public Export() { appType = "Web"; response = System.Web.HttpContext.Current.Response; } public Export(string ApplicationType) { appType = ApplicationType; if(appType != "Web" && appType != "Win") throw new Exception("Provide valid application format (Web/Win)"); if (appType == "Web") response = System.Web.HttpContext.Current.Response; } #region ExportData OverLoad : Type#1 // Function : ExportData // Arguments : table, FormatType, FileName // Purpose : To get all the column headers in the datatable and // exorts in CSV / Excel format with all columns public void ExportData(DataTable table, ExportFormat FormatType, string FileName) { try { if (table == null || table.Rows.Count == 0) throw new Exception("There are no details to export."); // Create Dataset using (DataSet dsExport = new DataSet("Export")) { using (DataTable dtExport = table.Copy()) { dtExport.TableName = "Values"; dsExport.Tables.Add(dtExport); // Getting Field Names string[] sHeaders = new string[dtExport.Columns.Count]; string[] sFileds = new string[dtExport.Columns.Count]; for (int i = 0; i < dtExport.Columns.Count; i++) { sHeaders[i] = dtExport.Columns[i].ColumnName; sFileds[i] = dtExport.Columns[i].ColumnName; } if (appType == "Web") Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName); else if (appType == "Win") Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName); } } } catch(Exception Ex) { throw Ex; } } #endregion // ExportData OverLoad : Type#1 #region ExportData OverLoad : Type#2 // Function : ExportData // Arguments : table, ColumnList, FormatType, FileName // Purpose : To get the specified column headers in the datatable and // exorts in CSV / Excel format with specified columns public void ExportData(DataTable table, int[] ColumnList, ExportFormat FormatType, string FileName) { try { if (table == null || table.Rows.Count == 0) throw new Exception("There are no details to export"); // Create Dataset using (DataSet dsExport = new DataSet("Export")) { using (DataTable dtExport = table.Copy()) { dtExport.TableName = "Values"; dsExport.Tables.Add(dtExport); if (ColumnList.Length > dtExport.Columns.Count) throw new Exception("ExportColumn List should not exceed Total Columns"); // Getting Field Names string[] sHeaders = new string[ColumnList.Length]; string[] sFileds = new string[ColumnList.Length]; for (int i = 0; i < ColumnList.Length; i++) { if ((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count)) throw new Exception("ExportColumn Number should not exceed Total Columns Range"); sHeaders[i] = dtExport.Columns[ColumnList[i]].ColumnName; sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName; } if (appType == "Web") Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName); else if (appType == "Win") Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName); } } } catch(Exception Ex) { throw Ex; } } #endregion // ExportData OverLoad : Type#2 #region ExportData OverLoad : Type#3 // Function : ExportData // Arguments : table, ColumnList, Headers, FormatType, FileName // Purpose : To get the specified column headers in the datatable and // exorts in CSV / Excel format with specified columns and // with specified headers public void ExportData(DataTable table, int[] ColumnList, string[] Headers, ExportFormat FormatType, string FileName) { try { if (table == null || table.Rows.Count == 0) throw new Exception("There are no details to export"); // Create Dataset using (DataSet dsExport = new DataSet("Export")) { using (DataTable dtExport = table.Copy()) { dtExport.TableName = "Values"; dsExport.Tables.Add(dtExport); if (ColumnList.Length != Headers.Length) throw new Exception("ExportColumn List and Headers List should be of same length"); else if (ColumnList.Length > dtExport.Columns.Count || Headers.Length > dtExport.Columns.Count) throw new Exception("ExportColumn List should not exceed Total Columns"); // Getting Field Names string[] sFileds = new string[ColumnList.Length]; for (int i = 0; i < ColumnList.Length; i++) { if ((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count)) throw new Exception("ExportColumn Number should not exceed Total Columns Range"); sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName; } if (appType == "Web") Export_with_XSLT_Web(dsExport, Headers, sFileds, FormatType, FileName); else if (appType == "Win") Export_with_XSLT_Windows(dsExport, Headers, sFileds, FormatType, FileName); } } } catch(Exception Ex) { throw Ex; } } #endregion // ExportData OverLoad : Type#3 #region ExportData OverLoad : Type#3 // Function : ExportData // Arguments : table, FormatType, FileName // Purpose : To get all the column headers in the datatable and // exorts in CSV / Excel format with all columns public void ExportData(DataTableCollection tables, ExportFormat FormatType, string FileName) { try { string NewFileName; if (tables == null) throw new Exception("There are no details to export."); foreach(DataTable DetailsTable in tables) { if(DetailsTable.Rows.Count == 0) throw new Exception("There are no details to export."); NewFileName = FileName.Substring(0,FileName.LastIndexOf(".")); NewFileName+= " - " + DetailsTable.TableName; NewFileName+= FileName.Substring(FileName.LastIndexOf(".")); // Create Dataset DataSet dsExport = new DataSet("Export"); DataTable dtExport = DetailsTable.Copy(); dtExport.TableName = "Values"; dsExport.Tables.Add(dtExport); // Getting Field Names string[] sHeaders = new string[dtExport.Columns.Count]; string[] sFileds = new string[dtExport.Columns.Count]; for (int i=0; i < dtExport.Columns.Count; i++) { sHeaders[i] = dtExport.Columns[i].ColumnName; sFileds[i] = dtExport.Columns[i].ColumnName; } if(appType == "Web") Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, NewFileName); else if(appType == "Win") Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, NewFileName); } } catch(Exception Ex) { throw Ex; } } #endregion //ExportData OverLoad : Type#4 public void ExportDataSetToExcel(DataSet ds, string filename) { // first let's clean up the response.object //response.Clear(); //response.Charset = ""; // set the response mime type for excel //response.ContentType = "application/vnd.ms-excel"; //response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); // create a string writer using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // instantiate a datagrid GridView dg = new GridView(); for(int ii = 1; ii < ds.Tables.Count; ii++) { DataTable dt = ds.Tables[ii]; GridView dgChild = new GridView(); dg.Controls.Add(dgChild); dgChild.DataSource = dt; dgChild.DataBind(); } dg.DataSource = ds.Tables[0]; dg.DataBind(); dg.RenderControl(htw); File.AppendAllText(filename,sw.ToString()); //response.End(); } } } #region Export_with_XSLT_Web // Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer= true; if(FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content response.Write(sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); response.End(); sw.Dispose(); stream.Dispose(); } catch(ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch(Exception Ex) { throw Ex; } } #endregion // Export_with_XSLT #region Export_with_XSLT_Windows // Function : Export_with_XSLT_Windows // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content File.WriteAllText(FileName, sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); sw.Dispose(); stream.Dispose(); } catch(Exception Ex) { throw Ex; } } #endregion // Export_with_XSLT #region CreateStylesheet // Function : WriteStylesheet // Arguments : writer, sHeaders, sFileds, FormatType // Purpose : Creates XSLT file to apply on dataset's XML file private void CreateStylesheet(XmlTextWriter writer, string[] sHeaders, string[] sFileds, ExportFormat FormatType) { try { // xsl:stylesheet string ns = "http://www.w3.org/1999/XSL/Transform"; writer.Formatting = Formatting.Indented; writer.WriteStartDocument( ); writer.WriteStartElement("xsl","stylesheet",ns); writer.WriteAttributeString("version","1.0"); writer.WriteStartElement("xsl:output"); writer.WriteAttributeString("method","text"); writer.WriteAttributeString("version","4.0"); writer.WriteEndElement( ); // xsl-template writer.WriteStartElement("xsl:template"); writer.WriteAttributeString("match","/"); // xsl:value-of for headers for(int i=0; i< sHeaders.Length; i++) { writer.WriteString("\""); writer.WriteStartElement("xsl:value-of"); writer.WriteAttributeString("select", "'" + sHeaders[i] + "'"); writer.WriteEndElement( ); // xsl:value-of writer.WriteString("\""); if (i != sFileds.Length - 1) writer.WriteString( (FormatType == ExportFormat.CSV ) ? "," : " " ); } // xsl:for-each writer.WriteStartElement("xsl:for-each"); writer.WriteAttributeString("select","Export/Values"); writer.WriteString("\r\n"); // xsl:value-of for data fields for(int i=0; i< sFileds.Length; i++) { writer.WriteString("\""); writer.WriteStartElement("xsl:value-of"); writer.WriteAttributeString("select", sFileds[i]); writer.WriteEndElement( ); // xsl:value-of writer.WriteString("\""); if (i != sFileds.Length - 1) writer.WriteString( (FormatType == ExportFormat.CSV ) ? "," : " " ); } writer.WriteEndElement( ); // xsl:for-each writer.WriteEndElement( ); // xsl-template writer.WriteEndElement( ); // xsl:stylesheet writer.WriteEndDocument( ); } catch(Exception Ex) { throw Ex; } } #endregion // WriteStylesheet } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Process Exception ///<para>SObject Name: ProcessException</para> ///<para>Custom Object: False</para> ///</summary> public class SfProcessException : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ProcessException"; } } ///<summary> /// Process Exception ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Process Exception Number /// <para>Name: ProcessExceptionNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "processExceptionNumber")] [Updateable(false), Createable(false)] public string ProcessExceptionNumber { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Attached To ID /// <para>Name: AttachedToId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "attachedToId")] public string AttachedToId { get; set; } ///<summary> /// Message /// <para>Name: Message</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "message")] public string Message { get; set; } ///<summary> /// Status Category /// <para>Name: StatusCategory</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "statusCategory")] [Updateable(false), Createable(false)] public string StatusCategory { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Category /// <para>Name: Category</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "category")] public string Category { get; set; } ///<summary> /// Severity /// <para>Name: Severity</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "severity")] public string Severity { get; set; } ///<summary> /// Priority /// <para>Name: Priority</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "priority")] public string Priority { get; set; } ///<summary> /// Case ID /// <para>Name: CaseId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "caseId")] public string CaseId { get; set; } ///<summary> /// ReferenceTo: Case /// <para>RelationshipName: Case</para> ///</summary> [JsonProperty(PropertyName = "case")] [Updateable(false), Createable(false)] public SfCase Case { get; set; } ///<summary> /// External Reference /// <para>Name: ExternalReference</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "externalReference")] public string ExternalReference { get; set; } ///<summary> /// Severity Category /// <para>Name: SeverityCategory</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "severityCategory")] [Updateable(false), Createable(false)] public string SeverityCategory { get; set; } ///<summary> /// Description /// <para>Name: Description</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } } }
/* * Copyright (c) 2006-2014, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; namespace OpenMetaverse { public static partial class Utils { /// <summary> /// Operating system /// </summary> public enum Platform { /// <summary>Unknown</summary> Unknown, /// <summary>Microsoft Windows</summary> Windows, /// <summary>Microsoft Windows CE</summary> WindowsCE, /// <summary>Linux</summary> Linux, /// <summary>Apple OSX</summary> OSX } /// <summary> /// Runtime platform /// </summary> public enum Runtime { /// <summary>.NET runtime</summary> Windows, /// <summary>Mono runtime: http://www.mono-project.com/</summary> Mono } public const float E = (float)Math.E; public const float LOG10E = 0.4342945f; public const float LOG2E = 1.442695f; public const float PI = (float)Math.PI; public const float TWO_PI = (float)(Math.PI * 2.0d); public const float PI_OVER_TWO = (float)(Math.PI / 2.0d); public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d); /// <summary>Used for converting degrees to radians</summary> public const float DEG_TO_RAD = (float)(Math.PI / 180.0d); /// <summary>Used for converting radians to degrees</summary> public const float RAD_TO_DEG = (float)(180.0d / Math.PI); /// <summary>Provide a single instance of the CultureInfo class to /// help parsing in situations where the grid assumes an en-us /// culture</summary> public static readonly System.Globalization.CultureInfo EnUsCulture = new System.Globalization.CultureInfo("en-us"); /// <summary>UNIX epoch in DateTime format</summary> public static readonly DateTime Epoch = new DateTime(1970, 1, 1); public static readonly byte[] EmptyBytes = new byte[0]; /// <summary>Provide a single instance of the MD5 class to avoid making /// duplicate copies and handle thread safety</summary> private static readonly System.Security.Cryptography.MD5 MD5Builder = new System.Security.Cryptography.MD5CryptoServiceProvider(); /// <summary>Provide a single instance of the SHA-1 class to avoid /// making duplicate copies and handle thread safety</summary> private static readonly System.Security.Cryptography.SHA1 SHA1Builder = new System.Security.Cryptography.SHA1CryptoServiceProvider(); private static readonly System.Security.Cryptography.SHA256 SHA256Builder = new System.Security.Cryptography.SHA256Managed(); /// <summary>Provide a single instance of a random number generator /// to avoid making duplicate copies and handle thread safety</summary> private static readonly Random RNG = new Random(); #region Math /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static float Clamp(float value, float min, float max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static double Clamp(double value, double min, double max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Clamp a given value between a range /// </summary> /// <param name="value">Value to clamp</param> /// <param name="min">Minimum allowable value</param> /// <param name="max">Maximum allowable value</param> /// <returns>A value inclusively between lower and upper</returns> public static int Clamp(int value, int min, int max) { // First we check to see if we're greater than the max value = (value > max) ? max : value; // Then we check to see if we're less than the min. value = (value < min) ? min : value; // There's no check to see if min > max. return value; } /// <summary> /// Round a floating-point value to the nearest integer /// </summary> /// <param name="val">Floating point number to round</param> /// <returns>Integer</returns> public static int Round(float val) { return (int)Math.Floor(val + 0.5f); } /// <summary> /// Test if a single precision float is a finite number /// </summary> public static bool IsFinite(float value) { return !(Single.IsNaN(value) || Single.IsInfinity(value)); } /// <summary> /// Test if a double precision float is a finite number /// </summary> public static bool IsFinite(double value) { return !(Double.IsNaN(value) || Double.IsInfinity(value)); } /// <summary> /// Get the distance between two floating-point values /// </summary> /// <param name="value1">First value</param> /// <param name="value2">Second value</param> /// <returns>The distance between the two values</returns> public static float Distance(float value1, float value2) { return Math.Abs(value1 - value2); } public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount) { // All transformed to double not to lose precission // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; double sCubed = s * s * s; double sSquared = s * s; if (amount == 0f) result = value1; else if (amount == 1f) result = value2; else result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + t1 * s + v1; return (float)result; } public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount) { // All transformed to double not to lose precission // Otherwise, for high numbers of param:amount the result is NaN instead of Infinity double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result; double sCubed = s * s * s; double sSquared = s * s; if (amount == 0d) result = value1; else if (amount == 1f) result = value2; else result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed + (3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared + t1 * s + v1; return result; } public static float Lerp(float value1, float value2, float amount) { return value1 + (value2 - value1) * amount; } public static double Lerp(double value1, double value2, double amount) { return value1 + (value2 - value1) * amount; } public static float SmoothStep(float value1, float value2, float amount) { // It is expected that 0 < amount < 1 // If amount < 0, return value1 // If amount > 1, return value2 float result = Utils.Clamp(amount, 0f, 1f); return Utils.Hermite(value1, 0f, value2, 0f, result); } public static double SmoothStep(double value1, double value2, double amount) { // It is expected that 0 < amount < 1 // If amount < 0, return value1 // If amount > 1, return value2 double result = Utils.Clamp(amount, 0f, 1f); return Utils.Hermite(value1, 0f, value2, 0f, result); } public static float ToDegrees(float radians) { // This method uses double precission internally, // though it returns single float // Factor = 180 / pi return (float)(radians * 57.295779513082320876798154814105); } public static float ToRadians(float degrees) { // This method uses double precission internally, // though it returns single float // Factor = pi / 180 return (float)(degrees * 0.017453292519943295769236907684886); } /// <summary> /// Compute the MD5 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>MD5 hash of the input data</returns> public static byte[] MD5(byte[] data) { lock (MD5Builder) return MD5Builder.ComputeHash(data); } /// <summary> /// Compute the SHA1 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>SHA1 hash of the input data</returns> public static byte[] SHA1(byte[] data) { lock (SHA1Builder) return SHA1Builder.ComputeHash(data); } /// <summary> /// Calculate the SHA1 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The SHA1 hash as a string</returns> public static string SHA1String(string value) { StringBuilder digest = new StringBuilder(40); byte[] hash = SHA1(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Compute the SHA256 hash for a byte array /// </summary> /// <param name="data">Byte array to compute the hash for</param> /// <returns>SHA256 hash of the input data</returns> public static byte[] SHA256(byte[] data) { lock (SHA256Builder) return SHA256Builder.ComputeHash(data); } /// <summary> /// Calculate the SHA256 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The SHA256 hash as a string</returns> public static string SHA256String(string value) { StringBuilder digest = new StringBuilder(64); byte[] hash = SHA256(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Calculate the MD5 hash of a given string /// </summary> /// <param name="password">The password to hash</param> /// <returns>An MD5 hash in string format, with $1$ prepended</returns> public static string MD5(string password) { StringBuilder digest = new StringBuilder(32); byte[] hash = MD5(ASCIIEncoding.Default.GetBytes(password)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return "$1$" + digest.ToString(); } /// <summary> /// Calculate the MD5 hash of a given string /// </summary> /// <param name="value">The string to hash</param> /// <returns>The MD5 hash as a string</returns> public static string MD5String(string value) { StringBuilder digest = new StringBuilder(32); byte[] hash = MD5(Encoding.UTF8.GetBytes(value)); // Convert the hash to a hex string foreach (byte b in hash) digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b); return digest.ToString(); } /// <summary> /// Generate a random double precision floating point value /// </summary> /// <returns>Random value of type double</returns> public static double RandomDouble() { lock (RNG) return RNG.NextDouble(); } #endregion Math #region Platform /// <summary> /// Get the current running platform /// </summary> /// <returns>Enumeration of the current platform we are running on</returns> public static Platform GetRunningPlatform() { const string OSX_CHECK_FILE = "/Library/Extensions.kextcache"; if (Environment.OSVersion.Platform == PlatformID.WinCE) { return Platform.WindowsCE; } else { int plat = (int)Environment.OSVersion.Platform; if ((plat != 4) && (plat != 128)) { return Platform.Windows; } else { if (System.IO.File.Exists(OSX_CHECK_FILE)) return Platform.OSX; else return Platform.Linux; } } } /// <summary> /// Get the current running runtime /// </summary> /// <returns>Enumeration of the current runtime we are running on</returns> public static Runtime GetRunningRuntime() { Type t = Type.GetType("Mono.Runtime"); if (t != null) return Runtime.Mono; else return Runtime.Windows; } #endregion Platform } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class SymbolEquivalenceComparerTests { public static readonly CS.CSharpCompilationOptions CSharpDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); public static readonly CS.CSharpCompilationOptions CSharpSignedDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithCryptoKeyFile(SigningTestHelpers.KeyPairFile). WithStrongNameProvider(new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>())); [Fact] public async Task TestArraysAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; int intField2; int[] intArrayField2; string[] stringArrayField2; int[][] intArrayArrayField2; int[,] intArrayRank2Field2; System.Int32 int32Field2; }"; using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode)) { var type = (ITypeSymbol)(await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single(); var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single(); var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single(); var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single(); var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single(); var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single(); var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single(); var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single(); var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single(); var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single(); var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single(); var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type), SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type)); } } [Fact] public async Task TestArraysInDifferentLanguagesAreEquivalent() { var csharpCode = @"class C { int intField1; int[] intArrayField1; string[] stringArrayField1; int[][] intArrayArrayField1; int[,] intArrayRank2Field1; System.Int32 int32Field1; }"; var vbCode = @"class C dim intField1 as Integer; dim intArrayField1 as Integer() dim stringArrayField1 as String() dim intArrayArrayField1 as Integer()() dim intArrayRank2Field1 as Integer(,) dim int32Field1 as System.Int32 end class"; using (var csharpWorkspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode)) using (var vbWorkspace = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode)) { var csharpType = (ITypeSymbol)(await csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var vbType = (await vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single(); var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single(); var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single(); var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single(); var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single(); var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single(); var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single(); var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single(); var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single(); var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single(); var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single(); var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type)); } } [Fact] public async Task TestFields() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var csharpCode2 = @"class Type1 { int field1; short field4; } class Type2 { bool field3; string field2; }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [WorkItem(538124)] [Fact] public async Task TestFieldsAcrossLanguages() { var csharpCode1 = @"class Type1 { int field1; string field2; } class Type2 { bool field3; short field4; }"; var vbCode1 = @"class Type1 dim field1 as Integer; dim field4 as Short; end class class Type2 dim field3 as Boolean; dim field2 as String; end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field1_v2 = type1_v2.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); var field2_v2 = type2_v2.GetMembers("field2").Single(); var field3_v1 = type2_v1.GetMembers("field3").Single(); var field3_v2 = type2_v2.GetMembers("field3").Single(); var field4_v1 = type2_v1.GetMembers("field4").Single(); var field4_v2 = type1_v2.GetMembers("field4").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2)); } } [Fact] public async Task TestFieldsInGenericTypes() { var code = @"class C<T> { int foo; C<int> intInstantiation1; C<string> stringInstantiation; C<T> instanceInstantiation; } class D { C<int> intInstantiation2; } "; using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var typeC = (await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var typeD = (await workspace.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("D").Single(); var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single(); var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single(); var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single(); var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single(); var foo = typeC.GetMembers("foo").Single(); var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single(); var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single(); var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single(); var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo), SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1), SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2)); } } [Fact] public async Task TestMethodsWithDifferentReturnTypeNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { int Foo() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsWithDifferentNamesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo1() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsWithDifferentAritiesAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo<T>() {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsWithDifferentParametersAreNotEquivalent() { var csharpCode1 = @"class Type1 { void Foo() {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsWithDifferentTypeParameters() { var csharpCode1 = @"class Type1 { void Foo<A>(A a) {} }"; var csharpCode2 = @"class Type1 { void Foo<B>(B a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestMethodsWithSameParameters() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestMethodsWithDifferentParameterNames() { var csharpCode1 = @"class Type1 { void Foo(int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int b) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestMethodsAreEquivalentOutToRef() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(ref int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsNotEquivalentRemoveOut() { var csharpCode1 = @"class Type1 { void Foo(out int a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsAreEquivalentIgnoreParams() { var csharpCode1 = @"class Type1 { void Foo(params int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(int[] a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestMethodsNotEquivalentDifferentParameterTypes() { var csharpCode1 = @"class Type1 { void Foo(int[] a) {} }"; var csharpCode2 = @"class Type1 { void Foo(string[] a) {} }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); } } [Fact] public async Task TestMethodsAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { T Foo<T>(IList<T> list, int a) {} void Bar() { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1 function Foo(of U)(list as IList(of U), a as Integer) as U end function sub Quux() end sub end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbQuuxMethod = vbType1.GetMembers("Quux").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod)); } } [Fact] public async Task TestMethodsInGenericTypesAcrossLanguages() { var csharpCode1 = @" using System.Collections.Generic; class Type1<X> { T Foo<T>(IList<T> list, X a) {} void Bar(X x) { } }"; var vbCode1 = @" Imports System.Collections.Generic class Type1(of M) function Foo(of U)(list as IList(of U), a as M) as U end function sub Bar(x as Object) end sub end class"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(vbCode1)) { var csharpType1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var vbType1 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var csharpFooMethod = csharpType1.GetMembers("Foo").Single(); var csharpBarMethod = csharpType1.GetMembers("Bar").Single(); var vbFooMethod = vbType1.GetMembers("Foo").Single(); var vbBarMethod = vbType1.GetMembers("Bar").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod), SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod)); } } [Fact] public async Task TestObjectAndDynamicAreNotEqualNormally() { var csharpCode1 = @"class Type1 { object field1; dynamic field2; }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var field1_v1 = type1_v1.GetMembers("field1").Single(); var field2_v1 = type1_v1.GetMembers("field2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1)); } } [Fact] public async Task TestObjectAndDynamicAreEqualInSignatures() { var csharpCode1 = @"class Type1 { void Foo(object o1) { } }"; var csharpCode2 = @"class Type1 { void Foo(dynamic o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestUnequalGenericsInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<int> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<string> o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [Fact] public async Task TestGenericsWithDynamicAndObjectInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(IList<object> o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(IList<dynamic> o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [Fact] public async Task TestDynamicAndUnrelatedTypeInSignatures() { var csharpCode1 = @" using System.Collections.Generic; class Type1 { void Foo(dynamic o1) { } }"; var csharpCode2 = @" using System.Collections.Generic; class Type1 { void Foo(string o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); } } [Fact] public async Task TestNamespaces() { var csharpCode1 = @"namespace Outer { namespace Inner { class Type { } } class Type { } } "; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) { var outer1 = (INamespaceSymbol)(await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").Single(); var outer2 = (INamespaceSymbol)(await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").Single(); var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single(); var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single(); var outerType1 = outer1.GetTypeMembers("Type").Single(); var outerType2 = outer2.GetTypeMembers("Type").Single(); var innerType1 = inner1.GetTypeMembers("Type").Single(); var innerType2 = inner2.GetTypeMembers("Type").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outer2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(inner2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1), SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1), SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol)); } } [Fact] public async Task TestNamedTypesEquivalent() { var csharpCode1 = @" class Type1 { } class Type2<X> { } "; var csharpCode2 = @" class Type1 { void Foo(); } class Type2<Y> { }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type2_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); var type2_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1), SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1)); } } [Fact] public async Task TestNamedTypesDifferentIfNameChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type2 { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type2").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public async Task TestNamedTypesDifferentIfTypeKindChanges() { var csharpCode1 = @" struct Type1 { }"; var csharpCode2 = @" class Type1 { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public async Task TestNamedTypesDifferentIfArityChanges() { var csharpCode1 = @" class Type1 { }"; var csharpCode2 = @" class Type1<T> { void Foo(); }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public async Task TestNamedTypesDifferentIfContainerDifferent() { var csharpCode1 = @" class Outer { class Type1 { } }"; var csharpCode2 = @" class Other { class Type1 { void Foo(); } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var outer = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Outer").Single(); var other = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Other").Single(); var type1_v1 = outer.GetTypeMembers("Type1").Single(); var type1_v2 = other.GetTypeMembers("Type1").Single(); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1)); } } [Fact] public async Task TestAliasedTypes1() { var csharpCode1 = @" using i = System.Int32; class Type1 { void Foo(i o1) { } }"; var csharpCode2 = @" class Type1 { void Foo(int o1) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("Type1").Single(); var method_v1 = type1_v1.GetMembers("Foo").Single(); var method_v2 = type1_v2.GetMembers("Foo").Single(); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1)); Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1), SymbolEquivalenceComparer.Instance.GetHashCode(method_v2)); } } [WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")] [Fact] public async Task TestRefVersusOut() { var csharpCode1 = @" class C { void M(out int i) { } }"; var csharpCode2 = @" class C { void M(ref int i) { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode1)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(csharpCode2)) { var type1_v1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var type1_v2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetTypeMembers("C").Single(); var method_v1 = type1_v1.GetMembers("M").Single(); var method_v2 = type1_v2.GetMembers("M").Single(); var trueComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: true); var falseComp = new SymbolEquivalenceComparer(assemblyComparerOpt: null, distinguishRefFromOut: false); Assert.False(trueComp.Equals(method_v1, method_v2)); Assert.False(trueComp.Equals(method_v2, method_v1)); // The hashcodes of distinct objects don't have to be distinct. Assert.True(falseComp.Equals(method_v1, method_v2)); Assert.True(falseComp.Equals(method_v2, method_v1)); Assert.Equal(falseComp.GetHashCode(method_v1), falseComp.GetHashCode(method_v2)); } } [Fact] public async Task TestCSharpReducedExtensionMethodsAreEquivalent() { var code = @" class Zed {} public static class Extensions { public static void NotGeneric(this Zed z, int data) { } public static void GenericThis<T>(this T me, int data) where T : Zed { } public static void GenericNotThis<T>(this Zed z, T data) { } public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { } public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { } } class Test { void NotGeneric() { Zed z; int n; z.NotGeneric(n); } void GenericThis() { Zed z; int n; z.GenericThis(n); } void GenericNotThis() { Zed z; int n; z.GenericNotThis(n); } void GenericThisAndMore() { Zed z; int n; z.GenericThisAndMore(n); } void GenericThisAndOther() { Zed z; z.GenericThisAndOther(z); } } "; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); var comp2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [Fact] public async Task TestVisualBasicReducedExtensionMethodsAreEquivalent() { var code = @" Imports System.Runtime.CompilerServices Class Zed End Class Module Extensions <Extension> Public Sub NotGeneric(z As Zed, data As Integer) End Sub <Extension> Public Sub GenericThis(Of T As Zed)(m As T, data as Integer) End Sub <Extension> Public Sub GenericNotThis(Of T)(z As Zed, data As T) End Sub <Extension> Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S) End Sub <Extension> Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T) End Sub End Module Class Test Sub NotGeneric() Dim z As Zed Dim n As Integer z.NotGeneric(n) End Sub Sub GenericThis() Dim z As Zed Dim n As Integer z.GenericThis(n) End Sub Sub GenericNotThis() Dim z As Zed Dim n As Integer z.GenericNotThis(n) End Sub Sub GenericThisAndMore() Dim z As Zed Dim n As Integer z.GenericThisAndMore(n) End Sub Sub GenericThisAndOther() Dim z As Zed z.GenericThisAndOther(z) End Sub End Class "; using (var workspace1 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) using (var workspace2 = await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)) { var comp1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()); var comp2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore"); TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther"); } } [Fact] public async Task TestDifferentModules() { var csharpCode = @"namespace N { namespace M { } }"; using (var workspace1 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule"))) using (var workspace2 = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule"))) { var namespace1 = (await workspace1.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); var namespace2 = (await workspace2.CurrentSolution.Projects.Single().GetCompilationAsync()).GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M"); Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2)); Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1), SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2)); Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1), SymbolEquivalenceComparer.Instance.GetHashCode(namespace2)); } } [Fact] public void AssemblyComparer1() { var references = new[] { TestReferences.NetFx.v4_0_30319.mscorlib }; string source = "public class T {}"; string sourceV1 = "[assembly: System.Reflection.AssemblyVersion(\"1.0.0.0\")] public class T {}"; string sourceV2 = "[assembly: System.Reflection.AssemblyVersion(\"2.0.0.0\")] public class T {}"; var a1 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var a2 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions); var b1 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV1) }, references, CSharpSignedDllOptions); var b2 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var b3 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions); var ta1 = (ITypeSymbol)a1.GlobalNamespace.GetMembers("T").Single(); var ta2 = (ITypeSymbol)a2.GlobalNamespace.GetMembers("T").Single(); var tb1 = (ITypeSymbol)b1.GlobalNamespace.GetMembers("T").Single(); var tb2 = (ITypeSymbol)b2.GlobalNamespace.GetMembers("T").Single(); var tb3 = (ITypeSymbol)b3.GlobalNamespace.GetMembers("T").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false); // same name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, ta2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(ta1, ta2)); Assert.True(identityComparer.Equals(ta1, ta2)); // different name: Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, tb1)); Assert.False(SymbolEquivalenceComparer.Instance.Equals(ta1, tb1)); Assert.False(identityComparer.Equals(ta1, tb1)); // different identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb1, tb2)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb1, tb2)); Assert.False(identityComparer.Equals(tb1, tb2)); // same identity Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb2, tb3)); Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb2, tb3)); Assert.True(identityComparer.Equals(tb2, tb3)); } private sealed class AssemblySymbolIdentityComparer : IEqualityComparer<IAssemblySymbol> { public static readonly IEqualityComparer<IAssemblySymbol> Instance = new AssemblySymbolIdentityComparer(); public bool Equals(IAssemblySymbol x, IAssemblySymbol y) { return x.Identity.Equals(y.Identity); } public int GetHashCode(IAssemblySymbol obj) { return obj.Identity.GetHashCode(); } } [Fact] public void CustomModifiers_Methods1() { const string ilSource = @" .class public C { .method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1 int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 2 int32 a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) { ldnull throw } .method public instance int32[] F( // 3 int32 a, int32 b) { ldnull throw } } "; MetadataReference r1, r2; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource)) { byte[] bytes = File.ReadAllBytes(tempAssembly.Path); r1 = MetadataReference.CreateFromImage(bytes); r2 = MetadataReference.CreateFromImage(bytes); } var c1 = CS.CSharpCompilation.Create("comp1", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r1 }); var c2 = CS.CSharpCompilation.Create("comp2", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r2 }); var type1 = (ITypeSymbol)c1.GlobalNamespace.GetMembers("C").Single(); var type2 = (ITypeSymbol)c2.GlobalNamespace.GetMembers("C").Single(); var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance, distinguishRefFromOut: false); var f1 = type1.GetMembers("F"); var f2 = type2.GetMembers("F"); Assert.True(identityComparer.Equals(f1[0], f2[0])); Assert.False(identityComparer.Equals(f1[0], f2[1])); Assert.False(identityComparer.Equals(f1[0], f2[2])); Assert.False(identityComparer.Equals(f1[0], f2[3])); Assert.False(identityComparer.Equals(f1[1], f2[0])); Assert.True(identityComparer.Equals(f1[1], f2[1])); Assert.False(identityComparer.Equals(f1[1], f2[2])); Assert.False(identityComparer.Equals(f1[1], f2[3])); Assert.False(identityComparer.Equals(f1[2], f2[0])); Assert.False(identityComparer.Equals(f1[2], f2[1])); Assert.True(identityComparer.Equals(f1[2], f2[2])); Assert.False(identityComparer.Equals(f1[2], f2[3])); Assert.False(identityComparer.Equals(f1[3], f2[0])); Assert.False(identityComparer.Equals(f1[3], f2[1])); Assert.False(identityComparer.Equals(f1[3], f2[2])); Assert.True(identityComparer.Equals(f1[3], f2[3])); } private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName) where TInvocation : SyntaxNode { var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName); var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName); Assert.NotNull(method1); Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension); Assert.NotNull(method2); Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension); Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2)); var cfmethod1 = method1.ConstructedFrom; var cfmethod2 = method2.ConstructedFrom; Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2)); } private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName) where TInvocation : SyntaxNode { var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single(); var method = type1.GetMembers(methodName).Single(); var method_root = method.DeclaringSyntaxReferences[0].GetSyntax(); var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault(); if (invocation == null) { // vb method root is statement, but we need block to find body with invocation invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First(); } var model = compilation.GetSemanticModel(invocation.SyntaxTree); var info = model.GetSymbolInfo(invocation); return info.Symbol as IMethodSymbol; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Json; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.UI; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Abp.Authorization.Users { public class AbpUserManager<TRole, TUser> : UserManager<TUser>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; set; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } protected AbpUserStore<TRole, TUser> AbpUserStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; private readonly IOptions<IdentityOptions> _optionsAccessor; public AbpUserManager( AbpRoleManager<TRole, TUser> roleManager, AbpUserStore<TRole, TUser> userStore, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; _settingManager = settingManager; _optionsAccessor = optionsAccessor; AbpUserStore = userStore; RoleManager = roleManager; LocalizationManager = NullLocalizationManager.Instance; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } await InitializeOptionsAsync(user.TenantId); return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual bool IsGranted(long userId, string permissionName) { return IsGranted( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual bool IsGranted(TUser user, Permission permission) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return IsGranted(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual bool IsGranted(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!permission.FeatureDependency.IsSatisfied(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = GetUserPermissionCacheItem(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (RoleManager.IsGranted(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public void ResetAllPermissions(TUser user) { UserPermissionStore.RemoveAllPermissionSettings(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual TUser FindByNameOrEmail(string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmail(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpUserStore.FindAllAsync(login); } public virtual List<TUser> FindAll(UserLoginInfo login) { return AbpUserStore.FindAll(login); } public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login) { return AbpUserStore.FindAsync(tenantId, login); } public virtual TUser Find(int? tenantId, UserLoginInfo login) { return AbpUserStore.Find(tenantId, login); } public virtual Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); } public virtual TUser FindByNameOrEmail(int? tenantId, string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmail(tenantId, userNameOrEmailAddress); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual TUser GetUserById(long userId) { var user = AbpUserStore.FindById(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public virtual TUser GetUserById(long userId) //{ // var user = FindById(userId.ToString()); // if (user == null) // { // throw new AbpException("There is no user with id: " + userId); // } // return user; //} public override async Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUserBase.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName) { throw new UserFriendlyException( string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); } } return await base.UpdateAsync(user); } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public override IdentityResult Update(TUser user) //{ // var result = CheckDuplicateUsernameOrEmailAddress(user.Id, user.UserName, user.EmailAddress); // if (!result.Succeeded) // { // return result; // } // //Admin user's username can not be changed! // if (user.UserName != AbpUserBase.AdminUserName) // { // if ((GetOldUserName(user.Id)) == AbpUserBase.AdminUserName) // { // throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); // } // } // return base.Update(user); //} public override async Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); } return await base.DeleteAsync(user); } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public override IdentityResult Delete(TUser user) //{ // if (user.UserName == AbpUserBase.AdminUserName) // { // throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); // } // return base.Delete(user); //} public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var errors = new List<IdentityError>(); foreach (var validator in PasswordValidators) { var validationResult = await validator.ValidateAsync(this, user, newPassword); if (!validationResult.Succeeded) { errors.AddRange(validationResult.Errors); } } if (errors.Any()) { return IdentityResult.Failed(errors.ToArray()); } await AbpUserStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword)); await UpdateSecurityStampAsync(user); return IdentityResult.Success; } // IPasswordValidator doesn't have a sync version of Validate(...) //public virtual IdentityResult ChangePassword(TUser user, string newPassword) //{ // var errors = new List<IdentityError>(); // foreach (var validator in PasswordValidators) // { // var validationResult = validator.Validate(this, user, newPassword); // if (!validationResult.Succeeded) // { // errors.AddRange(validationResult.Errors); // } // } // if (errors.Any()) // { // return IdentityResult.Failed(errors.ToArray()); // } // AbpUserStore.SetPasswordHash(user, PasswordHasher.HashPassword(user, newPassword)); // return IdentityResult.Success; //} public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRolesAsync(TUser user, string[] roleNames) { await AbpUserStore.UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles); //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId.ToString()); if (role != null && roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; }); } public virtual bool IsInOrganizationUnit(TUser user, OrganizationUnit ou) { return _unitOfWorkManager.WithUnitOfWork(() => { return _userOrganizationUnitRepository.Count(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; }); } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); }); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); }); } public virtual void AddToOrganizationUnit(TUser user, OrganizationUnit ou) { _unitOfWorkManager.WithUnitOfWork(() => { var currentOus = GetOrganizationUnits(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } CheckMaxUserOrganizationUnitMembershipCount(user.TenantId, currentOus.Count + 1); _userOrganizationUnitRepository.Insert(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); }); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); }); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ); }); } public virtual void RemoveFromOrganizationUnit(TUser user, OrganizationUnit ou) { _unitOfWorkManager.WithUnitOfWork(() => { _userOrganizationUnitRepository.Delete( uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ); }); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } private void CheckMaxUserOrganizationUnitMembershipCount(int? tenantId, int requestedCount) { var maxCount = _organizationUnitSettings.GetMaxUserMembershipCount(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } await _unitOfWorkManager.Current.SaveChangesAsync(); //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } }); } public virtual void SetOrganizationUnits(TUser user, params long[] organizationUnitIds) { _unitOfWorkManager.WithUnitOfWork(() => { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } CheckMaxUserOrganizationUnitMembershipCount(user.TenantId, organizationUnitIds.Length); var currentOus = GetOrganizationUnits(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { RemoveFromOrganizationUnit(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { AddToOrganizationUnit( user, _organizationUnitRepository.Get(organizationUnitId) ); } } }); } public virtual async Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var result = _unitOfWorkManager.WithUnitOfWork(() => { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return query.ToList(); }); return await Task.FromResult(result); } public virtual List<OrganizationUnit> GetOrganizationUnits(TUser user) { return _unitOfWorkManager.WithUnitOfWork(() => { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return query.ToList(); }); } public virtual async Task<List<TUser>> GetUsersInOrganizationUnitAsync( OrganizationUnit organizationUnit, bool includeChildren = false) { var result = _unitOfWorkManager.WithUnitOfWork(() => { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return query.ToList(); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return query.ToList(); } }); return await Task.FromResult(result); } public virtual List<TUser> GetUsersInOrganizationUnit( OrganizationUnit organizationUnit, bool includeChildren = false) { return _unitOfWorkManager.WithUnitOfWork(() => { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return query.ToList(); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return query.ToList(); } }); } public virtual async Task InitializeOptionsAsync(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = await IsTrueAsync( AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId ); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds( await GetSettingValueAsync<int>( AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId ) ); Options.Lockout.MaxFailedAccessAttempts = await GetSettingValueAsync<int>( AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId ); //Password complexity Options.Password.RequireDigit = await GetSettingValueAsync<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId ); Options.Password.RequireLowercase = await GetSettingValueAsync<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId ); Options.Password.RequireNonAlphanumeric = await GetSettingValueAsync<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId ); Options.Password.RequireUppercase = await GetSettingValueAsync<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId ); Options.Password.RequiredLength = await GetSettingValueAsync<int>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId ); } public virtual void InitializeOptions(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = IsTrue( AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId ); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds( GetSettingValue<int>( AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId) ); Options.Lockout.MaxFailedAccessAttempts = GetSettingValue<int>( AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); //Password complexity Options.Password.RequireDigit = GetSettingValue<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId ); Options.Password.RequireLowercase = GetSettingValue<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId ); Options.Password.RequireNonAlphanumeric = GetSettingValue<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId ); Options.Password.RequireUppercase = GetSettingValue<bool>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId ); Options.Password.RequiredLength = GetSettingValue<int>( AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId ); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpUserStore.GetUserNameFromDatabaseAsync(userId); } protected virtual string GetOldUserName(long userId) { return AbpUserStore.GetUserNameFromDatabase(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(user)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private UserPermissionCacheItem GetUserPermissionCacheItem(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return _cacheManager.GetUserPermissionCache().Get(cacheKey, () => { var user = AbpUserStore.FindById(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in AbpUserStore.GetRoles(user)) { newCacheItem.RoleIds.Add((RoleManager.GetRoleByName(roleName)).Id); } foreach (var permissionInfo in UserPermissionStore.GetPermissions(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user) { var providers = new List<string>(); foreach (var provider in await base.GetValidTwoFactorProvidersAsync(user)) { var isEmailProviderEnabled = await IsTrueAsync( AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId ); if (provider == "Email" && !isEmailProviderEnabled) { continue; } var isSmsProviderEnabled = await IsTrueAsync( AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId ); if (provider == "Phone" && !isSmsProviderEnabled) { continue; } providers.Add(provider); } return providers; } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private Task<bool> IsTrueAsync(string settingName, int? tenantId) { return GetSettingValueAsync<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } private Task<T> GetSettingValueAsync<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplicationAsync<T>(settingName) : _settingManager.GetSettingValueForTenantAsync<T>(settingName, tenantId.Value); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } public virtual async Task AddTokenValidityKeyAsync( TUser user, string tokenValidityKey, DateTime expireDate, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.AddTokenValidityKeyAsync(user, tokenValidityKey, expireDate, cancellationToken); } public virtual void AddTokenValidityKey( TUser user, string tokenValidityKey, DateTime expireDate, CancellationToken cancellationToken = default(CancellationToken)) { AbpUserStore.AddTokenValidityKey(user, tokenValidityKey, expireDate, cancellationToken); } public virtual async Task<bool> IsTokenValidityKeyValidAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { return await AbpUserStore.IsTokenValidityKeyValidAsync(user, tokenValidityKey, cancellationToken); } public virtual bool IsTokenValidityKeyValid( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { return AbpUserStore.IsTokenValidityKeyValid(user, tokenValidityKey, cancellationToken); } public virtual async Task RemoveTokenValidityKeyAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.RemoveTokenValidityKeyAsync(user, tokenValidityKey, cancellationToken); } public virtual void RemoveTokenValidityKey( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { AbpUserStore.RemoveTokenValidityKey(user, tokenValidityKey, cancellationToken); } public bool IsLockedOut(string userId) { var user = AbpUserStore.FindById(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } var lockoutEndDateUtc = AbpUserStore.GetLockoutEndDate(user); return lockoutEndDateUtc > DateTimeOffset.UtcNow; } public bool IsLockedOut(TUser user) { var lockoutEndDateUtc = AbpUserStore.GetLockoutEndDate(user); return lockoutEndDateUtc > DateTimeOffset.UtcNow; } public void ResetAccessFailedCount(TUser user) { AbpUserStore.ResetAccessFailedCount(user); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Threading; using Android.OS; using Android.App; using Android.Widget; using Android.Content; using Android.Content.PM; using Sensus.Shared; using Sensus.Shared.UI; using Sensus.Shared.Context; using Xamarin; using Xamarin.Forms; using Xamarin.Facebook; using Xamarin.Forms.Platform.Android; using Xam.Plugin.MapExtend.Droid; using Plugin.CurrentActivity; using ZXing.Mobile; #if __ANDROID_23__ using Plugin.Permissions; #endif [assembly: MetaData("com.facebook.sdk.ApplicationId", Value = "@string/app_id")] [assembly: UsesPermission(Microsoft.Band.BandClientManager.BindBandService)] namespace Sensus.Android { [Activity(Label = "@string/app_name", MainLauncher = true, LaunchMode = LaunchMode.SingleTask, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] [IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "http", DataHost = "*", DataPathPattern = ".*\\\\.json")] // protocols downloaded from an http web link [IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "https", DataHost = "*", DataPathPattern = ".*\\\\.json")] // protocols downloaded from an https web link [IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault }, DataMimeType = "application/json")] // protocols obtained from "file" and "content" schemes: http://developer.android.com/guide/components/intents-filters.html#DataTest public class AndroidMainActivity : FormsApplicationActivity { private AndroidSensusServiceConnection _serviceConnection; private ManualResetEvent _activityResultWait; private AndroidActivityResultRequestCode _activityResultRequestCode; private Tuple<Result, Intent> _activityResult; private ICallbackManager _facebookCallbackManager; private App _app; private ManualResetEvent _serviceBindWait; private readonly object _locker = new object(); public ICallbackManager FacebookCallbackManager { get { return _facebookCallbackManager; } } protected override void OnCreate(Bundle savedInstanceState) { Console.Error.WriteLine("--------------------------- Creating activity ---------------------------"); base.OnCreate(savedInstanceState); _activityResultWait = new ManualResetEvent(false); _facebookCallbackManager = CallbackManagerFactory.Create(); _serviceBindWait = new ManualResetEvent(false); Window.AddFlags(global::Android.Views.WindowManagerFlags.DismissKeyguard); Window.AddFlags(global::Android.Views.WindowManagerFlags.ShowWhenLocked); Window.AddFlags(global::Android.Views.WindowManagerFlags.TurnScreenOn); Forms.Init(this, savedInstanceState); FormsMaps.Init(this, savedInstanceState); MapExtendRenderer.Init(this, savedInstanceState); CrossCurrentActivity.Current.Activity = this; #if UNIT_TESTING Forms.ViewInitialized += (sender, e) => { if (!string.IsNullOrWhiteSpace(e.View.StyleId)) e.NativeView.ContentDescription = e.View.StyleId; }; #endif _app = new App(); LoadApplication(_app); MobileBarcodeScanner.Initialize(Application); _serviceConnection = new AndroidSensusServiceConnection(); _serviceConnection.ServiceConnected += (o, e) => { // it's happened that the service is created / started after the service helper is disposed: https://insights.xamarin.com/app/Sensus-Production/issues/46 // binding to the service in such a situation can result in a null service helper within the binder. if the service helper was disposed, then the goal is // to close down sensus. so finish the activity. if (e.Binder.SensusServiceHelper == null) { Finish(); return; } if (e.Binder.SensusServiceHelper.BarcodeScanner == null) { try { e.Binder.SensusServiceHelper.BarcodeScanner = new MobileBarcodeScanner(); } catch (Exception ex) { e.Binder.SensusServiceHelper.Logger.Log("Failed to create barcode scanner: " + ex.Message, LoggingLevel.Normal, GetType()); } } // tell the service to finish this activity when it is stopped e.Binder.ServiceStopAction = Finish; // signal the activity that the service has been bound _serviceBindWait.Set(); // if we're unit testing, try to load and run the unit testing protocol from the embedded assets #if UNIT_TESTING using (Stream protocolFile = Assets.Open("UnitTestingProtocol.json")) { Protocol.RunUnitTestingProtocol(protocolFile); } #endif }; // the following is fired if the process hosting the service crashes or is killed. _serviceConnection.ServiceDisconnected += (o, e) => { Toast.MakeText(this, "The Sensus service has crashed.", ToastLength.Long); DisconnectFromService(); Finish(); }; OpenIntentAsync(Intent); } protected override void OnStart() { Console.Error.WriteLine("--------------------------- Starting activity ---------------------------"); base.OnStart(); CrossCurrentActivity.Current.Activity = this; } protected override void OnResume() { Console.Error.WriteLine("--------------------------- Resuming activity ---------------------------"); base.OnResume(); CrossCurrentActivity.Current.Activity = this; // make sure that the service is running and bound any time the activity is resumed. Intent serviceIntent = new Intent(this, typeof(AndroidSensusService)); StartService(serviceIntent); BindService(serviceIntent, _serviceConnection, Bind.AutoCreate | Bind.AboveClient); // prevent the user from interacting with the UI by displaying a progress dialog until // the service has been bound. if the service has already bound, the wait handle below // will already be set and the dialog will immediately be dismissed. ProgressDialog serviceBindWaitDialog = ProgressDialog.Show(this, "Please Wait", "Binding to Sensus", true, false); // start new thread to wait for connection, since we're currently on the UI thread, which the service connection needs in order to complete. new Thread(() => { _serviceBindWait.WaitOne(); SensusServiceHelper.Get().ClearPendingSurveysNotificationAsync(); // now that the service connection has been established, dismiss the wait dialog and show protocols. SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(serviceBindWaitDialog.Dismiss); }).Start(); } protected override void OnPause() { Console.Error.WriteLine("--------------------------- Pausing activity ---------------------------"); base.OnPause(); // we disconnect from the service within onpause because onresume always blocks the user while rebinding // to the service. conditions (the bind wait handle and service connection) need to be ready for onresume // and this is the only place to establish those conditions. DisconnectFromService(); } protected override void OnStop() { Console.Error.WriteLine("--------------------------- Stopping activity ---------------------------"); base.OnStop(); SensusServiceHelper serviceHelper = SensusServiceHelper.Get(); if (serviceHelper != null) { serviceHelper.Save(); serviceHelper.IssuePendingSurveysNotificationAsync(true, true); } } protected override void OnDestroy() { Console.Error.WriteLine("--------------------------- Destroying activity ---------------------------"); base.OnDestroy(); // if the activity is destroyed, reset the service connection stop action to be null so that the service doesn't try to // finish a destroyed activity if/when the service stops. if (_serviceConnection.Binder != null) _serviceConnection.Binder.ServiceStopAction = null; } private void DisconnectFromService() { _serviceBindWait.Reset(); if (_serviceConnection.Binder != null) UnbindService(_serviceConnection); } public override void OnWindowFocusChanged(bool hasFocus) { base.OnWindowFocusChanged(hasFocus); // the service helper is responsible for running actions that depend on the main activity. if the main activity // is not showing, the service helper starts the main activity and then runs requested actions. there is a race // condition between actions that wish to show a dialog (e.g., starting speech recognition) and the display of // the activity. in order to ensure that the activity is showing before any actions are run, we override this // focus changed event and let the service helper know when the activity is focused and when it is not. this // way, any actions that the service helper runs will certainly be run after the main activity is running // and focused. AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper; if (serviceHelper != null) { if (hasFocus) serviceHelper.SetFocusedMainActivity(this); else serviceHelper.SetFocusedMainActivity(null); } } #region intent handling protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); OpenIntentAsync(intent); } private void OpenIntentAsync(Intent intent) { new Thread(() => { // wait for service helper to be initialized, since this method might be called before the service starts up // and initializes the service helper. int timeToWaitMS = 60000; int waitIntervalMS = 1000; while (SensusServiceHelper.Get() == null && timeToWaitMS > 0) { Thread.Sleep(waitIntervalMS); timeToWaitMS -= waitIntervalMS; } if (SensusServiceHelper.Get() == null) { // don't use SensusServiceHelper.Get().FlashNotificationAsync because service helper is null RunOnUiThread(() => { Toast.MakeText(this, "Failed to get service helper. Cannot open Intent.", ToastLength.Long); }); return; } // open page to view protocol if a protocol was passed to us if (intent.Data != null) { global::Android.Net.Uri dataURI = intent.Data; try { if (intent.Scheme == "http" || intent.Scheme == "https") Protocol.DeserializeAsync(new Uri(dataURI.ToString()), Protocol.DisplayAndStartAsync); else if (intent.Scheme == "content" || intent.Scheme == "file") { byte[] bytes = null; try { MemoryStream memoryStream = new MemoryStream(); Stream inputStream = ContentResolver.OpenInputStream(dataURI); inputStream.CopyTo(memoryStream); inputStream.Close(); bytes = memoryStream.ToArray(); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to read bytes from local file URI \"" + dataURI + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } if (bytes != null) Protocol.DeserializeAsync(bytes, Protocol.DisplayAndStartAsync); } else SensusServiceHelper.Get().Logger.Log("Sensus didn't know what to do with URI \"" + dataURI + "\".", LoggingLevel.Normal, GetType()); } catch (Exception ex) { SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() => { new AlertDialog.Builder(this).SetTitle("Failed to get protocol").SetMessage(ex.Message).Show(); }); } } }).Start(); } #endregion #region activity results public void GetActivityResultAsync(Intent intent, AndroidActivityResultRequestCode requestCode, Action<Tuple<Result, Intent>> callback) { new Thread(() => { lock (_locker) { _activityResultRequestCode = requestCode; _activityResult = null; _activityResultWait.Reset(); try { StartActivityForResult(intent, (int)requestCode); } catch (Exception ex) { try { Insights.Report(ex, Insights.Severity.Error); } catch (Exception) { } _activityResultWait.Set(); } _activityResultWait.WaitOne(); callback(_activityResult); } }).Start(); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == (int)_activityResultRequestCode) { _activityResult = new Tuple<Result, Intent>(resultCode, data); _activityResultWait.Set(); } // looks like the facebook SDK can become uninitialized during the process of interacting with the Facebook login manager. this // might happen when Sensus is stopped/destroyed while the user is logging into facebook. check here to ensure that the facebook // SDK is initialized. // // see: https://insights.xamarin.com/app/Sensus-Production/issues/66 // if (!FacebookSdk.IsInitialized) FacebookSdk.SdkInitialize(global::Android.App.Application.Context); _facebookCallbackManager.OnActivityResult(requestCode, (int)resultCode, data); } #if __ANDROID_23__ public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } #endif #endregion } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using NUnit.Framework; using System; using System.Collections.Generic; namespace Aardvark.Base.Benchmarks { // AUTO GENERATED CODE - DO NOT CHANGE! #region Rot3f [SimpleJob(RuntimeMoniker.NetCoreApp30)] // Uncomment following lines for assembly output, need to add // <DebugType>pdbonly</DebugType> // <DebugSymbols>true</DebugSymbols> // to Aardvark.Base.csproj for Release configuration. // [DisassemblyDiagnoser(printAsm: true, printSource: true)] public class Rot3fGetEuler { private static class Implementations { public static V3f Original(Rot3f r) { var test = r.W * r.Y - r.X * r.Z; if (test > 0.5f - Constant<float>.PositiveTinyValue) // singularity at north pole { return new V3f( 2 * Fun.Atan2(r.X, r.W), (float)Constant.PiHalf, 0); } if (test < -0.5f + Constant<float>.PositiveTinyValue) // singularity at south pole { return new V3f( 2 * Fun.Atan2(r.X, r.W), -(float)Constant.PiHalf, 0); } // From Wikipedia, conversion between quaternions and Euler angles. return new V3f( Fun.Atan2(2 * (r.W * r.X + r.Y * r.Z), 1 - 2 * (r.X * r.X + r.Y * r.Y)), Fun.AsinClamped(2 * test), Fun.Atan2(2 * (r.W * r.Z + r.X * r.Y), 1 - 2 * (r.Y * r.Y + r.Z * r.Z))); } public static V3f CopySign(Rot3f r) { var test = r.W * r.Y - r.X * r.Z; if (test.Abs() >= 0.5f - Constant<float>.PositiveTinyValue) { return new V3f( 2 * Fun.Atan2(r.X, r.W), Fun.CopySign((float)Constant.PiHalf, test), 0); } else { return new V3f( Fun.Atan2(2 * (r.W * r.X + r.Y * r.Z), 1 - 2 * (r.X * r.X + r.Y * r.Y)), Fun.AsinClamped(2 * test), Fun.Atan2(2 * (r.W * r.Z + r.X * r.Y), 1 - 2 * (r.Y * r.Y + r.Z * r.Z))); } } public static Dictionary<string, Func<Rot3f, V3f>> All { get => new Dictionary<string, Func<Rot3f, V3f>>() { { "Original", Original }, { "CopySign", CopySign } }; } } const int count = 1000000; readonly Rot3f[] Rots = new Rot3f[count]; readonly V3f[] EulerAngles = new V3f[count]; public Rot3fGetEuler() { var rnd = new RandomSystem(1); EulerAngles.SetByIndex(i => { var vrnd = rnd.UniformV3f() * Constant.PiF * 2; var veps = (rnd.UniformDouble() < 0.5) ? rnd.UniformV3f() * (i / (float)100) * 1e-12f : V3f.Zero; var vspc = new V3f(rnd.UniformV3i(4)) * (float)Constant.PiHalf + veps; float roll = (rnd.UniformDouble() < 0.5) ? vrnd.X : vspc.X; float pitch = (rnd.UniformDouble() < 0.5) ? vrnd.Y : vspc.Y; float yaw = (rnd.UniformDouble() < 0.5) ? vrnd.Z : vspc.Z; return new V3f(roll, pitch, yaw); }); Rots.SetByIndex(i => Rot3f.RotationEuler(EulerAngles[i])); } private double[] ComputeAbsoluteError(Func<Rot3f, V3f> f) { double[] error = new double[count]; for (int i = 0; i < count; i++) { var r1 = Rots[i]; var r2 = Rot3f.RotationEuler(f(r1)).Normalized; error[i] = Rot.Distance(r1, r2); } return error; } public void BenchmarkNumericalStability() { Console.WriteLine("Benchmarking numerical stability for Rot3f.GetEulerAngles() variants"); Console.WriteLine(); foreach (var m in Implementations.All) { var errors = ComputeAbsoluteError(m.Value); var min = errors.Min(); var max = errors.Max(); var mean = errors.Mean(); var var = errors.Variance(); Report.Begin("Absolute error for '{0}'", m.Key); Report.Line("Min = {0}", min); Report.Line("Max = {0}", max); Report.Line("Mean = {0}", mean); Report.Line("Variance = {0}", var); Report.End(); Console.WriteLine(); } } [Test] public void CorrectnessTest() { for (int i = 0; i < count; i++) { foreach (var f in Implementations.All) { Rot3f r1 = Rots[i]; Rot3f r2 = Rot3f.RotationEuler(f.Value(r1)); Assert.Less( Rot.Distance(r1, r2), 1e-2f, string.Format("{0} implementation incorrect!", f.Key) ); } } } [Benchmark] public V3f Original() { V3f accum = V3f.Zero; for (int i = 0; i < count; i++) { accum += Implementations.Original(Rots[i]); } return accum; } [Benchmark] public V3f CopySign() { V3f accum = V3f.Zero; for (int i = 0; i < count; i++) { accum += Implementations.CopySign(Rots[i]); } return accum; } } #endregion #region Rot3d [SimpleJob(RuntimeMoniker.NetCoreApp30)] // Uncomment following lines for assembly output, need to add // <DebugType>pdbonly</DebugType> // <DebugSymbols>true</DebugSymbols> // to Aardvark.Base.csproj for Release configuration. // [DisassemblyDiagnoser(printAsm: true, printSource: true)] public class Rot3dGetEuler { private static class Implementations { public static V3d Original(Rot3d r) { var test = r.W * r.Y - r.X * r.Z; if (test > 0.5 - Constant<double>.PositiveTinyValue) // singularity at north pole { return new V3d( 2 * Fun.Atan2(r.X, r.W), Constant.PiHalf, 0); } if (test < -0.5 + Constant<double>.PositiveTinyValue) // singularity at south pole { return new V3d( 2 * Fun.Atan2(r.X, r.W), -Constant.PiHalf, 0); } // From Wikipedia, conversion between quaternions and Euler angles. return new V3d( Fun.Atan2(2 * (r.W * r.X + r.Y * r.Z), 1 - 2 * (r.X * r.X + r.Y * r.Y)), Fun.AsinClamped(2 * test), Fun.Atan2(2 * (r.W * r.Z + r.X * r.Y), 1 - 2 * (r.Y * r.Y + r.Z * r.Z))); } public static V3d CopySign(Rot3d r) { var test = r.W * r.Y - r.X * r.Z; if (test.Abs() >= 0.5 - Constant<double>.PositiveTinyValue) { return new V3d( 2 * Fun.Atan2(r.X, r.W), Fun.CopySign(Constant.PiHalf, test), 0); } else { return new V3d( Fun.Atan2(2 * (r.W * r.X + r.Y * r.Z), 1 - 2 * (r.X * r.X + r.Y * r.Y)), Fun.AsinClamped(2 * test), Fun.Atan2(2 * (r.W * r.Z + r.X * r.Y), 1 - 2 * (r.Y * r.Y + r.Z * r.Z))); } } public static Dictionary<string, Func<Rot3d, V3d>> All { get => new Dictionary<string, Func<Rot3d, V3d>>() { { "Original", Original }, { "CopySign", CopySign } }; } } const int count = 1000000; readonly Rot3d[] Rots = new Rot3d[count]; readonly V3d[] EulerAngles = new V3d[count]; public Rot3dGetEuler() { var rnd = new RandomSystem(1); EulerAngles.SetByIndex(i => { var vrnd = rnd.UniformV3d() * Constant.Pi * 2; var veps = (rnd.UniformDouble() < 0.5) ? rnd.UniformV3d() * (i / (double)100) * 1e-22 : V3d.Zero; var vspc = new V3d(rnd.UniformV3i(4)) * Constant.PiHalf + veps; double roll = (rnd.UniformDouble() < 0.5) ? vrnd.X : vspc.X; double pitch = (rnd.UniformDouble() < 0.5) ? vrnd.Y : vspc.Y; double yaw = (rnd.UniformDouble() < 0.5) ? vrnd.Z : vspc.Z; return new V3d(roll, pitch, yaw); }); Rots.SetByIndex(i => Rot3d.RotationEuler(EulerAngles[i])); } private double[] ComputeAbsoluteError(Func<Rot3d, V3d> f) { double[] error = new double[count]; for (int i = 0; i < count; i++) { var r1 = Rots[i]; var r2 = Rot3d.RotationEuler(f(r1)).Normalized; error[i] = Rot.Distance(r1, r2); } return error; } public void BenchmarkNumericalStability() { Console.WriteLine("Benchmarking numerical stability for Rot3d.GetEulerAngles() variants"); Console.WriteLine(); foreach (var m in Implementations.All) { var errors = ComputeAbsoluteError(m.Value); var min = errors.Min(); var max = errors.Max(); var mean = errors.Mean(); var var = errors.Variance(); Report.Begin("Absolute error for '{0}'", m.Key); Report.Line("Min = {0}", min); Report.Line("Max = {0}", max); Report.Line("Mean = {0}", mean); Report.Line("Variance = {0}", var); Report.End(); Console.WriteLine(); } } [Test] public void CorrectnessTest() { for (int i = 0; i < count; i++) { foreach (var f in Implementations.All) { Rot3d r1 = Rots[i]; Rot3d r2 = Rot3d.RotationEuler(f.Value(r1)); Assert.Less( Rot.Distance(r1, r2), 1e-7, string.Format("{0} implementation incorrect!", f.Key) ); } } } [Benchmark] public V3d Original() { V3d accum = V3d.Zero; for (int i = 0; i < count; i++) { accum += Implementations.Original(Rots[i]); } return accum; } [Benchmark] public V3d CopySign() { V3d accum = V3d.Zero; for (int i = 0; i < count; i++) { accum += Implementations.CopySign(Rots[i]); } return accum; } } #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; namespace System { public static class AppContext { [Flags] private enum SwitchValueState { HasFalseValue = 0x1, HasTrueValue = 0x2, HasLookedForOverride = 0x4, UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary<string, SwitchValueState> s_switchMap = new Dictionary<string, SwitchValueState>(); static AppContext() { // Unloading event must happen before ProcessExit event AppDomain.CurrentDomain.ProcessExit += OnUnloading; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; // populate the AppContext with the default set of values AppContextDefaultValues.PopulateDefaultValues(); } public static string BaseDirectory { get { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception return (string) AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; } } public static string TargetFrameworkName { get { // Forward the value that is set on the current domain. return AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; } } public static object GetData(string name) { return AppDomain.CurrentDomain.GetData(name); } public static void SetData(string name, object data) { AppDomain.CurrentDomain.SetData(name, data); } public static event UnhandledExceptionEventHandler UnhandledException { add { AppDomain.CurrentDomain.UnhandledException += value; } remove { AppDomain.CurrentDomain.UnhandledException -= value; } } public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException { add { AppDomain.CurrentDomain.FirstChanceException += value; } remove { AppDomain.CurrentDomain.FirstChanceException -= value; } } public static event System.EventHandler ProcessExit; public static event System.EventHandler Unloading; private static void OnProcessExit(object sender, EventArgs e) { var processExit = ProcessExit; if (processExit != null) { processExit(null, EventArgs.Empty); } } private static void OnUnloading(object sender, EventArgs e) { var unloading = Unloading; if (unloading != null) { unloading(null, EventArgs.Empty); } } #region Switch APIs /// <summary> /// Try to get the value of the switch. /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">A variable where to place the value of the switch</param> /// <returns>A return value of true represents that the switch was set and <paramref name="isEnabled"/> contains the value of the switch</returns> public static bool TryGetSwitch(string switchName, out bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); // By default, the switch is not enabled. isEnabled = false; SwitchValueState switchValue; lock (s_switchMap) { if (s_switchMap.TryGetValue(switchName, out switchValue)) { // The value is in the dictionary. // There are 3 cases here: // 1. The value of the switch is 'unknown'. This means that the switch name is not known to the system (either via defaults or checking overrides). // Example: This is the case when, during a servicing event, a switch is added to System.Xml which ships before mscorlib. The value of the switch // Will be unknown to mscorlib.dll and we want to prevent checking the overrides every time we check this switch // 2. The switch has a valid value AND we have read the overrides for it // Example: TryGetSwitch is called for a switch set via SetSwitch // 3. The switch has the default value and we need to check for overrides // Example: TryGetSwitch is called for the first time for a switch that has a default value // 1. The value is unknown if (switchValue == SwitchValueState.UnknownValue) { isEnabled = false; return false; } // We get the value of isEnabled from the value that we stored in the dictionary isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; // 2. The switch has a valid value AND we have checked for overrides if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride) { return true; } // 3. The switch has a valid value, but we need to check for overrides. // Regardless of whether or not the switch has an override, we need to update the value to reflect // the fact that we checked for overrides. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { // we found an override! isEnabled = overrideValue; } // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } else { // The value is NOT in the dictionary // In this case we need to see if we have an override defined for the value. // There are 2 cases: // 1. The value has an override specified. In this case we need to add the value to the dictionary // and mark it as checked for overrides // Example: In a servicing event, System.Xml introduces a switch and an override is specified. // The value is not found in mscorlib (as System.Xml ships independent of mscorlib) // 2. The value does not have an override specified // In this case, we want to capture the fact that we looked for a value and found nothing by adding // an entry in the dictionary with the 'sentinel' value of 'SwitchValueState.UnknownValue'. // Example: This will prevent us from trying to find overrides for values that we don't have in the dictionary // 1. The value has an override specified. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { isEnabled = overrideValue; // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } // 2. The value does not have an override. s_switchMap[switchName] = SwitchValueState.UnknownValue; } } return false; // we did not find a value for the switch } /// <summary> /// Assign a switch a value /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">The value to assign</param> public static void SetSwitch(string switchName, bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; lock (s_switchMap) { // Store the new value and the fact that we checked in the dictionary s_switchMap[switchName] = switchValue; } } /// <summary> /// This method is going to be called from the AppContextDefaultValues class when setting up the /// default values for the switches. !!!! This method is called during the static constructor so it does not /// take a lock !!!! If you are planning to use this outside of that, please ensure proper locking. /// </summary> internal static void DefineSwitchDefault(string switchName, bool isEnabled) { s_switchMap[switchName] = isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue; } #endregion } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// <para> Provides details of the <c>WorkflowExecutionContinuedAsNew</c> event. </para> /// </summary> public class WorkflowExecutionContinuedAsNewEventAttributes { private string input; private long? decisionTaskCompletedEventId; private string newExecutionRunId; private string executionStartToCloseTimeout; private TaskList taskList; private string taskStartToCloseTimeout; private string childPolicy; private List<string> tagList = new List<string>(); private WorkflowType workflowType; /// <summary> /// The input provided to the new workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 32768</description> /// </item> /// </list> /// </para> /// </summary> public string Input { get { return this.input; } set { this.input = value; } } /// <summary> /// Sets the Input property /// </summary> /// <param name="input">The value to set for the Input property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithInput(string input) { this.input = input; return this; } // Check to see if Input property is set internal bool IsSetInput() { return this.input != null; } /// <summary> /// The id of the <c>DecisionTaskCompleted</c> event corresponding to the decision task that resulted in the /// <c>ContinueAsNewWorkflowExecution</c> decision that started this execution. This information can be useful for diagnosing problems by /// tracing back the cause of events. /// /// </summary> public long DecisionTaskCompletedEventId { get { return this.decisionTaskCompletedEventId ?? default(long); } set { this.decisionTaskCompletedEventId = value; } } /// <summary> /// Sets the DecisionTaskCompletedEventId property /// </summary> /// <param name="decisionTaskCompletedEventId">The value to set for the DecisionTaskCompletedEventId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithDecisionTaskCompletedEventId(long decisionTaskCompletedEventId) { this.decisionTaskCompletedEventId = decisionTaskCompletedEventId; return this; } // Check to see if DecisionTaskCompletedEventId property is set internal bool IsSetDecisionTaskCompletedEventId() { return this.decisionTaskCompletedEventId.HasValue; } /// <summary> /// The <c>runId</c> of the new workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 64</description> /// </item> /// </list> /// </para> /// </summary> public string NewExecutionRunId { get { return this.newExecutionRunId; } set { this.newExecutionRunId = value; } } /// <summary> /// Sets the NewExecutionRunId property /// </summary> /// <param name="newExecutionRunId">The value to set for the NewExecutionRunId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithNewExecutionRunId(string newExecutionRunId) { this.newExecutionRunId = newExecutionRunId; return this; } // Check to see if NewExecutionRunId property is set internal bool IsSetNewExecutionRunId() { return this.newExecutionRunId != null; } /// <summary> /// The total duration allowed for the new workflow execution. The valid values are integers greater than or equal to <c>0</c>. An integer value /// can be used to specify the duration in seconds while <c>NONE</c> can be used to specify unlimited duration. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string ExecutionStartToCloseTimeout { get { return this.executionStartToCloseTimeout; } set { this.executionStartToCloseTimeout = value; } } /// <summary> /// Sets the ExecutionStartToCloseTimeout property /// </summary> /// <param name="executionStartToCloseTimeout">The value to set for the ExecutionStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithExecutionStartToCloseTimeout(string executionStartToCloseTimeout) { this.executionStartToCloseTimeout = executionStartToCloseTimeout; return this; } // Check to see if ExecutionStartToCloseTimeout property is set internal bool IsSetExecutionStartToCloseTimeout() { return this.executionStartToCloseTimeout != null; } /// <summary> /// Represents a task list. /// /// </summary> public TaskList TaskList { get { return this.taskList; } set { this.taskList = value; } } /// <summary> /// Sets the TaskList property /// </summary> /// <param name="taskList">The value to set for the TaskList property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithTaskList(TaskList taskList) { this.taskList = taskList; return this; } // Check to see if TaskList property is set internal bool IsSetTaskList() { return this.taskList != null; } /// <summary> /// The maximum duration of decision tasks for the new workflow execution. The valid values are integers greater than or equal to <c>0</c>. An /// integer value can be used to specify the duration in seconds while <c>NONE</c> can be used to specify unlimited duration. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string TaskStartToCloseTimeout { get { return this.taskStartToCloseTimeout; } set { this.taskStartToCloseTimeout = value; } } /// <summary> /// Sets the TaskStartToCloseTimeout property /// </summary> /// <param name="taskStartToCloseTimeout">The value to set for the TaskStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithTaskStartToCloseTimeout(string taskStartToCloseTimeout) { this.taskStartToCloseTimeout = taskStartToCloseTimeout; return this; } // Check to see if TaskStartToCloseTimeout property is set internal bool IsSetTaskStartToCloseTimeout() { return this.taskStartToCloseTimeout != null; } /// <summary> /// The policy to use for the child workflow executions of the new execution if it is terminated by calling the /// <a>TerminateWorkflowExecution</a> action explicitly or due to an expired timeout. The supported child policies are: <ul> /// <li><b>TERMINATE:</b> the child executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b> a request to cancel will be attempted for /// each child execution by recording a <c>WorkflowExecutionCancelRequested</c> event in its history. It is up to the decider to take /// appropriate actions when it receives an execution history with this event. </li> <li><b>ABANDON:</b> no action will be taken. The child /// executions will continue to run.</li> </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TERMINATE, REQUEST_CANCEL, ABANDON</description> /// </item> /// </list> /// </para> /// </summary> public string ChildPolicy { get { return this.childPolicy; } set { this.childPolicy = value; } } /// <summary> /// Sets the ChildPolicy property /// </summary> /// <param name="childPolicy">The value to set for the ChildPolicy property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithChildPolicy(string childPolicy) { this.childPolicy = childPolicy; return this; } // Check to see if ChildPolicy property is set internal bool IsSetChildPolicy() { return this.childPolicy != null; } /// <summary> /// The list of tags associated with the new workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 5</description> /// </item> /// </list> /// </para> /// </summary> public List<string> TagList { get { return this.tagList; } set { this.tagList = value; } } /// <summary> /// Adds elements to the TagList collection /// </summary> /// <param name="tagList">The values to add to the TagList collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithTagList(params string[] tagList) { foreach (string element in tagList) { this.tagList.Add(element); } return this; } /// <summary> /// Adds elements to the TagList collection /// </summary> /// <param name="tagList">The values to add to the TagList collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithTagList(IEnumerable<string> tagList) { foreach (string element in tagList) { this.tagList.Add(element); } return this; } // Check to see if TagList property is set internal bool IsSetTagList() { return this.tagList.Count > 0; } /// <summary> /// Represents a workflow type. /// /// </summary> public WorkflowType WorkflowType { get { return this.workflowType; } set { this.workflowType = value; } } /// <summary> /// Sets the WorkflowType property /// </summary> /// <param name="workflowType">The value to set for the WorkflowType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public WorkflowExecutionContinuedAsNewEventAttributes WithWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; return this; } // Check to see if WorkflowType property is set internal bool IsSetWorkflowType() { return this.workflowType != null; } } }
#region Namespaces using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Newtonsoft.Json; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using System.Reflection; using Autodesk.Revit.ApplicationServices; using System; #endregion namespace rvtmetaprop { [Transaction( TransactionMode.Manual )] public class Command : IExternalCommand { #region Create shared parameters /// <summary> /// Shared parameters filename; used only in case /// none is set. /// </summary> const string _shared_parameters_filename = "rvtmetaprop_shared_parameters.txt"; /// <summary> /// Create the shared parameters. /// </summary> static void CreateSharedParameters( Document doc, Dictionary<string, ParamDef> paramdefs, List<string> log ) { Application app = doc.Application; // Save original shared parameter file name string saveSharedParamsFileName = app.SharedParametersFilename; // Set up our own shared parameter file name string path = Path.GetTempPath(); path = Path.Combine( path, _shared_parameters_filename ); StreamWriter stream; stream = new StreamWriter( path ); stream.Close(); app.SharedParametersFilename = path; path = app.SharedParametersFilename; // Retrieve shared parameter file object DefinitionFile f = app.OpenSharedParameterFile(); List<string> keys = new List<string>( paramdefs.Keys ); keys.Sort(); foreach( string pname in keys ) { ParamDef def = paramdefs[pname]; // Create the category set for binding Binding binding = app.Create.NewInstanceBinding( def.Categories ); // Retrieve or create shared parameter group DefinitionGroup group = f.Groups.get_Item( def.GroupName ) ?? f.Groups.Create( def.GroupName ); // Retrieve or create the parameter; // we could check if they are already bound, // but it looks like Insert will just ignore // them in that case. Definition definition = group.Definitions.get_Item( pname ); try { if( null == definition ) { ExternalDefinitionCreationOptions opt = new ExternalDefinitionCreationOptions( pname, def.Type ); definition = group.Definitions.Create( opt ); } doc.ParameterBindings.Insert( definition, binding, def.BipGroup ); } catch( Exception ex ) { log.Add( string.Format( "Error: creating shared parameter '{0}': {1}", pname, ex.Message ) ); } } // Restore original shared parameter file name app.SharedParametersFilename = saveSharedParamsFileName; } #endregion // Create shared parameters public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; List<string> log = new List<string>(); log.Add( string.Format( "\r\n\r\n{0:yyyy-MM-dd HH:mm:ss}: rvtmetaprop begin", DateTime.Now ) ); int n; #region Select meta property input file string filename = ""; if( !FileSelector.Select( ref filename ) ) { return Result.Cancelled; } log.Add( "Input file selected: " + filename ); #endregion // Select meta property input file #region Deserialise meta properties from input file List<MetaProp> props = null; if( filename.ToLower().EndsWith( ".json" ) ) { string s = File.ReadAllText( filename ); props = JsonConvert .DeserializeObject<List<MetaProp>>( s ); } else if( filename.ToLower().EndsWith( ".csv" ) ) { IEnumerable<IList<string>> a = EasyCsv.FromFile( filename, true ); n = a.Count(); props = new List<MetaProp>( n ); foreach( IList<string> rec in a ) { props.Add( new MetaProp( rec ) ); } } else { message = "Unhandled meta property file format: " + Path.GetExtension( filename ); return Result.Failed; } log.Add( props.Count + " meta properties deserialised" ); #endregion // Deserialise meta properties from input file #region Remove 'Model' properties // Special 'Model' properties have extenalId prefix 'doc_' n = props.RemoveAll( m => m.IsModelProperty ); if( 0 < n ) { log.Add( n.ToString() + " 'Model' properties removed with" + " extenalId prefix 'doc_'" ); } #endregion // Remove 'Model' properties #region Remove 'File' and 'Link' properties // 'File' and 'Link' properties are not supported n = props.RemoveAll( m => m.IsFileOrLinkProperty ); if( 0 < n ) { log.Add( n.ToString() + " File and Link properties removed" ); } #endregion // Remove 'Model' properties #region Determine missing elements // Test that original elements are present in model IEnumerable<MetaProp> missing = props.Where<MetaProp>( m => null == doc.GetElement( m.externalId ) ); n = missing.Count(); if( 0 < n ) { string s = string.Format( "{0} invalid unique id{1}", n, ( 1 == n ) ? "" : "s" ); List<string> uids = new List<string>( missing .Select<MetaProp, string>( m => m.externalId ) .Distinct<string>() ); uids.Sort(); n = uids.Count; s += string.Format( " used in {0} meta propert{1}: ", n, ( 1 == n ) ? "y" : "ies" ); TaskDialog d = new TaskDialog( s ); log.Add( "Error: " + s ); s = " " + string.Join( "\r\n ", missing.Select<MetaProp, string>( m => m.component ) ); d.MainContent = s; d.Show(); log.Add( s ); props.RemoveAll( m => null == doc.GetElement( m.externalId ) ); } #endregion // Determine missing elements #region Determine parameters to use to store in // Determine what existing properties can be used; // for new ones, create dictionary mapping parameter // name to shared parameter definition input data Dictionary<string, ParamDef> paramdefs = new Dictionary<string, ParamDef>(); foreach( MetaProp m in props ) { m.CanSet = false; string s = m.displayName; // Check for existing parameters Element e = doc.GetElement( m.externalId ); IList<Parameter> a = e.GetParameters( m.displayName ); n = a.Count; if( 0 < n ) { // Property already exists on element if( 1 < n ) { log.Add( string.Format( "Error: element <{0}> already has {1} parameters named '{2}'", m.component, n, m.displayName ) ); } else { Parameter p = a[0]; Definition pdef = p.Definition; //ExternalDefinition extdef = pdef as ExternalDefinition; //InternalDefinition intdef = pdef as InternalDefinition; //log.Add( string.Format( "extdef {0}, intdef {1}", // null == extdef ? "<null>" : "ok", // null == intdef ? "<null>" : "ok" ) ); ParameterType ptyp = pdef.ParameterType; if( m.ParameterType != ptyp ) { log.Add( string.Format( "Error: element <{0}> parameter '{1}' has type {2} != meta property type {3}", m.component, m.displayName, ptyp.ToString(), m.metaType ) ); } else if( p.IsReadOnly ) { log.Add( string.Format( "Error: element <{0}> parameter '{1}' is read-only", m.component, m.displayName ) ); } else { m.CanSet = true; } } } else if( !m.IsDeleteOverride ) { // Property needs to be added to element // If several properties are added, // ensure they all go into the same // built -in parameter group. if( paramdefs.ContainsKey( s ) && !m.displayCategory.Equals( paramdefs[s].GroupName ) ) { log.Add( string.Format( "Error: element <{0}> parameter '{1}' " + "display category is {2} != {3} from " + "prior definition", m.component, m.displayName, m.displayCategory, paramdefs[s].GroupName ) ); } else { if( !paramdefs.ContainsKey( s ) ) { paramdefs.Add( s, new ParamDef( m ) ); } ParamDef def = paramdefs[s]; Category cat = e.Category; if( !def.Categories.Contains( cat ) ) { def.Categories.Insert( cat ); } m.CanSet = true; } } } props.RemoveAll( m => !m.CanSet ); #endregion // Determine parameters to use to store in using( TransactionGroup tg = new TransactionGroup( doc ) ) { tg.Start( "Import Forge Meta Properties" ); #region Create required shared parameter bindings // Create required shared parameter bindings n = paramdefs.Count; if( 0 < n ) { using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Create Shared Parameters" ); CreateSharedParameters( doc, paramdefs, log ); tx.Commit(); log.Add( string.Format( "Created {0} new shared parameter{1}", n, (1 == n ? "" : "s") ) ); } } #endregion // Create required shared parameter bindings #region Import Forge meta properties to parameter values // Set meta properties on elements using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Import Forge Meta Properties" ); n = props.Count; log.Add( string.Format( "Setting {0} propert{1}:", n, ( 1 == n ? "y" : "ies" ) ) ); foreach( MetaProp m in props ) { log.Add( string.Format( "Set {0} property {1} = '{2}'", m.component, m.displayName, m.DisplayString ) ); Element e = doc.GetElement( m.externalId ); IList<Parameter> a = e.GetParameters( m.displayName ); n = a.Count; // may be zero if shared param creation failed Debug.Assert( 0 == n || 1 == n, "expected one single parameter of this " + "name; all others are skipped" ); if( 0 < n ) { m.SetValue( a[0] ); } } tx.Commit(); } #endregion // Import Forge meta properties to parameter values tg.Assimilate(); //tg.Commit(); } log.Add( string.Format( "{0:yyyy-MM-dd HH:mm:ss}: rvtmetaprop completed.\r\n", DateTime.Now ) ); filename = Path.Combine( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ), "rvtmetaprop.log" ); File.AppendAllText( filename, string.Join( "\r\n", log ) ); Process.Start( filename ); return Result.Succeeded; } } }
// 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.Globalization; /// <summary> /// Convert.ToString(System.Int32,System.IFormatProvider) /// </summary> public class ConvertToString14 { public static int Main() { ConvertToString14 testObj = new ConvertToString14(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int32,System.IFormatProvider)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is a random Int32 and IFormatProvider is a null reference... "; string c_TEST_ID = "P001"; Int32 intValue = GetInt32(Int32.MinValue, Int32.MaxValue); IFormatProvider provider = null; String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int32 value is " + intValue; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is a random Int32 and IFormatProvider is en-US CultureInfo... "; string c_TEST_ID = "P002"; Int32 intValue = GetInt32(Int32.MinValue, Int32.MaxValue); IFormatProvider provider = new CultureInfo("en-US"); String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int32 value is " + intValue; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is a random Int32 and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P003"; Int32 intValue = GetInt32(Int32.MinValue, Int32.MaxValue); IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = intValue.ToString(provider); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int32 value is " + intValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify value is -32465641235 and IFormatProvider is user-defined NumberFormatInfo... "; string c_TEST_ID = "P004"; Int32 intValue = -465641235; NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); numberFormatInfo.NegativeSign = "minus "; numberFormatInfo.NumberDecimalSeparator = " point "; String actualValue = "minus 465641235"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, numberFormatInfo); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; errorDesc += "\n Int32 value is " + intValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify value is Int32.MaxValue and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P005"; Int32 intValue = Int32.MaxValue; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = "2147483647"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string c_TEST_DESC = "PosTest6: Verify value is Int32.MinValue and IFormatProvider is fr-FR CultureInfo... "; string c_TEST_ID = "P006"; Int32 intValue = Int32.MinValue; IFormatProvider provider = new CultureInfo("fr-FR"); String actualValue = "-2147483648"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(intValue, provider); if (actualValue != resValue) { string errorDesc = "value is not " + resValue + " as expected: Actual is " + actualValue; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return (minValue); } if (minValue < maxValue) { return (Int32)(minValue + TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue)); } } catch { throw; } return minValue; } #endregion }
// Copyright 2018 Yassine Riahi and Liam Flookes. Provided under a MIT License, see license file on github. // Used to generate a fastbuild .bff file from UnrealBuildTool to allow caching and distributed builds. // Tested with Windows 10, Visual Studio 2015/2017, Unreal Engine 4.19.1, FastBuild v0.95 // Durango is fully supported (Compiles with VS2015). // Orbis will likely require some changes. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Linq; using Tools.DotNETCommon; namespace UnrealBuildTool { class FASTBuild : ActionExecutor { /*---- Configurable User settings ----*/ // Used to specify a non-standard location for the FBuild.exe, for example if you have not added it to your PATH environment variable. public static string FBuildExePathOverride = ""; // Controls network build distribution private bool bEnableDistribution = true; // Controls whether to use caching at all. CachePath and CacheMode are only relevant if this is enabled. private bool bEnableCaching = false; // Location of the shared cache, it could be a local or network path (i.e: @"\\DESKTOP-BEAST\FASTBuildCache"). // Only relevant if bEnableCaching is true; private string CachePath = @"\\SharedDrive\FASTBuildCache"; public enum eCacheMode { ReadWrite, // This machine will both read and write to the cache ReadOnly, // This machine will only read from the cache, use for developer machines when you have centralized build machines WriteOnly, // This machine will only write from the cache, use for build machines when you have centralized build machines } // Cache access mode // Only relevant if bEnableCaching is true; private eCacheMode CacheMode = eCacheMode.ReadWrite; /*--------------------------------------*/ public override string Name { get { return "FASTBuild"; } } public static bool IsAvailable() { if (FBuildExePathOverride != "") { return File.Exists(FBuildExePathOverride); } // Get the name of the FASTBuild executable. string fbuild = "fbuild"; if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Win64) { fbuild = "fbuild.exe"; } // Search the path for it string PathVariable = Environment.GetEnvironmentVariable("PATH"); foreach (string SearchPath in PathVariable.Split(Path.PathSeparator)) { try { string PotentialPath = Path.Combine(SearchPath, fbuild); if (File.Exists(PotentialPath)) { return true; } } catch (ArgumentException) { // PATH variable may contain illegal characters; just ignore them. } } return false; } private HashSet<string> ForceLocalCompileModules = new HashSet<string>() {"Module.ProxyLODMeshReduction", "GoogleVRController"}; private enum FBBuildType { Windows, XBOne, PS4 } private FBBuildType BuildType = FBBuildType.Windows; private void DetectBuildType(List<Action> Actions) { foreach (Action action in Actions) { if (action.ActionType != ActionType.Compile && action.ActionType != ActionType.Link) continue; if (action.CommandPath.Contains("orbis")) { BuildType = FBBuildType.PS4; return; } else if (action.CommandArguments.Contains("Intermediate\\Build\\XboxOne")) { BuildType = FBBuildType.XBOne; return; } else if (action.CommandPath.Contains("Microsoft")) //Not a great test. { BuildType = FBBuildType.Windows; return; } } } private bool IsMSVC() { return BuildType == FBBuildType.Windows || BuildType == FBBuildType.XBOne; } private bool IsPS4() { return BuildType == FBBuildType.PS4; } private bool IsXBOnePDBUtil(Action action) { return action.CommandPath.Contains("XboxOnePDBFileUtil.exe"); } private bool IsPS4SymbolTool(Action action) { return action.CommandPath.Contains("PS4SymbolTool.exe"); } private string GetCompilerName() { switch (BuildType) { default: case FBBuildType.XBOne: case FBBuildType.Windows: return "UE4Compiler"; case FBBuildType.PS4: return "UE4PS4Compiler"; } } //Run FASTBuild on the list of actions. Relies on fbuild.exe being in the path. public override bool ExecuteActions(List<Action> Actions, bool bLogDetailedActionStats) { bool FASTBuildResult = true; if (Actions.Count > 0) { DetectBuildType(Actions); string FASTBuildFilePath = Path.Combine(UnrealBuildTool.EngineDirectory.FullName, "Intermediate", "Build", "fbuild.bff"); List<Action> LocalExecutorActions = new List<Action>(); if (CreateBffFile(Actions, FASTBuildFilePath, LocalExecutorActions)) { FASTBuildResult = ExecuteBffFile(FASTBuildFilePath); if (FASTBuildResult) { LocalExecutor localExecutor = new LocalExecutor(); FASTBuildResult = localExecutor.ExecuteActions(LocalExecutorActions, bLogDetailedActionStats); } } else { FASTBuildResult = false; } } return FASTBuildResult; } private void AddText(string StringToWrite) { byte[] Info = new System.Text.UTF8Encoding(true).GetBytes(StringToWrite); bffOutputFileStream.Write(Info, 0, Info.Length); } private string SubstituteEnvironmentVariables(string commandLineString) { string outputString = commandLineString.Replace("$(DurangoXDK)", "$DurangoXDK$"); outputString = outputString.Replace("$(SCE_ORBIS_SDK_DIR)", "$SCE_ORBIS_SDK_DIR$"); outputString = outputString.Replace("$(DXSDK_DIR)", "$DXSDK_DIR$"); outputString = outputString.Replace("$(CommonProgramFiles)", "$CommonProgramFiles$"); return outputString; } private Dictionary<string, string> ParseCommandLineOptions(string CompilerCommandLine, string[] SpecialOptions, bool SaveResponseFile = false, bool SkipInputFile = false) { Dictionary<string, string> ParsedCompilerOptions = new Dictionary<string, string>(); // Make sure we substituted the known environment variables with corresponding BFF friendly imported vars CompilerCommandLine = SubstituteEnvironmentVariables(CompilerCommandLine); // Some tricky defines /DTROUBLE=\"\\\" abc 123\\\"\" aren't handled properly by either Unreal or Fastbuild, but we do our best. char[] SpaceChar = { ' ' }; string[] RawTokens = CompilerCommandLine.Trim().Split(' '); List<string> ProcessedTokens = new List<string>(); bool QuotesOpened = false; string PartialToken = ""; string ResponseFilePath = ""; if (RawTokens.Length >= 1 && RawTokens[0].StartsWith("@\"")) //Response files are in 4.13 by default. Changing VCToolChain to not do this is probably better. { string responseCommandline = RawTokens[0]; // If we had spaces inside the response file path, we need to reconstruct the path. for (int i = 1; i < RawTokens.Length; ++i) { responseCommandline += " " + RawTokens[i]; } ResponseFilePath = responseCommandline.Substring(2, responseCommandline.Length - 3); // bit of a bodge to get the @"response.txt" path... try { string ResponseFileText = File.ReadAllText(ResponseFilePath); // Make sure we substituted the known environment variables with corresponding BFF friendly imported vars ResponseFileText = SubstituteEnvironmentVariables(ResponseFileText); string[] Separators = { "\n", " ", "\r" }; if (File.Exists(ResponseFilePath)) RawTokens = ResponseFileText.Split(Separators, StringSplitOptions.RemoveEmptyEntries); //Certainly not ideal } catch (Exception e) { Console.WriteLine("Looks like a response file in: " + CompilerCommandLine + ", but we could not load it! " + e.Message); ResponseFilePath = ""; } } // Raw tokens being split with spaces may have split up some two argument options and // paths with multiple spaces in them also need some love for (int i = 0; i < RawTokens.Length; ++i) { string Token = RawTokens[i]; if (string.IsNullOrEmpty(Token)) { if (ProcessedTokens.Count > 0 && QuotesOpened) { string CurrentToken = ProcessedTokens.Last(); CurrentToken += " "; } continue; } int numQuotes = 0; // Look for unescaped " symbols, we want to stick those strings into one token. for (int j = 0; j < Token.Length; ++j) { if (Token[j] == '\\') //Ignore escaped quotes ++j; else if (Token[j] == '"') numQuotes++; } // Defines can have escaped quotes and other strings inside them // so we consume tokens until we've closed any open unescaped parentheses. if ((Token.StartsWith("/D") || Token.StartsWith("-D")) && !QuotesOpened) { if (numQuotes == 0 || numQuotes == 2) { ProcessedTokens.Add(Token); } else { PartialToken = Token; ++i; bool AddedToken = false; for (; i < RawTokens.Length; ++i) { string NextToken = RawTokens[i]; if (string.IsNullOrEmpty(NextToken)) { PartialToken += " "; } else if (!NextToken.EndsWith("\\\"") && NextToken.EndsWith("\"")) //Looking for a token that ends with a non-escaped " { ProcessedTokens.Add(PartialToken + " " + NextToken); AddedToken = true; break; } else { PartialToken += " " + NextToken; } } if (!AddedToken) { Console.WriteLine("Warning! Looks like an unterminated string in tokens. Adding PartialToken and hoping for the best. Command line: " + CompilerCommandLine); ProcessedTokens.Add(PartialToken); } } continue; } if (!QuotesOpened) { if (numQuotes % 2 != 0) //Odd number of quotes in this token { PartialToken = Token + " "; QuotesOpened = true; } else { ProcessedTokens.Add(Token); } } else { if (numQuotes % 2 != 0) //Odd number of quotes in this token { ProcessedTokens.Add(PartialToken + Token); QuotesOpened = false; } else { PartialToken += Token + " "; } } } //Processed tokens should now have 'whole' tokens, so now we look for any specified special options foreach (string specialOption in SpecialOptions) { for (int i = 0; i < ProcessedTokens.Count; ++i) { if (ProcessedTokens[i] == specialOption && i + 1 < ProcessedTokens.Count) { ParsedCompilerOptions[specialOption] = ProcessedTokens[i + 1]; ProcessedTokens.RemoveRange(i, 2); break; } else if (ProcessedTokens[i].StartsWith(specialOption)) { ParsedCompilerOptions[specialOption] = ProcessedTokens[i].Replace(specialOption, null); ProcessedTokens.RemoveAt(i); break; } } } //The search for the input file... we take the first non-argument we can find if (!SkipInputFile) { for (int i = 0; i < ProcessedTokens.Count; ++i) { string Token = ProcessedTokens[i]; if (Token.Length == 0) { continue; } if (Token == "/I" || Token == "/l" || Token == "/D" || Token == "-D" || Token == "-x" || Token == "-include") // Skip tokens with values, I for cpp includes, l for resource compiler includes { ++i; } else if (!Token.StartsWith("/") && !Token.StartsWith("-") && !Token.StartsWith("\"-")) { ParsedCompilerOptions["InputFile"] = Token; ProcessedTokens.RemoveAt(i); break; } } } ParsedCompilerOptions["OtherOptions"] = string.Join(" ", ProcessedTokens) + " "; if (SaveResponseFile && !string.IsNullOrEmpty(ResponseFilePath)) { ParsedCompilerOptions["@"] = ResponseFilePath; } return ParsedCompilerOptions; } private List<Action> SortActions(List<Action> InActions) { List<Action> Actions = InActions; int NumSortErrors = 0; for (int ActionIndex = 0; ActionIndex < InActions.Count; ActionIndex++) { Action Action = InActions[ActionIndex]; foreach (FileItem Item in Action.PrerequisiteItems) { if (Item.ProducingAction != null && InActions.Contains(Item.ProducingAction)) { int DepIndex = InActions.IndexOf(Item.ProducingAction); if (DepIndex > ActionIndex) { NumSortErrors++; } } } } if (NumSortErrors > 0) { Actions = new List<Action>(); var UsedActions = new HashSet<int>(); for (int ActionIndex = 0; ActionIndex < InActions.Count; ActionIndex++) { if (UsedActions.Contains(ActionIndex)) { continue; } Action Action = InActions[ActionIndex]; foreach (FileItem Item in Action.PrerequisiteItems) { if (Item.ProducingAction != null && InActions.Contains(Item.ProducingAction)) { int DepIndex = InActions.IndexOf(Item.ProducingAction); if (UsedActions.Contains(DepIndex)) { continue; } Actions.Add(Item.ProducingAction); UsedActions.Add(DepIndex); } } Actions.Add(Action); UsedActions.Add(ActionIndex); } for (int ActionIndex = 0; ActionIndex < Actions.Count; ActionIndex++) { Action Action = Actions[ActionIndex]; foreach (FileItem Item in Action.PrerequisiteItems) { if (Item.ProducingAction != null && Actions.Contains(Item.ProducingAction)) { int DepIndex = Actions.IndexOf(Item.ProducingAction); if (DepIndex > ActionIndex) { Console.WriteLine("Action is not topologically sorted."); Console.WriteLine(" {0} {1}", Action.CommandPath, Action.CommandArguments); Console.WriteLine("Dependency"); Console.WriteLine(" {0} {1}", Item.ProducingAction.CommandPath, Item.ProducingAction.CommandArguments); throw new BuildException("Cyclical Dependency in action graph."); } } } } } return Actions; } private string GetOptionValue(Dictionary<string, string> OptionsDictionary, string Key, Action Action, bool ProblemIfNotFound = false) { string Value = string.Empty; if (OptionsDictionary.TryGetValue(Key, out Value)) { return Value.Trim(new Char[] { '\"' }); } if (ProblemIfNotFound) { Console.WriteLine("We failed to find " + Key + ", which may be a problem."); Console.WriteLine("Action.CommandArguments: " + Action.CommandArguments); } return Value; } public string GetRegistryValue(string keyName, string valueName, object defaultValue) { object returnValue = (string)Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\" + keyName, valueName, defaultValue); if (returnValue != null) return returnValue.ToString(); returnValue = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\" + keyName, valueName, defaultValue); if (returnValue != null) return returnValue.ToString(); returnValue = (string)Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\" + keyName, valueName, defaultValue); if (returnValue != null) return returnValue.ToString(); returnValue = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Wow6432Node\\" + keyName, valueName, defaultValue); if (returnValue != null) return returnValue.ToString(); return defaultValue.ToString(); } private void WriteEnvironmentSetup() { DirectoryReference VCInstallDir = null; string VCToolPath64 = ""; VCEnvironment VCEnv = null; try { // This may fail if the caller emptied PATH; we try to ignore the problem since // it probably means we are building for another platform. if (BuildType == FBBuildType.Windows) { VCEnv = VCEnvironment.Create(WindowsPlatform.GetDefaultCompiler(null), CppPlatform.Win64, null, null); } else if (BuildType == FBBuildType.XBOne) { // If you have XboxOne source access, uncommenting the line below will be better for selecting the appropriate version of the compiler. // Translate the XboxOne compiler to the right Windows compiler to set the VC environment vars correctly... WindowsCompiler windowsCompiler = XboxOnePlatform.GetDefaultCompiler() == XboxOneCompiler.VisualStudio2015 ? WindowsCompiler.VisualStudio2015 : WindowsCompiler.VisualStudio2017; VCEnv = VCEnvironment.Create(windowsCompiler, CppPlatform.Win64, null, null); } } catch (Exception) { Console.WriteLine("Failed to get Visual Studio environment."); } // Copy environment into a case-insensitive dictionary for easier key lookups Dictionary<string, string> envVars = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { envVars[(string)entry.Key] = (string)entry.Value; } if (envVars.ContainsKey("CommonProgramFiles")) { AddText("#import CommonProgramFiles\n"); } if (envVars.ContainsKey("DXSDK_DIR")) { AddText("#import DXSDK_DIR\n"); } if (envVars.ContainsKey("DurangoXDK")) { AddText("#import DurangoXDK\n"); } if (VCEnv != null) { string platformVersionNumber = "VSVersionUnknown"; switch (VCEnv.Compiler) { case WindowsCompiler.VisualStudio2015: platformVersionNumber = "140"; break; case WindowsCompiler.VisualStudio2017: // For now we are working with the 140 version, might need to change to 141 or 150 depending on the version of the Toolchain you chose // to install platformVersionNumber = "140"; break; default: string exceptionString = "Error: Unsupported Visual Studio Version."; Console.WriteLine(exceptionString); throw new BuildException(exceptionString); } if (!WindowsPlatform.TryGetVSInstallDir(WindowsPlatform.GetDefaultCompiler(null), out VCInstallDir)) { string exceptionString = "Error: Cannot locate Visual Studio Installation."; Console.WriteLine(exceptionString); throw new BuildException(exceptionString); } VCToolPath64 = VCEnvironment.GetVCToolPath64(WindowsPlatform.GetDefaultCompiler(null), VCEnv.ToolChainDir).ToString(); string debugVCToolPath64 = VCEnv.CompilerPath.Directory.ToString(); AddText(string.Format(".WindowsSDKBasePath = '{0}'\n", VCEnv.WindowsSdkDir)); AddText("Compiler('UE4ResourceCompiler') \n{\n"); AddText(string.Format("\t.Executable = '{0}'\n", VCEnv.ResourceCompilerPath)); AddText("\t.CompilerFamily = 'custom'\n"); AddText("}\n\n"); AddText("Compiler('UE4Compiler') \n{\n"); AddText(string.Format("\t.Root = '{0}'\n", VCEnv.CompilerPath.Directory)); AddText("\t.Executable = '$Root$/cl.exe'\n"); AddText("\t.ExtraFiles =\n\t{\n"); AddText("\t\t'$Root$/c1.dll'\n"); AddText("\t\t'$Root$/c1xx.dll'\n"); AddText("\t\t'$Root$/c2.dll'\n"); if (File.Exists(FileReference.Combine(VCEnv.CompilerPath.Directory, "1033/clui.dll").ToString())) //Check English first... { AddText("\t\t'$Root$/1033/clui.dll'\n"); } else { var numericDirectories = Directory.GetDirectories(VCToolPath64).Where(d => Path.GetFileName(d).All(char.IsDigit)); var cluiDirectories = numericDirectories.Where(d => Directory.GetFiles(d, "clui.dll").Any()); if (cluiDirectories.Any()) { AddText(string.Format("\t\t'$Root$/{0}/clui.dll'\n", Path.GetFileName(cluiDirectories.First()))); } } AddText("\t\t'$Root$/mspdbsrv.exe'\n"); AddText("\t\t'$Root$/mspdbcore.dll'\n"); AddText(string.Format("\t\t'$Root$/mspft{0}.dll'\n", platformVersionNumber)); AddText(string.Format("\t\t'$Root$/msobj{0}.dll'\n", platformVersionNumber)); AddText(string.Format("\t\t'$Root$/mspdb{0}.dll'\n", platformVersionNumber)); if (VCEnv.Compiler == WindowsCompiler.VisualStudio2015) { AddText(string.Format("\t\t'{0}/VC/redist/x64/Microsoft.VC{1}.CRT/msvcp{2}.dll'\n", VCInstallDir.ToString(), platformVersionNumber, platformVersionNumber)); AddText(string.Format("\t\t'{0}/VC/redist/x64/Microsoft.VC{1}.CRT/vccorlib{2}.dll'\n", VCInstallDir.ToString(), platformVersionNumber, platformVersionNumber)); } else { //VS 2017 is really confusing in terms of version numbers and paths so these values might need to be modified depending on what version of the tool chain you // chose to install. AddText(string.Format("\t\t'{0}/VC/Redist/MSVC/14.13.26020/x64/Microsoft.VC141.CRT/msvcp{1}.dll'\n", VCInstallDir.ToString(), platformVersionNumber)); AddText(string.Format("\t\t'{0}/VC/Redist/MSVC/14.13.26020/x64/Microsoft.VC141.CRT/vccorlib{1}.dll'\n", VCInstallDir.ToString(), platformVersionNumber)); } AddText("\t}\n"); //End extra files AddText("}\n\n"); //End compiler } if (envVars.ContainsKey("SCE_ORBIS_SDK_DIR")) { AddText(string.Format(".SCE_ORBIS_SDK_DIR = '{0}'\n", envVars["SCE_ORBIS_SDK_DIR"])); AddText(string.Format(".PS4BasePath = '{0}/host_tools/bin'\n\n", envVars["SCE_ORBIS_SDK_DIR"])); AddText("Compiler('UE4PS4Compiler') \n{\n"); AddText("\t.Executable = '$PS4BasePath$/orbis-clang.exe'\n"); AddText("\t.ExtraFiles = '$PS4BasePath$/orbis-snarl.exe'\n"); AddText("}\n\n"); } AddText("Settings \n{\n"); // Optional cachePath user setting if (bEnableCaching && CachePath != "") { AddText(string.Format("\t.CachePath = '{0}'\n", CachePath)); } //Start Environment AddText("\t.Environment = \n\t{\n"); if (VCEnv != null) { AddText(string.Format("\t\t\"PATH={0}\\Common7\\IDE\\;{1}\",\n", VCInstallDir.ToString(), VCToolPath64)); if (VCEnv.IncludePaths.Count() > 0) { AddText(string.Format("\t\t\"INCLUDE={0}\",\n", String.Join(";", VCEnv.IncludePaths.Select(x => x)))); } if (VCEnv.LibraryPaths.Count() > 0) { AddText(string.Format("\t\t\"LIB={0}\",\n", String.Join(";", VCEnv.LibraryPaths.Select(x => x)))); } } if (envVars.ContainsKey("TMP")) AddText(string.Format("\t\t\"TMP={0}\",\n", envVars["TMP"])); if (envVars.ContainsKey("SystemRoot")) AddText(string.Format("\t\t\"SystemRoot={0}\",\n", envVars["SystemRoot"])); if (envVars.ContainsKey("INCLUDE")) AddText(string.Format("\t\t\"INCLUDE={0}\",\n", envVars["INCLUDE"])); if (envVars.ContainsKey("LIB")) AddText(string.Format("\t\t\"LIB={0}\",\n", envVars["LIB"])); AddText("\t}\n"); //End environment AddText("}\n\n"); //End Settings } private void AddCompileAction(Action Action, int ActionIndex, List<int> DependencyIndices) { string CompilerName = GetCompilerName(); if (Action.CommandPath.Contains("rc.exe")) { CompilerName = "UE4ResourceCompiler"; } string[] SpecialCompilerOptions = { "/Fo", "/fo", "/Yc", "/Yu", "/Fp", "-o" }; var ParsedCompilerOptions = ParseCommandLineOptions(Action.CommandArguments, SpecialCompilerOptions); string OutputObjectFileName = GetOptionValue(ParsedCompilerOptions, IsMSVC() ? "/Fo" : "-o", Action, ProblemIfNotFound: !IsMSVC()); if (IsMSVC() && string.IsNullOrEmpty(OutputObjectFileName)) // Didn't find /Fo, try /fo { OutputObjectFileName = GetOptionValue(ParsedCompilerOptions, "/fo", Action, ProblemIfNotFound: true); } if (string.IsNullOrEmpty(OutputObjectFileName)) //No /Fo or /fo, we're probably in trouble. { Console.WriteLine("We have no OutputObjectFileName. Bailing."); return; } string IntermediatePath = Path.GetDirectoryName(OutputObjectFileName); if (string.IsNullOrEmpty(IntermediatePath)) { Console.WriteLine("We have no IntermediatePath. Bailing."); Console.WriteLine("Our Action.CommandArguments were: " + Action.CommandArguments); return; } string InputFile = GetOptionValue(ParsedCompilerOptions, "InputFile", Action, ProblemIfNotFound: true); if (string.IsNullOrEmpty(InputFile)) { Console.WriteLine("We have no InputFile. Bailing."); return; } AddText(string.Format("ObjectList('Action_{0}')\n{{\n", ActionIndex)); AddText(string.Format("\t.Compiler = '{0}' \n", CompilerName)); AddText(string.Format("\t.CompilerInputFiles = \"{0}\"\n", InputFile)); AddText(string.Format("\t.CompilerOutputPath = \"{0}\"\n", IntermediatePath)); bool bSkipDistribution = false; foreach (var it in ForceLocalCompileModules) { if (Path.GetFullPath(InputFile).Contains(it)) { bSkipDistribution = true; break; } } if (!Action.bCanExecuteRemotely || !Action.bCanExecuteRemotelyWithSNDBS || bSkipDistribution) { AddText(string.Format("\t.AllowDistribution = false\n")); } string OtherCompilerOptions = GetOptionValue(ParsedCompilerOptions, "OtherOptions", Action); string CompilerOutputExtension = ".unset"; if (ParsedCompilerOptions.ContainsKey("/Yc")) //Create PCH { string PCHIncludeHeader = GetOptionValue(ParsedCompilerOptions, "/Yc", Action, ProblemIfNotFound: true); string PCHOutputFile = GetOptionValue(ParsedCompilerOptions, "/Fp", Action, ProblemIfNotFound: true); AddText(string.Format("\t.CompilerOptions = '\"%1\" /Fo\"%2\" /Fp\"{0}\" /Yu\"{1}\" {2} '\n", PCHOutputFile, PCHIncludeHeader, OtherCompilerOptions)); AddText(string.Format("\t.PCHOptions = '\"%1\" /Fp\"%2\" /Yc\"{0}\" {1} /Fo\"{2}\"'\n", PCHIncludeHeader, OtherCompilerOptions, OutputObjectFileName)); AddText(string.Format("\t.PCHInputFile = \"{0}\"\n", InputFile)); AddText(string.Format("\t.PCHOutputFile = \"{0}\"\n", PCHOutputFile)); CompilerOutputExtension = ".obj"; } else if (ParsedCompilerOptions.ContainsKey("/Yu")) //Use PCH { string PCHIncludeHeader = GetOptionValue(ParsedCompilerOptions, "/Yu", Action, ProblemIfNotFound: true); string PCHOutputFile = GetOptionValue(ParsedCompilerOptions, "/Fp", Action, ProblemIfNotFound: true); string PCHToForceInclude = PCHOutputFile.Replace(".pch", ""); AddText(string.Format("\t.CompilerOptions = '\"%1\" /Fo\"%2\" /Fp\"{0}\" /Yu\"{1}\" /FI\"{2}\" {3} '\n", PCHOutputFile, PCHIncludeHeader, PCHToForceInclude, OtherCompilerOptions)); CompilerOutputExtension = ".cpp.obj"; } else { if (CompilerName == "UE4ResourceCompiler") { AddText(string.Format("\t.CompilerOptions = '{0} /fo\"%2\" \"%1\" '\n", OtherCompilerOptions)); CompilerOutputExtension = Path.GetExtension(InputFile) + ".res"; } else { if (IsMSVC()) { AddText(string.Format("\t.CompilerOptions = '{0} /Fo\"%2\" \"%1\" '\n", OtherCompilerOptions)); CompilerOutputExtension = ".cpp.obj"; } else { AddText(string.Format("\t.CompilerOptions = '{0} -o \"%2\" \"%1\" '\n", OtherCompilerOptions)); CompilerOutputExtension = ".cpp.o"; } } } AddText(string.Format("\t.CompilerOutputExtension = '{0}' \n", CompilerOutputExtension)); if (DependencyIndices.Count > 0) { List<string> DependencyNames = DependencyIndices.ConvertAll(x => string.Format("'Action_{0}'", x)); AddText(string.Format("\t.PreBuildDependencies = {{ {0} }}\n", string.Join(",", DependencyNames.ToArray()))); } AddText(string.Format("}}\n\n")); } private void AddLinkAction(List<Action> Actions, int ActionIndex, List<int> DependencyIndices) { Action Action = Actions[ActionIndex]; string[] SpecialLinkerOptions = { "/OUT:", "@", "-o" }; var ParsedLinkerOptions = ParseCommandLineOptions(Action.CommandArguments, SpecialLinkerOptions, SaveResponseFile: true, SkipInputFile: Action.CommandPath.Contains("orbis-clang")); string OutputFile; if (IsXBOnePDBUtil(Action)) { OutputFile = ParsedLinkerOptions["OtherOptions"].Trim(' ').Trim('"'); } else if (IsMSVC()) { OutputFile = GetOptionValue(ParsedLinkerOptions, "/OUT:", Action, ProblemIfNotFound: true); } else //PS4 { OutputFile = GetOptionValue(ParsedLinkerOptions, "-o", Action, ProblemIfNotFound: false); if (string.IsNullOrEmpty(OutputFile)) { OutputFile = GetOptionValue(ParsedLinkerOptions, "InputFile", Action, ProblemIfNotFound: true); } } if (string.IsNullOrEmpty(OutputFile)) { Console.WriteLine("Failed to find output file. Bailing."); return; } string ResponseFilePath = GetOptionValue(ParsedLinkerOptions, "@", Action); string OtherCompilerOptions = GetOptionValue(ParsedLinkerOptions, "OtherOptions", Action); List<int> PrebuildDependencies = new List<int>(); if (IsXBOnePDBUtil(Action)) { AddText(string.Format("Exec('Action_{0}')\n{{\n", ActionIndex)); AddText(string.Format("\t.ExecExecutable = '{0}'\n", Action.CommandPath)); AddText(string.Format("\t.ExecArguments = '{0}'\n", Action.CommandArguments)); AddText(string.Format("\t.ExecInput = {{ {0} }} \n", ParsedLinkerOptions["InputFile"])); AddText(string.Format("\t.ExecOutput = '{0}' \n", OutputFile)); AddText(string.Format("\t.PreBuildDependencies = {{ {0} }} \n", ParsedLinkerOptions["InputFile"])); AddText(string.Format("}}\n\n")); } else if (IsPS4SymbolTool(Action)) { string searchString = "-map=\""; int execArgumentStart = Action.CommandArguments.LastIndexOf(searchString) + searchString.Length; int execArgumentEnd = Action.CommandArguments.IndexOf("\"", execArgumentStart); string ExecOutput = Action.CommandArguments.Substring(execArgumentStart, execArgumentEnd - execArgumentStart); AddText(string.Format("Exec('Action_{0}')\n{{\n", ActionIndex)); AddText(string.Format("\t.ExecExecutable = '{0}'\n", Action.CommandPath)); AddText(string.Format("\t.ExecArguments = '{0}'\n", Action.CommandArguments)); AddText(string.Format("\t.ExecOutput = '{0}'\n", ExecOutput)); AddText(string.Format("\t.PreBuildDependencies = {{ 'Action_{0}' }} \n", ActionIndex - 1)); AddText(string.Format("}}\n\n")); } else if (Action.CommandPath.Contains("lib.exe") || Action.CommandPath.Contains("orbis-snarl")) { if (DependencyIndices.Count > 0) { for (int i = 0; i < DependencyIndices.Count; ++i) //Don't specify pch or resource files, they have the wrong name and the response file will have them anyways. { int depIndex = DependencyIndices[i]; foreach (FileItem item in Actions[depIndex].ProducedItems) { if (item.ToString().Contains(".pch") || item.ToString().Contains(".res")) { DependencyIndices.RemoveAt(i); i--; PrebuildDependencies.Add(depIndex); break; } } } } AddText(string.Format("Library('Action_{0}')\n{{\n", ActionIndex)); AddText(string.Format("\t.Compiler = '{0}'\n", GetCompilerName())); if (IsMSVC()) AddText(string.Format("\t.CompilerOptions = '\"%1\" /Fo\"%2\" /c'\n")); else AddText(string.Format("\t.CompilerOptions = '\"%1\" -o \"%2\" -c'\n")); AddText(string.Format("\t.CompilerOutputPath = \"{0}\"\n", Path.GetDirectoryName(OutputFile))); AddText(string.Format("\t.Librarian = '{0}' \n", Action.CommandPath)); if (!string.IsNullOrEmpty(ResponseFilePath)) { if (IsMSVC()) // /ignore:4042 to turn off the linker warning about the output option being present twice (command-line + rsp file) AddText(string.Format("\t.LibrarianOptions = ' /OUT:\"%2\" /ignore:4042 @\"{0}\" \"%1\"' \n", ResponseFilePath)); else if (IsPS4()) AddText(string.Format("\t.LibrarianOptions = '\"%2\" @\"%1\"' \n", ResponseFilePath)); else AddText(string.Format("\t.LibrarianOptions = '\"%2\" @\"%1\" {0}' \n", OtherCompilerOptions)); } else { if (IsMSVC()) AddText(string.Format("\t.LibrarianOptions = ' /OUT:\"%2\" {0} \"%1\"' \n", OtherCompilerOptions)); } if (DependencyIndices.Count > 0) { List<string> DependencyNames = DependencyIndices.ConvertAll(x => string.Format("'Action_{0}'", x)); if (IsPS4()) AddText(string.Format("\t.LibrarianAdditionalInputs = {{ '{0}' }} \n", ResponseFilePath)); // Hack...Because FastBuild needs at least one Input file else if (!string.IsNullOrEmpty(ResponseFilePath)) AddText(string.Format("\t.LibrarianAdditionalInputs = {{ {0} }} \n", DependencyNames[0])); // Hack...Because FastBuild needs at least one Input file else if (IsMSVC()) AddText(string.Format("\t.LibrarianAdditionalInputs = {{ {0} }} \n", string.Join(",", DependencyNames.ToArray()))); PrebuildDependencies.AddRange(DependencyIndices); } else { string InputFile = GetOptionValue(ParsedLinkerOptions, "InputFile", Action, ProblemIfNotFound: true); if (InputFile != null && InputFile.Length > 0) AddText(string.Format("\t.LibrarianAdditionalInputs = {{ '{0}' }} \n", InputFile)); } if (PrebuildDependencies.Count > 0) { List<string> PrebuildDependencyNames = PrebuildDependencies.ConvertAll(x => string.Format("'Action_{0}'", x)); AddText(string.Format("\t.PreBuildDependencies = {{ {0} }} \n", string.Join(",", PrebuildDependencyNames.ToArray()))); } AddText(string.Format("\t.LibrarianOutput = '{0}' \n", OutputFile)); AddText(string.Format("}}\n\n")); } else if (Action.CommandPath.Contains("link.exe") || Action.CommandPath.Contains("orbis-clang")) { if (DependencyIndices.Count > 0) //Insert a dummy node to make sure all of the dependencies are finished. //If FASTBuild supports PreBuildDependencies on the Executable action we can remove this. { string dummyText = string.IsNullOrEmpty(ResponseFilePath) ? GetOptionValue(ParsedLinkerOptions, "InputFile", Action) : ResponseFilePath; File.SetLastAccessTimeUtc(dummyText, DateTime.UtcNow); AddText(string.Format("Copy('Action_{0}_dummy')\n{{ \n", ActionIndex)); AddText(string.Format("\t.Source = '{0}' \n", dummyText)); AddText(string.Format("\t.Dest = '{0}' \n", dummyText + ".dummy")); List<string> DependencyNames = DependencyIndices.ConvertAll(x => string.Format("\t\t'Action_{0}', ;{1}", x, Actions[x].StatusDescription)); AddText(string.Format("\t.PreBuildDependencies = {{\n{0}\n\t}} \n", string.Join("\n", DependencyNames.ToArray()))); AddText(string.Format("}}\n\n")); } AddText(string.Format("Executable('Action_{0}')\n{{ \n", ActionIndex)); AddText(string.Format("\t.Linker = '{0}' \n", Action.CommandPath)); if (DependencyIndices.Count == 0) { AddText(string.Format("\t.Libraries = {{ '{0}' }} \n", ResponseFilePath)); if (IsMSVC()) { if (BuildType == FBBuildType.XBOne) { AddText(string.Format("\t.LinkerOptions = '/TLBOUT:\"%1\" /Out:\"%2\" @\"{0}\" {1} ' \n", ResponseFilePath, OtherCompilerOptions)); // The TLBOUT is a huge bodge to consume the %1. } else { // /ignore:4042 to turn off the linker warning about the output option being present twice (command-line + rsp file) AddText(string.Format("\t.LinkerOptions = '/TLBOUT:\"%1\" /ignore:4042 /Out:\"%2\" @\"{0}\" ' \n", ResponseFilePath)); // The TLBOUT is a huge bodge to consume the %1. } } else AddText(string.Format("\t.LinkerOptions = '{0} -o \"%2\" @\"%1\"' \n", OtherCompilerOptions)); // The MQ is a huge bodge to consume the %1. } else { AddText(string.Format("\t.Libraries = 'Action_{0}_dummy' \n", ActionIndex)); if (IsMSVC()) { if (BuildType == FBBuildType.XBOne) { AddText(string.Format("\t.LinkerOptions = '/TLBOUT:\"%1\" /Out:\"%2\" @\"{0}\" {1} ' \n", ResponseFilePath, OtherCompilerOptions)); // The TLBOUT is a huge bodge to consume the %1. } else { AddText(string.Format("\t.LinkerOptions = '/TLBOUT:\"%1\" /Out:\"%2\" @\"{0}\" ' \n", ResponseFilePath)); // The TLBOUT is a huge bodge to consume the %1. } } else AddText(string.Format("\t.LinkerOptions = '{0} -o \"%2\" @\"%1\"' \n", OtherCompilerOptions)); // The MQ is a huge bodge to consume the %1. } AddText(string.Format("\t.LinkerOutput = '{0}' \n", OutputFile)); AddText(string.Format("}}\n\n")); } } private FileStream bffOutputFileStream = null; private bool CreateBffFile(List<Action> InActions, string BffFilePath, List<Action> LocalExecutorActions) { List<Action> Actions = SortActions(InActions); try { bffOutputFileStream = new FileStream(BffFilePath, FileMode.Create, FileAccess.Write); WriteEnvironmentSetup(); //Compiler, environment variables and base paths int numFastBuildActions = 0; for (int ActionIndex = 0; ActionIndex < Actions.Count; ActionIndex++) { Action Action = Actions[ActionIndex]; // Resolve dependencies List<int> DependencyIndices = new List<int>(); foreach (FileItem Item in Action.PrerequisiteItems) { if (Item.ProducingAction != null) { int ProducingActionIndex = Actions.IndexOf(Item.ProducingAction); if (ProducingActionIndex >= 0) { DependencyIndices.Add(ProducingActionIndex); } } } AddText(string.Format("// \"{0}\" {1}\n", Action.CommandPath, Action.CommandArguments)); switch (Action.ActionType) { case ActionType.Compile: AddCompileAction(Action, ActionIndex, DependencyIndices); ++numFastBuildActions; break; case ActionType.Link: AddLinkAction(Actions, ActionIndex, DependencyIndices); ++numFastBuildActions; break; case ActionType.BuildProject: LocalExecutorActions.Add(Action); break; default: Console.WriteLine("Fastbuild is ignoring an unsupported action: " + Action.ActionType.ToString()); break; } } AddText("Alias( 'all' ) \n{\n"); AddText("\t.Targets = { \n"); for (int ActionIndex = 0; ActionIndex < numFastBuildActions; ActionIndex++) { AddText(string.Format("\t\t'Action_{0}'{1}", ActionIndex, ActionIndex < (numFastBuildActions - 1) ? ",\n" : "\n\t}\n")); } AddText("}\n"); bffOutputFileStream.Close(); } catch (Exception e) { Console.WriteLine("Exception while creating bff file: " + e.ToString()); return false; } return true; } private bool ExecuteBffFile(string BffFilePath) { string cacheArgument = ""; if (bEnableCaching) { switch (CacheMode) { case eCacheMode.ReadOnly: cacheArgument = "-cacheread"; break; case eCacheMode.WriteOnly: cacheArgument = "-cachewrite"; break; case eCacheMode.ReadWrite: cacheArgument = "-cache"; break; } } string distArgument = bEnableDistribution ? "-dist" : ""; //Interesting flags for FASTBuild: -nostoponerror, -verbose, -monitor (if FASTBuild Monitor Visual Studio Extension is installed!) // Yassine: The -clean is to bypass the FastBuild internal dependencies checks (cached in the fdb) as it could create some conflicts with UBT. // Basically we want FB to stupidly compile what UBT tells it to. string FBCommandLine = string.Format("-monitor -summary {0} {1} -ide -clean -config {2}", distArgument, cacheArgument, BffFilePath); ProcessStartInfo FBStartInfo = new ProcessStartInfo(string.IsNullOrEmpty(FBuildExePathOverride) ? "fbuild" : FBuildExePathOverride, FBCommandLine); FBStartInfo.UseShellExecute = false; FBStartInfo.WorkingDirectory = Path.Combine(UnrealBuildTool.EngineDirectory.MakeRelativeTo(DirectoryReference.GetCurrentDirectory()), "Source"); try { Process FBProcess = new Process(); FBProcess.StartInfo = FBStartInfo; FBStartInfo.RedirectStandardError = true; FBStartInfo.RedirectStandardOutput = true; FBProcess.EnableRaisingEvents = true; DataReceivedEventHandler OutputEventHandler = (Sender, Args) => { if (Args.Data != null) Console.WriteLine(Args.Data); }; FBProcess.OutputDataReceived += OutputEventHandler; FBProcess.ErrorDataReceived += OutputEventHandler; FBProcess.Start(); FBProcess.BeginOutputReadLine(); FBProcess.BeginErrorReadLine(); FBProcess.WaitForExit(); return FBProcess.ExitCode == 0; } catch (Exception e) { Console.WriteLine("Exception launching fbuild process. Is it in your path?" + e.ToString()); return false; } } } }
using UnityEngine; using UnityEditor; public class MegaFFDWarpEditor : MegaWarpEditor { public override string GetHelpString() { return "Bend Warp Modifier by Chris West"; } Vector3 pm = new Vector3(); public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers\\ffd_help.png"); } bool showpoints = false; public static void CreateFFDWarp(string type, System.Type classtype) { Vector3 pos = Vector3.zero; if ( UnityEditor.SceneView.lastActiveSceneView != null ) pos = UnityEditor.SceneView.lastActiveSceneView.pivot; GameObject go = new GameObject(type + " Warp"); MegaFFDWarp warp = (MegaFFDWarp)go.AddComponent(classtype); warp.Init(); go.transform.position = pos; Selection.activeObject = go; } public override bool Inspector() { MegaFFDWarp mod = (MegaFFDWarp)target; #if !UNITY_5 && !UNITY_2017 EditorGUIUtility.LookLikeControls(); #endif mod.KnotSize = EditorGUILayout.FloatField("Knot Size", mod.KnotSize); mod.inVol = EditorGUILayout.Toggle("In Vol", mod.inVol); handles = EditorGUILayout.Toggle("Handles", handles); handleSize = EditorGUILayout.Slider("Size", handleSize, 0.0f, 1.0f); mirrorX = EditorGUILayout.Toggle("Mirror X", mirrorX); mirrorY = EditorGUILayout.Toggle("Mirror Y", mirrorY); mirrorZ = EditorGUILayout.Toggle("Mirror Z", mirrorZ); showpoints = EditorGUILayout.Foldout(showpoints, "Points"); if ( showpoints ) { int gs = mod.GridSize(); //int num = gs * gs * gs; for ( int x = 0; x < gs; x++ ) { for ( int y = 0; y < gs; y++ ) { for ( int z = 0; z < gs; z++ ) { int i = (x * gs * gs) + (y * gs) + z; mod.pt[i] = EditorGUILayout.Vector3Field("p[" + x + "," + y + "," + z + "]", mod.pt[i]); } } } } if ( mod.bsize.x != mod.Width || mod.bsize.y != mod.Height || mod.bsize.z != mod.Length ) { mod.Init(); } return false; } static public float handleSize = 0.5f; static public bool handles = true; static public bool mirrorX = false; static public bool mirrorY = false; static public bool mirrorZ = false; Vector3 CircleCap(int id, Vector3 pos, Quaternion rot, float size) { #if UNITY_5_6 || UNITY_2017 return Handles.FreeMoveHandle(pos, rot, size, Vector3.zero, Handles.CircleHandleCap); #else return Handles.FreeMoveHandle(pos, rot, size, Vector3.zero, Handles.CircleCap); #endif } public override void DrawSceneGUI() { MegaFFDWarp ffd = (MegaFFDWarp)target; bool snapshot = false; if ( ffd.DisplayGizmo ) { //MegaModifiers context = ffd.GetComponent<MegaModifiers>(); //if ( context && context.DrawGizmos ) { Vector3 size = ffd.lsize; Vector3 osize = ffd.lsize; osize.x = 1.0f / size.x; osize.y = 1.0f / size.y; osize.z = 1.0f / size.z; //Matrix4x4 tm1 = Matrix4x4.identity; //Quaternion rot = Quaternion.Euler(Vector3.zero); //ffd.gizmoRot); //tm1.SetTRS(-(ffd.gizmoPos + ffd.Offset), rot, ffd.gizmoScale); //Vector3.one); Matrix4x4 tm = Matrix4x4.identity; Handles.matrix = Matrix4x4.identity; //if ( context != null && context.sourceObj != null ) //tm = context.sourceObj.transform.localToWorldMatrix * tm1; //else tm = ffd.transform.localToWorldMatrix; // * tm1; DrawGizmos(ffd, tm); //Handles.matrix); Handles.color = Color.yellow; #if false int pc = ffd.GridSize(); pc = pc * pc * pc; for ( int i = 0; i < pc; i++ ) { Vector3 p = ffd.GetPoint(i); // + ffd.bcenter; //pm = Handles.PositionHandle(p, Quaternion.identity); pm = Handles.FreeMoveHandle(p, Quaternion.identity, ffd.KnotSize * 0.1f, Vector3.zero, Handles.CircleCap); pm -= ffd.bcenter; p = Vector3.Scale(pm, osize); p.x += 0.5f; p.y += 0.5f; p.z += 0.5f; ffd.pt[i] = p; } #endif int gs = ffd.GridSize(); //int i = 0; Vector3 ttp = Vector3.zero; for ( int z = 0; z < gs; z++ ) { for ( int y = 0; y < gs; y++ ) { for ( int x = 0; x < gs; x++ ) { int index = ffd.GridIndex(x, y, z); //Vector3 p = ffd.GetPoint(i); // + ffd.bcenter; Vector3 lp = ffd.GetPoint(index); Vector3 p = lp; //tm.MultiplyPoint(lp); //ffdi); // + ffd.bcenter; Vector3 tp = tm.MultiplyPoint(p); if ( handles ) { ttp = PositionHandle(tp, Quaternion.identity, handleSize, ffd.GizCol1.a); //ttp = Handles.PositionHandle(tp, Quaternion.identity); //pm = tm.inverse.MultiplyPoint(Handles.PositionHandle(tm.MultiplyPoint(p), Quaternion.identity)); //pm = PositionHandle(p, Quaternion.identity, handleSize, ffd.gizCol1.a); } else { //ttp = Handles.FreeMoveHandle(tp, Quaternion.identity, ffd.KnotSize * 0.1f, Vector3.zero, Handles.CircleCap); ttp = CircleCap(0, tp, Quaternion.identity, ffd.KnotSize * 0.1f); } if ( ttp != tp ) { if ( !snapshot ) { MegaUndo.SetSnapshotTarget(ffd, "FFD Lattice Move"); snapshot = true; } } pm = tm.inverse.MultiplyPoint(ttp); Vector3 delta = pm - p; //pm = lp + delta; //ffd.SetPoint(x, y, z, pm); pm -= ffd.bcenter; p = Vector3.Scale(pm, osize); p.x += 0.5f; p.y += 0.5f; p.z += 0.5f; ffd.pt[index] = p; if ( mirrorX ) { int y1 = y - (gs - 1); if ( y1 < 0 ) y1 = -y1; if ( y != y1 ) { Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x, y1, z)); // + ffd.bcenter; delta.y = -delta.y; p1 += delta; p1 -= ffd.bcenter; p = Vector3.Scale(p1, osize); p.x += 0.5f; p.y += 0.5f; p.z += 0.5f; ffd.pt[ffd.GridIndex(x, y1, z)] = p; } } if ( mirrorY ) { int z1 = z - (gs - 1); if ( z1 < 0 ) z1 = -z1; if ( z != z1 ) { Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x, y, z1)); // + ffd.bcenter; delta.z = -delta.z; p1 += delta; p1 -= ffd.bcenter; p = Vector3.Scale(p1, osize); p.x += 0.5f; p.y += 0.5f; p.z += 0.5f; ffd.pt[ffd.GridIndex(x, y, z1)] = p; } } if ( mirrorZ ) { int x1 = x - (gs - 1); if ( x1 < 0 ) x1 = -x1; if ( x != x1 ) { Vector3 p1 = ffd.GetPoint(ffd.GridIndex(x1, y, z)); // + ffd.bcenter; delta.x = -delta.x; p1 += delta; p1 -= ffd.bcenter; p = Vector3.Scale(p1, osize); p.x += 0.5f; p.y += 0.5f; p.z += 0.5f; ffd.pt[ffd.GridIndex(x1, y, z)] = p; } } } } } Handles.matrix = Matrix4x4.identity; if ( GUI.changed && snapshot ) { MegaUndo.CreateSnapshot(); MegaUndo.RegisterSnapshot(); EditorUtility.SetDirty(ffd); } MegaUndo.ClearSnapshotTarget(); } } } #if UNITY_5_6 || UNITY_2017 public static Vector3 PositionHandle(Vector3 position, Quaternion rotation, float size, float alpha) { float handlesize = HandleUtility.GetHandleSize(position) * size; Color color = Handles.color; Color col = Color.red; col.a = alpha; Handles.color = col; //Color.red; //Handles..xAxisColor; //position = Handles.Slider(position, rotation * Vector3.right, handlesize, new Handles.DrawCapFunction(Handles.ArrowHandleCap), 0.0f); //SnapSettings.move.x); position = Handles.Slider(position, rotation * Vector3.right, handlesize, Handles.ArrowHandleCap, 0.0f); // new Handles.DrawCapFunction(Handles.ArrowHandleCap), 0.0f); //SnapSettings.move.x); col = Color.green; col.a = alpha; Handles.color = col; //Color.green; //Handles.yAxisColor; position = Handles.Slider(position, rotation * Vector3.up, handlesize, Handles.ArrowHandleCap, 0.0f); //SnapSettings.move.y); col = Color.blue; col.a = alpha; Handles.color = col; //Color.blue; //Handles.zAxisColor; position = Handles.Slider(position, rotation * Vector3.forward, handlesize, Handles.ArrowHandleCap, 0.0f); //SnapSettings.move.z); col = Color.yellow; col.a = alpha; Handles.color = col; //Color.yellow; //Handles.centerColor; position = Handles.FreeMoveHandle(position, rotation, handlesize * 0.15f, Vector3.zero, Handles.RectangleHandleCap); Handles.color = color; return position; } #else public static Vector3 PositionHandle(Vector3 position, Quaternion rotation, float size, float alpha) { float handlesize = HandleUtility.GetHandleSize(position) * size; Color color = Handles.color; Color col = Color.red; col.a = alpha; Handles.color = col; //Color.red; //Handles..xAxisColor; position = Handles.Slider(position, rotation * Vector3.right, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.x); col = Color.green; col.a = alpha; Handles.color = col; //Color.green; //Handles.yAxisColor; position = Handles.Slider(position, rotation * Vector3.up, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.y); col = Color.blue; col.a = alpha; Handles.color = col; //Color.blue; //Handles.zAxisColor; position = Handles.Slider(position, rotation * Vector3.forward, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.z); col = Color.yellow; col.a = alpha; Handles.color = col; //Color.yellow; //Handles.centerColor; position = Handles.FreeMoveHandle(position, rotation, handlesize * 0.15f, Vector3.zero, new Handles.DrawCapFunction(Handles.RectangleCap)); Handles.color = color; return position; } #endif #if false public static Vector3 PositionHandle(Vector3 position, Quaternion rotation, float size, float alpha) { float handlesize = handleSize; //HandleUtility.GetHandleSize(position) * size; Color color = Handles.color; Color col = Color.red; col.a = alpha; Handles.color = col; //Color.red; //Handles..xAxisColor; position = Handles.Slider(position, rotation * Vector3.right, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.x); col = Color.green; col.a = alpha; Handles.color = col; //Color.green; //Handles.yAxisColor; position = Handles.Slider(position, rotation * Vector3.up, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.y); col = Color.blue; col.a = alpha; Handles.color = col; //Color.blue; //Handles.zAxisColor; position = Handles.Slider(position, rotation * Vector3.forward, handlesize, new Handles.DrawCapFunction(Handles.ArrowCap), 0.0f); //SnapSettings.move.z); col = Color.yellow; col.a = alpha; Handles.color = col; //Color.yellow; //Handles.centerColor; position = Handles.FreeMoveHandle(position, rotation, handlesize * 0.15f, Vector3.zero, new Handles.DrawCapFunction(Handles.RectangleCap)); Handles.color = color; return position; } #endif Vector3[] pp3 = new Vector3[3]; #if false public void DrawGizmos(MegaFFD ffd, Matrix4x4 tm) { Handles.color = ffd.gizCol1; //Color.red; int pc = ffd.GridSize(); for ( int i = 0; i < pc; i++ ) { for ( int j = 0; j < pc; j++ ) { for ( int k = 0; k < pc; k++ ) { //pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k)); // + ffd.bcenter); pp3[0] = ffd.GetPoint(i, j, k); // + ffd.bcenter); if ( i < pc - 1 ) { //pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k)); // + ffd.bcenter); pp3[1] = ffd.GetPoint(i + 1, j, k); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( j < pc - 1 ) { //pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k)); // + ffd.bcenter); pp3[1] = ffd.GetPoint(i, j + 1, k); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( k < pc - 1 ) { //pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1)); // + ffd.bcenter); pp3[1] = ffd.GetPoint(i, j, k + 1); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } } } } } #else public void DrawGizmos(MegaFFDWarp ffd, Matrix4x4 tm) { Handles.color = Color.yellow; //ffd.gizCol1; //Color.red; int pc = ffd.GridSize(); for ( int i = 0; i < pc; i++ ) { for ( int j = 0; j < pc; j++ ) { for ( int k = 0; k < pc; k++ ) { pp3[0] = tm.MultiplyPoint(ffd.GetPoint(i, j, k)); // + ffd.bcenter); //pp3[0] = ffd.GetPoint(i, j, k); // + ffd.bcenter); if ( i < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i + 1, j, k)); // + ffd.bcenter); //pp3[1] = ffd.GetPoint(i + 1, j, k); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( j < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j + 1, k)); // + ffd.bcenter); //pp3[1] = ffd.GetPoint(i, j + 1, k); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } if ( k < pc - 1 ) { pp3[1] = tm.MultiplyPoint(ffd.GetPoint(i, j, k + 1)); // + ffd.bcenter); //pp3[1] = ffd.GetPoint(i, j, k + 1); // + ffd.bcenter); Handles.DrawLine(pp3[0], pp3[1]); } } } } } #endif }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Security.Cryptography; public class PsdLayerExtractor { #region Child Classes public class Layer { public bool canLoadLayer = true; public PsdParser.PSDLayer psdLayer; public List<Layer> children = new List<Layer>(); public bool isContainer { get { return this.psdLayer.groupStarted; } } public bool isTextLayer { get { return this.psdLayer.isTextLayer; } } public bool isImageLayer { get { return this.psdLayer.isImageLayer; } } public string name { get { return this.psdLayer.name; } } public string text { get; internal set; } public Layer() { } public Layer(PsdParser.PSDLayer psdLayer) { this.psdLayer = psdLayer; if (this.psdLayer.isTextLayer) this.text = this.psdLayer.text.Replace('\r', '\n'); } public void LoadData(BinaryReader br, int bpp) { var channelCount = this.psdLayer.channels.Length; for (var k=0; k<channelCount; ++k) { var channel = this.psdLayer.channels[k]; if (this.canLoadLayer && this.psdLayer.isImageLayer) channel.loadData(br, bpp); } } }; public class ImageFilePath { public string filePath; public string imageMd5; public ImageFilePath() { } public ImageFilePath(string info) { var arr = info.Split('='); this.filePath = arr[0]; if (arr.Length > 1) this.imageMd5 = arr[1]; } public ImageFilePath(string filePath, string imageMd5) { this.filePath = filePath; this.imageMd5 = imageMd5; } public override string ToString() { return this.filePath + "=" + this.imageMd5; } }; #endregion #region Properties private bool foldout; private System.Timers.Timer watchingTimer; private FileSystemWatcher watcher; private System.Action<PsdLayerExtractor> whenPsdFileChanged; public Object PsdFileAsset { get; private set; } public string PsdFilePath { get { return AssetDatabase.GetAssetPath(this.PsdFileAsset); } } public string PsdFileName { get { return this.Psd.fileName; } } public GameObject RootGameObject { get; private set; } public Layer Root { get; private set; } public bool IsAddFont { get; set; } public bool IsLinked { get{ return this.RootGameObject != null && this.RootGameObject.transform.parent != null; } } public bool IsChanged { get{ return this.PsdMd5 != this.CalcMd5(); } } public PsdParser.PSD Psd { get; private set; } public string PsdMd5 { get; private set; } public List<ImageFilePath> ImageFilePathes { get; private set; } public List<ImageFilePath> LastImageFilePathes { get; private set; } public override string ToString() { var imageFilePaths = ""; if (this.LastImageFilePathes != null && this.LastImageFilePathes.Count > 0) { foreach (var imageFilePath in this.LastImageFilePathes) { if (!string.IsNullOrEmpty(imageFilePaths)) imageFilePaths += ","; imageFilePaths += imageFilePath.ToString(); } } if (string.IsNullOrEmpty(imageFilePaths)) return this.PsdFilePath + ":" + this.PsdMd5 + ":" + (this.IsAddFont ? 1 : 0); else return this.PsdFilePath + ":" + this.PsdMd5 + ":" + (this.IsAddFont ? 1 : 0) + ":" + imageFilePaths; } #endregion public PsdLayerExtractor(GameObject uiRoot, Object psdFileAsset, string info, System.Action<PsdLayerExtractor> whenPsdFileChanged) { /*! about info array * * 0: path of psd file * 1: md5 of psd file * 2: add font boolean * 3: image file infos */ // load psd header var arr = info.Split(':'); var filePath = arr[0]; if (psdFileAsset != null) this.PsdFileAsset = psdFileAsset; else this.PsdFileAsset = AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D)); this.Psd = new PsdParser.PSD(); this.Psd.loadHeader(filePath); // get md5 if (arr.Length > 1) { this.PsdMd5 = arr[1]; var nowMd5 = this.CalcMd5(); if (this.PsdMd5 != nowMd5) { if (whenPsdFileChanged != null) whenPsdFileChanged(this); this.PsdMd5 = nowMd5; } } else this.PsdMd5 = this.CalcMd5(); // check font option if (arr.Length > 2) this.IsAddFont = arr[2] == "1"; else this.IsAddFont = true; // image files if (arr.Length > 3) { this.LastImageFilePathes = new List<ImageFilePath>(); var pathAndMd5s = arr[3].Split(','); foreach (var pathAndMd5 in pathAndMd5s) this.LastImageFilePathes.Add(new ImageFilePath(pathAndMd5)); } // set UIRoot object if (uiRoot != null) this.RootGameObject = GBlue.Util.FindGameObjectRecursively(uiRoot, this.PsdFileName); // load layers this.Root = new Layer(); { var psdLayers = this.Psd.layerInfo.layers; this.LoadPsdLayers(this.Root, psdLayers, psdLayers.Length-1); } this.Root.children.Reverse(); // monitor psd file this.whenPsdFileChanged = whenPsdFileChanged; this.BeginMonitoring(); } private void BeginMonitoring() { //**monodevelop problem in Unity3D 3.5?? // Mono.Debugger.Soft.ObjectCollectedException: The requested operation cannot be completed because the object has been garbage collected. if (this.watchingTimer != null){ this.watchingTimer.Stop(); } if (this.watcher != null){ this.watcher.EnableRaisingEvents = false; this.watcher.Dispose(); } var psdFilePath = this.PsdFilePath; this.watchingTimer = new System.Timers.Timer(1); this.watcher = new FileSystemWatcher(); this.watcher.Path = Path.GetDirectoryName(psdFilePath); this.watcher.Filter = Path.GetFileName(psdFilePath); this.watcher.NotifyFilter = NotifyFilters.LastWrite; this.watcher.EnableRaisingEvents = true; this.watcher.Changed += new FileSystemEventHandler(delegate(object s, FileSystemEventArgs e){ this.watcher.EnableRaisingEvents = false; if (PsdLayerToNGUI.verbose) Debug.Log(psdFilePath + " file changed"); if (this.whenPsdFileChanged != null) this.whenPsdFileChanged(this); this.watchingTimer.Elapsed += delegate { this.watcher.EnableRaisingEvents = true; this.watchingTimer.Stop(); }; this.watchingTimer.Start(); }); } public GameObject Link() { this.RootGameObject = new GameObject(this.Psd.fileName); return this.RootGameObject; } private string CalcMd5Imple(Stream s) { using (var md5 = new MD5CryptoServiceProvider()) { var bytes = md5.ComputeHash(s); var result = new StringBuilder(bytes.Length * 2); for (var i=0; i<bytes.Length; ++i) result.Append(bytes[i].ToString("x2")); return result.ToString(); } } public string CalcMd5() { using (var stream = File.OpenRead(this.PsdFilePath)) { return CalcMd5Imple(stream); } } public void Reload() { this.Psd = new PsdParser.PSD(); this.Psd.loadHeader(this.PsdFilePath); this.PsdMd5 = this.CalcMd5(); this.Root = new Layer(); { var psdLayers = this.Psd.layerInfo.layers; this.LoadPsdLayers(this.Root, psdLayers, psdLayers.Length-1); } this.Root.children.Reverse(); } public void Update(GameObject uiRoot) { if (this.Psd.filePath != this.PsdFilePath){ this.Psd.filePath = this.PsdFilePath; this.BeginMonitoring(); } if (this.RootGameObject == null && uiRoot != null) this.RootGameObject = GBlue.Util.FindGameObjectRecursively(uiRoot, this.PsdFileName); } private int LoadPsdLayers(Layer parent, PsdParser.PSDLayer[] psdLayers, int i) { while (i >= 0) { var psdLayer = psdLayers[i--]; if (psdLayer.groupStarted) { var newParent = new Layer(psdLayer); parent.children.Add(newParent); i = this.LoadPsdLayers(newParent, psdLayers, i); if (psdLayer.name.Contains("@ignore")) parent.children.Remove(newParent); } else if (psdLayer.groupEnded) { parent.children.Reverse(); break; } else if (!psdLayer.drop && !psdLayer.name.Contains("@ignore")) { parent.children.Add(new Layer(psdLayer)); } } return i; } private Texture MakeSlicedSprites(ref byte[] data, Layer layer, PsdLayerRect area) { var channelCount = layer.psdLayer.channels.Length; var pitch = layer.psdLayer.pitch; var w = layer.psdLayer.area.width; var h = layer.psdLayer.area.height; var x1 = area.left; var y1 = area.top; var x2 = area.right; var y2 = area.bottom; var aaa = 0; var rc1 = new Rect(0, 0, x1 + aaa, y1 + aaa); var rc2 = new Rect(w - x2, 0, x2, y1 + aaa); var rc3 = new Rect(0, h - y2, x1 + aaa, y2); var rc4 = new Rect(w - x2, h - y2, x2, y2); var ww = (int)(rc1.width + rc2.width); var hh = (int)(rc1.height + rc3.height); var format = channelCount == 3 ? TextureFormat.RGB24 : TextureFormat.ARGB32; var tex = new Texture2D(ww, hh, format, false); var opacity = (byte)Mathf.RoundToInt(layer.psdLayer.opacity * 255f); var colors = new Color32[ww * hh]; var k = 0; for (var y=h-1; y>=0; --y) { var yy = h-1-y; var xx = 0; for (var x=0; x<pitch; x+=channelCount) { var n = x + y * pitch; var c = new Color32(1,1,1,1); if (channelCount == 3) { c.b = data[n++]; c.g = data[n++]; c.r = data[n++]; c.a = opacity; } else { c.b = data[n++]; c.g = data[n++]; c.r = data[n++]; c.a = (byte)Mathf.RoundToInt(data[n++]/255f * opacity); } var pt = new Vector2(xx++, yy); if (rc1.Contains(pt) || rc2.Contains(pt) || rc3.Contains(pt) || rc4.Contains(pt)) colors[k++] = c; } } tex.filterMode = FilterMode.Point; tex.SetPixels32(colors); tex.Apply(); data = tex.EncodeToPNG(); return tex; } private Texture MakeTexture(ref byte[] data, Layer layer) { var channelCount = layer.psdLayer.channels.Length; var pitch = layer.psdLayer.pitch; var w = layer.psdLayer.area.width; var h = layer.psdLayer.area.height; var format = channelCount == 3 ? TextureFormat.RGB24 : TextureFormat.ARGB32; var tex = new Texture2D(w, h, format, false); var colors = new Color32[data.Length / channelCount]; var k = 0; for (var y=h-1; y>=0; --y) { for (var x=0; x<pitch; x+=channelCount) { var n = x + y * pitch; var c = new Color32(1,1,1,1); if (channelCount == 4) { c.b = data[n++]; c.g = data[n++]; c.r = data[n++]; c.a = (byte)Mathf.RoundToInt(data[n++]/255f * layer.psdLayer.opacity * 255f); } else { c.b = data[n++]; c.g = data[n++]; c.r = data[n++]; c.a = (byte)Mathf.RoundToInt(layer.psdLayer.opacity * 255f); } colors[k++] = c; } } tex.filterMode = FilterMode.Point; tex.SetPixels32(colors); tex.Apply(); data = tex.EncodeToPNG(); return tex; } public bool HasUnacceptibleChar(string str) { return str.IndexOfAny(new char[]{'\\', '/', ':', '*', '?', '"', '<', '>', '|'}) >= 0; } private void SaveLayersToPNGs_imple(string prePath, List<Layer> layers) { var psdFileStream = new FileStream(this.PsdFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); foreach (var layer in layers) { if (!layer.canLoadLayer) continue; if (layer.isContainer) { this.SaveLayersToPNGs_imple(prePath + "/" + layer.name, layer.children); continue; } var pa = new PsdLayerCommandParser.ControlParser(prePath, layer); if (pa.type == PsdLayerCommandParser.ControlType.Script || pa.type == PsdLayerCommandParser.ControlType.Label || pa.type == PsdLayerCommandParser.ControlType.LabelButton) continue; var fileName = pa.fullName; if (this.HasUnacceptibleChar(fileName)) { Debug.LogError(fileName + " Contains wrong character '\\ / : * ? \" < > |' not allowed"); continue; } var filePath = prePath + "/" + fileName + ".png"; ImageFilePath newImageFilePath = null; { try { psdFileStream.Position = 0; var br = new BinaryReader(psdFileStream); { layer.LoadData(br, this.Psd.headerInfo.bpp); newImageFilePath = new ImageFilePath(filePath, "pass"); } } catch (System.Exception e) { Debug.LogError(e.Message); } } this.ImageFilePathes.Add(newImageFilePath); //**md5: too slow // ImageFilePath lastImageFilePath = null; // ImageFilePath newImageFilePath = null; // { // try // { // if (this.LastImageFilePathes != null && this.LastImageFilePathes.Count > 0) // { // lastImageFilePath = this.LastImageFilePathes.Find(t=>t.filePath == filePath); // } // // psdFileStream.Position = 0; // var br = new BinaryReader(psdFileStream); // { // layer.LoadData(br, this.Psd.headerInfo.bpp); // var imageMd5 = this.CalcMd5Imple(br.BaseStream); // var imageMd5 = "pass"; // newImageFilePath = new ImageFilePath(filePath, imageMd5); // } // } // catch (System.Exception e) // { // Debug.LogError(e.Message); // } // } // this.ImageFilePathes.Add(newImageFilePath); // // if (lastImageFilePath != null) // { // if (lastImageFilePath.imageMd5 == newImageFilePath.imageMd5 && File.Exists(filePath)) // continue; // lastImageFilePath.imageMd5 = newImageFilePath.imageMd5; // } // else // this.LastImageFilePathes.Add(newImageFilePath); if (PsdLayerToNGUI.verbose) Debug.Log("Saving '" + newImageFilePath.filePath + "'"); var data = layer.psdLayer.mergeChannels(); if (data == null) continue; Texture tex = null; if (pa.sliceArea != null) { tex = MakeSlicedSprites(ref data, layer, pa.sliceArea); } else { tex = MakeTexture(ref data, layer); } if (tex != null) { if (!System.IO.Directory.Exists(prePath)) System.IO.Directory.CreateDirectory(prePath); System.IO.File.WriteAllBytes(filePath, data); AssetDatabase.ImportAsset(filePath, ImportAssetOptions.Default); Texture2D.DestroyImmediate(tex); } } } public void SaveLayersToPNGs() { var psdFilePath = this.PsdFilePath; var prePath = psdFilePath.Substring(0, psdFilePath.Length - 4) + "_layers"; if (PsdLayerToNGUI.verbose) Debug.Log("Saving layers from '" + psdFilePath + "'"); this.ImageFilePathes = new List<ImageFilePath>(); if (this.LastImageFilePathes == null) this.LastImageFilePathes = new List<ImageFilePath>(); this.SaveLayersToPNGs_imple(prePath, this.Root.children); } private void OnGUI_selection(bool canLoadLayer, List<Layer> layers) { foreach (var layer in layers) { if (layer.isContainer) this.OnGUI_selection(canLoadLayer, layer.children); else layer.canLoadLayer = canLoadLayer; } } private void OnGUI_toggle(string groupName, List<Layer> layers) { foreach (var layer in layers) { if (layer.isContainer) this.OnGUI_toggle(layer.name, layer.children); else { GUILayout.BeginHorizontal(); var preName = groupName + (!string.IsNullOrEmpty(groupName) ? "/" : ""); layer.canLoadLayer = GUILayout.Toggle(layer.canLoadLayer, "", GUILayout.Width(15)); GUILayout.Label(preName + layer.name); GUILayout.EndHorizontal(); } } } public void OnGUI(bool isAddFontToggleVisible, System.Action whenRemove) { EditorGUILayout.BeginHorizontal(); // remove EditorGUILayout.LabelField("", GUILayout.Width(5)); if (GUILayout.Button("Remove", GUILayout.MaxWidth(55))){ if (whenRemove != null) whenRemove(); } // font adding if (isAddFontToggleVisible) { this.IsAddFont = GUILayout.Toggle(this.IsAddFont, "Add Font", GUILayout.Width(70)); } // instance GUILayout.BeginHorizontal(); { this.RootGameObject = EditorGUILayout.ObjectField( "", this.RootGameObject, typeof(GameObject), true, GUILayout.MaxWidth(150)) as GameObject; } EditorGUILayout.BeginVertical(); this.foldout = EditorGUILayout.Foldout(this.foldout, this.PsdFileName); if (this.foldout) { // blank EditorGUILayout.LabelField(""); // selection EditorGUILayout.BeginHorizontal(); { if (GUILayout.Button("Select All", GUILayout.MaxWidth(100))) { this.OnGUI_selection(true, this.Root.children); } if (GUILayout.Button("Select None", GUILayout.MaxWidth(100))) { this.OnGUI_selection(false, this.Root.children); } } EditorGUILayout.EndHorizontal(); // layers this.OnGUI_toggle("", this.Root.children); } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } };
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.3 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // The author gratefully acknowleges the support of David Turner, // Robert Wilhelm, and Werner Lemberg - the authors of the FreeType // libray - in producing this work. See http://www.freetype.org for details. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Adaptation for 32-bit screen coordinates has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- using MatterHackers.Agg.VertexSource; namespace MatterHackers.Agg { //===========================================================layer_order_e public enum layer_order_e { layer_unsorted, //------layer_unsorted layer_direct, //------layer_direct layer_inverse //------layer_inverse }; //==================================================rasterizer_compound_aa //template<class Clip=rasterizer_sl_clip_int> sealed public class rasterizer_compound_aa : IRasterizer { private rasterizer_cells_aa m_Rasterizer; private VectorClipper m_VectorClipper; private agg_basics.filling_rule_e m_filling_rule; private layer_order_e m_layer_order; private VectorPOD<style_info> m_styles; // Active Styles private VectorPOD<int> m_ast; // Active Style Table (unique values) private VectorPOD<byte> m_asm; // Active Style Mask private VectorPOD<cell_aa> m_cells; private VectorPOD<byte> m_cover_buf; private VectorPOD<int> m_master_alpha; private int m_min_style; private int m_max_style; private int m_start_x; private int m_start_y; private int m_scan_y; private int m_sl_start; private int m_sl_len; private struct style_info { internal int start_cell; internal int num_cells; internal int last_x; }; private const int aa_shift = 8; private const int aa_scale = 1 << aa_shift; private const int aa_mask = aa_scale - 1; private const int aa_scale2 = aa_scale * 2; private const int aa_mask2 = aa_scale2 - 1; private const int poly_subpixel_shift = (int)agg_basics.poly_subpixel_scale_e.poly_subpixel_shift; public rasterizer_compound_aa() { m_Rasterizer = new rasterizer_cells_aa(); m_VectorClipper = new VectorClipper(); m_filling_rule = agg_basics.filling_rule_e.fill_non_zero; m_layer_order = layer_order_e.layer_direct; m_styles = new VectorPOD<style_info>(); // Active Styles m_ast = new VectorPOD<int>(); // Active Style Table (unique values) m_asm = new VectorPOD<byte>(); // Active Style Mask m_cells = new VectorPOD<cell_aa>(); m_cover_buf = new VectorPOD<byte>(); m_master_alpha = new VectorPOD<int>(); m_min_style = (0x7FFFFFFF); m_max_style = (-0x7FFFFFFF); m_start_x = (0); m_start_y = (0); m_scan_y = (0x7FFFFFFF); m_sl_start = (0); m_sl_len = (0); } public void gamma(IGammaFunction gamma_function) { throw new System.NotImplementedException(); } public void reset() { m_Rasterizer.reset(); m_min_style = 0x7FFFFFFF; m_max_style = -0x7FFFFFFF; m_scan_y = 0x7FFFFFFF; m_sl_start = 0; m_sl_len = 0; } private void filling_rule(agg_basics.filling_rule_e filling_rule) { m_filling_rule = filling_rule; } private void layer_order(layer_order_e order) { m_layer_order = order; } private void clip_box(double x1, double y1, double x2, double y2) { reset(); m_VectorClipper.clip_box(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1), m_VectorClipper.upscale(x2), m_VectorClipper.upscale(y2)); } private void reset_clipping() { reset(); m_VectorClipper.reset_clipping(); } public void styles(int left, int right) { cell_aa cell = new cell_aa(); cell.initial(); cell.left = (int)left; cell.right = (int)right; m_Rasterizer.style(cell); if (left >= 0 && left < m_min_style) m_min_style = left; if (left >= 0 && left > m_max_style) m_max_style = left; if (right >= 0 && right < m_min_style) m_min_style = right; if (right >= 0 && right > m_max_style) m_max_style = right; } public void move_to(int x, int y) { if (m_Rasterizer.sorted()) reset(); m_VectorClipper.move_to(m_start_x = m_VectorClipper.downscale(x), m_start_y = m_VectorClipper.downscale(y)); } public void line_to(int x, int y) { m_VectorClipper.line_to(m_Rasterizer, m_VectorClipper.downscale(x), m_VectorClipper.downscale(y)); } public void move_to_d(double x, double y) { if (m_Rasterizer.sorted()) reset(); m_VectorClipper.move_to(m_start_x = m_VectorClipper.upscale(x), m_start_y = m_VectorClipper.upscale(y)); } public void line_to_d(double x, double y) { m_VectorClipper.line_to(m_Rasterizer, m_VectorClipper.upscale(x), m_VectorClipper.upscale(y)); } private void add_vertex(double x, double y, ShapePath.FlagsAndCommand cmd) { if (ShapePath.is_move_to(cmd)) { move_to_d(x, y); } else if (ShapePath.is_vertex(cmd)) { line_to_d(x, y); } else if (ShapePath.is_close(cmd)) { m_VectorClipper.line_to(m_Rasterizer, m_start_x, m_start_y); } } private void edge(int x1, int y1, int x2, int y2) { if (m_Rasterizer.sorted()) reset(); m_VectorClipper.move_to(m_VectorClipper.downscale(x1), m_VectorClipper.downscale(y1)); m_VectorClipper.line_to(m_Rasterizer, m_VectorClipper.downscale(x2), m_VectorClipper.downscale(y2)); } private void edge_d(double x1, double y1, double x2, double y2) { if (m_Rasterizer.sorted()) reset(); m_VectorClipper.move_to(m_VectorClipper.upscale(x1), m_VectorClipper.upscale(y1)); m_VectorClipper.line_to(m_Rasterizer, m_VectorClipper.upscale(x2), m_VectorClipper.upscale(y2)); } private void sort() { m_Rasterizer.sort_cells(); } public bool rewind_scanlines() { m_Rasterizer.sort_cells(); if (m_Rasterizer.total_cells() == 0) { return false; } if (m_max_style < m_min_style) { return false; } m_scan_y = m_Rasterizer.min_y(); m_styles.Allocate((int)(m_max_style - m_min_style + 2), 128); allocate_master_alpha(); return true; } // Returns the number of styles public int sweep_styles() { for (; ; ) { if (m_scan_y > m_Rasterizer.max_y()) return 0; int num_cells = (int)m_Rasterizer.scanline_num_cells(m_scan_y); cell_aa[] cells; int cellOffset = 0; int curCellOffset; m_Rasterizer.scanline_cells(m_scan_y, out cells, out cellOffset); int num_styles = (int)(m_max_style - m_min_style + 2); int style_id; int styleOffset = 0; m_cells.Allocate((int)num_cells * 2, 256); // Each cell can have two styles m_ast.Capacity(num_styles, 64); m_asm.Allocate((num_styles + 7) >> 3, 8); m_asm.zero(); if (num_cells > 0) { // Pre-add zero (for no-fill style, that is, -1). // We need that to ensure that the "-1 style" would go first. m_asm.Array[0] |= 1; m_ast.add(0); m_styles.Array[styleOffset].start_cell = 0; m_styles.Array[styleOffset].num_cells = 0; m_styles.Array[styleOffset].last_x = -0x7FFFFFFF; m_sl_start = cells[0].x; m_sl_len = (int)(cells[num_cells - 1].x - m_sl_start + 1); while (num_cells-- != 0) { curCellOffset = (int)cellOffset++; add_style(cells[curCellOffset].left); add_style(cells[curCellOffset].right); } // Convert the Y-histogram into the array of starting indexes int i; int start_cell = 0; style_info[] stylesArray = m_styles.Array; for (i = 0; i < m_ast.size(); i++) { int IndexToModify = (int)m_ast[i]; int v = stylesArray[IndexToModify].start_cell; stylesArray[IndexToModify].start_cell = start_cell; start_cell += v; } num_cells = (int)m_Rasterizer.scanline_num_cells(m_scan_y); m_Rasterizer.scanline_cells(m_scan_y, out cells, out cellOffset); while (num_cells-- > 0) { curCellOffset = (int)cellOffset++; style_id = (int)((cells[curCellOffset].left < 0) ? 0 : cells[curCellOffset].left - m_min_style + 1); styleOffset = (int)style_id; if (cells[curCellOffset].x == stylesArray[styleOffset].last_x) { cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells - 1; unchecked { cells[cellOffset].area += cells[curCellOffset].area; cells[cellOffset].cover += cells[curCellOffset].cover; } } else { cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells; cells[cellOffset].x = cells[curCellOffset].x; cells[cellOffset].area = cells[curCellOffset].area; cells[cellOffset].cover = cells[curCellOffset].cover; stylesArray[styleOffset].last_x = cells[curCellOffset].x; stylesArray[styleOffset].num_cells++; } style_id = (int)((cells[curCellOffset].right < 0) ? 0 : cells[curCellOffset].right - m_min_style + 1); styleOffset = (int)style_id; if (cells[curCellOffset].x == stylesArray[styleOffset].last_x) { cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells - 1; unchecked { cells[cellOffset].area -= cells[curCellOffset].area; cells[cellOffset].cover -= cells[curCellOffset].cover; } } else { cellOffset = stylesArray[styleOffset].start_cell + stylesArray[styleOffset].num_cells; cells[cellOffset].x = cells[curCellOffset].x; cells[cellOffset].area = -cells[curCellOffset].area; cells[cellOffset].cover = -cells[curCellOffset].cover; stylesArray[styleOffset].last_x = cells[curCellOffset].x; stylesArray[styleOffset].num_cells++; } } } if (m_ast.size() > 1) break; ++m_scan_y; } ++m_scan_y; if (m_layer_order != layer_order_e.layer_unsorted) { VectorPOD_RangeAdaptor ra = new VectorPOD_RangeAdaptor(m_ast, 1, m_ast.size() - 1); if (m_layer_order == layer_order_e.layer_direct) { QuickSort_range_adaptor_uint m_QSorter = new QuickSort_range_adaptor_uint(); m_QSorter.Sort(ra); //quick_sort(ra, uint_greater); } else { throw new System.NotImplementedException(); //QuickSort_range_adaptor_uint m_QSorter = new QuickSort_range_adaptor_uint(); //m_QSorter.Sort(ra); //quick_sort(ra, uint_less); } } return m_ast.size() - 1; } // Returns style ID depending of the existing style index public int style(int style_idx) { return m_ast[style_idx + 1] + (int)m_min_style - 1; } private bool navigate_scanline(int y) { m_Rasterizer.sort_cells(); if (m_Rasterizer.total_cells() == 0) { return false; } if (m_max_style < m_min_style) { return false; } if (y < m_Rasterizer.min_y() || y > m_Rasterizer.max_y()) { return false; } m_scan_y = y; m_styles.Allocate((int)(m_max_style - m_min_style + 2), 128); allocate_master_alpha(); return true; } private bool hit_test(int tx, int ty) { if (!navigate_scanline(ty)) { return false; } int num_styles = sweep_styles(); if (num_styles <= 0) { return false; } scanline_hit_test sl = new scanline_hit_test(tx); sweep_scanline(sl, -1); return sl.hit(); } private byte[] allocate_cover_buffer(int len) { m_cover_buf.Allocate(len, 256); return m_cover_buf.Array; } private void master_alpha(int style, double alpha) { if (style >= 0) { while ((int)m_master_alpha.size() <= style) { m_master_alpha.add(aa_mask); } m_master_alpha.Array[style] = agg_basics.uround(alpha * aa_mask); } } public void add_path(IVertexSource vs) { add_path(vs, 0); } public void add_path(IVertexSource vs, int path_id) { double x; double y; ShapePath.FlagsAndCommand cmd; vs.rewind(path_id); if (m_Rasterizer.sorted()) reset(); while (!ShapePath.is_stop(cmd = vs.vertex(out x, out y))) { add_vertex(x, y, cmd); } } public int min_x() { return m_Rasterizer.min_x(); } public int min_y() { return m_Rasterizer.min_y(); } public int max_x() { return m_Rasterizer.max_x(); } public int max_y() { return m_Rasterizer.max_y(); } public int min_style() { return m_min_style; } public int max_style() { return m_max_style; } public int scanline_start() { return m_sl_start; } public int scanline_length() { return m_sl_len; } public int calculate_alpha(int area, int master_alpha) { int cover = area >> (poly_subpixel_shift * 2 + 1 - aa_shift); if (cover < 0) cover = -cover; if (m_filling_rule == agg_basics.filling_rule_e.fill_even_odd) { cover &= aa_mask2; if (cover > aa_scale) { cover = aa_scale2 - cover; } } if (cover > aa_mask) cover = aa_mask; return (int)((cover * master_alpha + aa_mask) >> aa_shift); } public bool sweep_scanline(IScanlineCache sl) { throw new System.NotImplementedException(); } // Sweeps one scanline with one style index. The style ID can be // determined by calling style(). //template<class Scanline> public bool sweep_scanline(IScanlineCache sl, int style_idx) { int scan_y = m_scan_y - 1; if (scan_y > m_Rasterizer.max_y()) return false; sl.ResetSpans(); int master_alpha = aa_mask; if (style_idx < 0) { style_idx = 0; } else { style_idx++; master_alpha = m_master_alpha[(int)(m_ast[(int)style_idx] + m_min_style - 1)]; } style_info st = m_styles[m_ast[style_idx]]; int num_cells = (int)st.num_cells; int CellOffset = st.start_cell; cell_aa cell = m_cells[CellOffset]; int cover = 0; while (num_cells-- != 0) { int alpha; int x = cell.x; int area = cell.area; cover += cell.cover; cell = m_cells[++CellOffset]; if (area != 0) { alpha = calculate_alpha((cover << (poly_subpixel_shift + 1)) - area, master_alpha); sl.add_cell(x, alpha); x++; } if (num_cells != 0 && cell.x > x) { alpha = calculate_alpha(cover << (poly_subpixel_shift + 1), master_alpha); if (alpha != 0) { sl.add_span(x, cell.x - x, alpha); } } } if (sl.num_spans() == 0) return false; sl.finalize(scan_y); return true; } private void add_style(int style_id) { if (style_id < 0) style_id = 0; else style_id -= m_min_style - 1; int nbyte = (int)((int)style_id >> 3); int mask = (int)(1 << (style_id & 7)); style_info[] stylesArray = m_styles.Array; if ((m_asm[nbyte] & mask) == 0) { m_ast.add((int)style_id); m_asm.Array[nbyte] |= (byte)mask; stylesArray[style_id].start_cell = 0; stylesArray[style_id].num_cells = 0; stylesArray[style_id].last_x = -0x7FFFFFFF; } ++stylesArray[style_id].start_cell; } private void allocate_master_alpha() { while ((int)m_master_alpha.size() <= m_max_style) { m_master_alpha.add(aa_mask); } } }; }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maxium precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; // can we get rid of this (?just have a mapping?) this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: Debug.Assert(false, "UDT is not supported"); return mt; default: return mt; } } // // map COM+ Type to MetaType class // static internal MetaType GetMetaTypeFromType(Type dataType, bool streamAllowed = true) { if (dataType == typeof(System.Byte[])) return MetaVarBinary; else if (dataType == typeof(System.Guid)) return s_metaUniqueId; else if (dataType == typeof(System.Object)) return s_metaVariant; else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) return MetaNVarChar; else if (dataType == typeof(IEnumerable<DbDataRecord>)) return s_metaTable; else if (dataType == typeof(TimeSpan)) return MetaTime; else if (dataType == typeof(DateTimeOffset)) return MetaDateTimeOffset; else if (dataType == typeof(DBNull)) throw ADP.InvalidDataType("DBNull"); else if (dataType == typeof(Boolean)) return s_metaBit; else if (dataType == typeof(Char)) throw ADP.InvalidDataType("Char"); else if (dataType == typeof(SByte)) throw ADP.InvalidDataType("SByte"); else if (dataType == typeof(Byte)) return s_metaTinyInt; else if (dataType == typeof(Int16)) return s_metaSmallInt; else if (dataType == typeof(UInt16)) throw ADP.InvalidDataType("UInt16"); else if (dataType == typeof(Int32)) return s_metaInt; else if (dataType == typeof(UInt32)) throw ADP.InvalidDataType("UInt32"); else if (dataType == typeof(Int64)) return s_metaBigInt; else if (dataType == typeof(UInt64)) throw ADP.InvalidDataType("UInt64"); else if (dataType == typeof(Single)) return s_metaReal; else if (dataType == typeof(Double)) return s_metaFloat; else if (dataType == typeof(Decimal)) return MetaDecimal; else if (dataType == typeof(DateTime)) return s_metaDateTime; else if (dataType == typeof(String)) return MetaNVarChar; else throw ADP.UnknownDataType(dataType); } static internal MetaType GetMetaTypeFromValue(object value, bool inferLen = true, bool streamAllowed = true) { if (value == null) { throw ADP.InvalidDataType("null"); } else if (value is DBNull) { throw ADP.InvalidDataType(typeof(DBNull).Name); } else if (value is bool) { return s_metaBit; } else if (value is char) { throw ADP.InvalidDataType(typeof(char).Name); } else if (value is sbyte) { throw ADP.InvalidDataType(typeof(sbyte).Name); } else if (value is byte) { return s_metaTinyInt; } else if (value is short) { return s_metaSmallInt; } else if (value is ushort) { throw ADP.InvalidDataType(typeof(ushort).Name); } else if (value is int) { return s_metaInt; } else if (value is uint) { throw ADP.InvalidDataType(typeof(uint).Name); } else if (value is long) { return s_metaBigInt; } else if (value is ulong) { throw ADP.InvalidDataType(typeof(ulong).Name); } else if (value is float) { return s_metaReal; } else if (value is double) { return s_metaFloat; } else if (value is decimal) { return MetaDecimal; } else if (value is DateTime) { return s_metaDateTime; } else if (value is string) { return (inferLen ? PromoteStringType((string)value) : MetaNVarChar); } else if (value is byte[]) { if (!inferLen || ((byte[])value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } else if (value is Guid) { return s_metaUniqueId; } else if (value is SqlBinary) return MetaVarBinary; else if (value is SqlBoolean) return s_metaBit; else if (value is SqlByte) return s_metaTinyInt; else if (value is SqlBytes) return MetaVarBinary; else if (value is SqlChars) return MetaNVarChar; else if (value is SqlDateTime) return s_metaDateTime; else if (value is SqlDouble) return s_metaFloat; else if (value is SqlGuid) return s_metaUniqueId; else if (value is SqlInt16) return s_metaSmallInt; else if (value is SqlInt32) return s_metaInt; else if (value is SqlInt64) return s_metaBigInt; else if (value is SqlMoney) return s_metaMoney; else if (value is SqlDecimal) return MetaDecimal; else if (value is SqlSingle) return s_metaReal; else if (value is SqlXml) return MetaXml; else if (value is SqlString) { return ((inferLen && !((SqlString)value).IsNull) ? PromoteStringType(((SqlString)value).Value) : MetaNVarChar); } else if (value is IEnumerable<DbDataRecord>) { return s_metaTable; } else if (value is TimeSpan) { return MetaTime; } else if (value is DateTimeOffset) { return MetaDateTimeOffset; } else if (streamAllowed) { // Derived from Stream ? if (value is Stream) { return MetaVarBinary; } // Derived from TextReader ? if (value is TextReader) { return MetaNVarChar; } // Derived from XmlReader ? if (value is XmlReader) { return MetaXml; } } throw ADP.UnknownDataType(value.GetType()); } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Assert(false, "Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { Debug.Assert(false, "unknown SqlType class stored in sqlVal"); } return comVal; } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Assert(false, "unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: //goto TdsEnums.SQLBIGVARCHAR; case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: //goto TdsEnums.SQLBIGBINARY; case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: //goto TdsEnums.SQLBIGCHAR; case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: //goto TdsEnums.SQLBITN; case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: //goto TdsEnums.SQLNUMERICN; case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLUDT: return s_metaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Assert(false, "Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); }// case } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // syntatic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // HACK!!! We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); private static readonly MetaType s_metaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days&minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; namespace OpenSim.Services.UserAccountService { public class GridUserService : GridUserServiceBase, IGridUserService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public GridUserService(IConfigSource config) : base(config) { m_log.Debug("[GRID USER SERVICE]: Starting user grid service"); MainConsole.Instance.Commands.AddCommand( "Users", false, "show grid user", "show grid user <ID>", "Show grid user entry or entries that match or start with the given ID. This will normally be a UUID.", "This is for debug purposes to see what data is found for a particular user id.", HandleShowGridUser); MainConsole.Instance.Commands.AddCommand( "Users", false, "show grid users online", "show grid users online", "Show number of grid users registered as online.", "This number may not be accurate as a region may crash or not be cleanly shutdown and leave grid users shown as online\n." + "For this reason, users online for more than 5 days are not currently counted", HandleShowGridUsersOnline); } protected void HandleShowGridUser(string module, string[] cmdparams) { if (cmdparams.Length != 4) { MainConsole.Instance.Output("Usage: show grid user <UUID>"); return; } GridUserData[] data = m_Database.GetAll(cmdparams[3]); foreach (GridUserData gu in data) { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("User ID", gu.UserID); foreach (KeyValuePair<string,string> kvp in gu.Data) cdl.AddRow(kvp.Key, kvp.Value); MainConsole.Instance.Output(cdl.ToString()); } MainConsole.Instance.OutputFormat("Entries: {0}", data.Length); } protected void HandleShowGridUsersOnline(string module, string[] cmdparams) { // if (cmdparams.Length != 4) // { // MainConsole.Instance.Output("Usage: show grid users online"); // return; // } // int onlineCount; int onlineRecentlyCount = 0; DateTime now = DateTime.UtcNow; foreach (GridUserData gu in m_Database.GetAll("")) { if (bool.Parse(gu.Data["Online"])) { // onlineCount++; int unixLoginTime = int.Parse(gu.Data["Login"]); if ((now - Util.ToDateTime(unixLoginTime)).Days < 5) onlineRecentlyCount++; } } MainConsole.Instance.OutputFormat("Users online: {0}", onlineRecentlyCount); } private GridUserData GetGridUserData(string userID) { GridUserData d = null; if (userID.Length > 36) // it's a UUI { d = m_Database.Get(userID); } else // it's a UUID { GridUserData[] ds = m_Database.GetAll(userID); if (ds == null) return null; if (ds.Length > 0) { d = ds[0]; foreach (GridUserData dd in ds) if (dd.UserID.Length > d.UserID.Length) // find the longest d = dd; } } return d; } public virtual GridUserInfo GetGridUserInfo(string userID) { GridUserData d = GetGridUserData(userID); if (d == null) return null; GridUserInfo info = new GridUserInfo(); info.UserID = d.UserID; info.HomeRegionID = new UUID(d.Data["HomeRegionID"]); info.HomePosition = Vector3.Parse(d.Data["HomePosition"]); info.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]); info.LastRegionID = new UUID(d.Data["LastRegionID"]); info.LastPosition = Vector3.Parse(d.Data["LastPosition"]); info.LastLookAt = Vector3.Parse(d.Data["LastLookAt"]); info.Online = bool.Parse(d.Data["Online"]); info.Login = Util.ToDateTime(Convert.ToInt32(d.Data["Login"])); info.Logout = Util.ToDateTime(Convert.ToInt32(d.Data["Logout"])); return info; } public virtual GridUserInfo[] GetGridUserInfo(string[] userIDs) { List<GridUserInfo> ret = new List<GridUserInfo>(); foreach (string id in userIDs) ret.Add(GetGridUserInfo(id)); return ret.ToArray(); } public GridUserInfo LoggedIn(string userID) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is online", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = true.ToString(); d.Data["Login"] = Util.UnixTimeSinceEpoch().ToString(); m_Database.Store(d); return GetGridUserInfo(userID); } public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = false.ToString(); d.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString(); d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt) { GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["HomeRegionID"] = homeID.ToString(); d.Data["HomePosition"] = homePosition.ToString(); d.Data["HomeLookAt"] = homeLookAt.ToString(); return m_Database.Store(d); } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // m_log.DebugFormat("[GRID USER SERVICE]: SetLastPosition for {0}", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } } }
using System; using System.Collections.Generic; using Alensia.Core.Common; using Alensia.Core.Common.Extension; using Alensia.Core.UI.Event; using Alensia.Core.UI.Property; using UniRx; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; using Object = UnityEngine.Object; using UESlider = UnityEngine.UI.Slider; namespace Alensia.Core.UI { public class Slider : InteractableComponent<UESlider, UESlider>, IInputComponent<float> { public float Value { get { return _value.Value; } set { _value.Value = value; } } public float MinValue { get { return _minValue.Value; } set { _minValue.Value = value; } } public float MaxValue { get { return _maxValue.Value; } set { _maxValue.Value = value; } } public ImageAndColorSet Background { get { return _background.Value; } set { Assert.IsNotNull(value, "value != null"); _background.Value = value; } } public ImageAndColorSet FillImage { get { return _fillImage.Value; } set { Assert.IsNotNull(value, "value != null"); _fillImage.Value = value; } } public ImageAndColorSet HandleImage { get { return _handleImage.Value; } set { Assert.IsNotNull(value, "value != null"); _handleImage.Value = value; } } public IObservable<float> OnValueChange => _value; protected override ImageAndColor DefaultBackground { get { var value = DefaultBackgroundSet; return value?.ValueFor(this)?.Merge(base.DefaultBackground) ?? base.DefaultBackground; } } protected virtual ImageAndColorSet DefaultBackgroundSet => Style?.ImageAndColorSets?["Slider.Background"]; protected virtual ImageAndColor DefaultFillImage => DefaultFillImageSet?.ValueFor(this); protected virtual ImageAndColorSet DefaultFillImageSet => Style?.ImageAndColorSets?["Slider.FillImage"]; protected virtual ImageAndColor DefaultHandleImage => DefaultHandleImageSet?.ValueFor(this); protected virtual ImageAndColorSet DefaultHandleImageSet => Style?.ImageAndColorSets?["Slider.HandleImage"]; protected UESlider PeerSlider => _peerSlider ?? (_peerSlider = GetComponentInChildren<UESlider>()); protected Image PeerBackground => _peerBackground ?? (_peerBackground = FindPeer<Image>("Background")); protected Transform PeerFillArea => _peerFillArea ?? (_peerFillArea = Transform.Find("Fill Area")); protected Image PeerFill => _peerFill ?? (_peerFill = PeerFillArea.FindComponent<Image>("Fill")); protected Transform PeerHandleSlideArea => _peerHandleSlideArea ?? (_peerHandleSlideArea = Transform.Find("Handle Slide Area")); protected Image PeerHandle => _peerHandle ?? (_peerHandle = PeerHandleSlideArea.FindComponent<Image>("Handle")); protected override UESlider PeerSelectable => PeerSlider; protected override UESlider PeerHotspot => PeerSlider; protected override IList<Object> Peers { get { var peers = base.Peers; if (PeerSlider != null) peers.Add(PeerSlider); if (PeerBackground != null) peers.Add(PeerBackground.gameObject); if (PeerFillArea != null) peers.Add(PeerFillArea.gameObject); if (PeerHandleSlideArea != null) peers.Add(PeerHandleSlideArea.gameObject); return peers; } } [SerializeField] private FloatReactiveProperty _value; [SerializeField] private FloatReactiveProperty _minValue; [SerializeField] private FloatReactiveProperty _maxValue; [SerializeField] private ImageAndColorSetReactiveProperty _background; [SerializeField] private ImageAndColorSetReactiveProperty _fillImage; [SerializeField] private ImageAndColorSetReactiveProperty _handleImage; [SerializeField, HideInInspector] private UESlider _peerSlider; [SerializeField, HideInInspector] private Image _peerBackground; [SerializeField, HideInInspector] private Image _peerFill; [SerializeField, HideInInspector] private Image _peerHandle; [NonSerialized] private Transform _peerFillArea; [NonSerialized] private Transform _peerHandleSlideArea; protected override void InitializeComponent(IUIContext context, bool isPlaying) { base.InitializeComponent(context, isPlaying); _value .Subscribe(v => PeerSlider.value = v, Debug.LogError) .AddTo(this); if (!isPlaying) return; PeerSlider .OnValueChangedAsObservable() .Subscribe(v => Value = v, Debug.LogError) .AddTo(this); _minValue .Subscribe(v => PeerSlider.minValue = v, Debug.LogError) .AddTo(this); _maxValue .Subscribe(v => PeerSlider.maxValue = v, Debug.LogError) .AddTo(this); _background .Select(v => v.ValueFor(this)) .Subscribe(v => v.Update(PeerBackground, DefaultBackground), Debug.LogError) .AddTo(this); _fillImage .Select(v => v.ValueFor(this)) .Subscribe(v => v.Update(PeerFill, DefaultFillImage), Debug.LogError) .AddTo(this); _handleImage .Select(v => v.ValueFor(this)) .Subscribe(v => v.Update(PeerHandle, DefaultHandleImage), Debug.LogError) .AddTo(this); } protected override void OnEditorUpdate() { base.OnEditorUpdate(); PeerSlider.minValue = MinValue; PeerSlider.maxValue = MaxValue; PeerSlider.value = Value; } protected override void OnStyleChanged(UIStyle style) { base.OnStyleChanged(style); Background.ValueFor(this).Update(PeerBackground, DefaultBackground); FillImage.ValueFor(this).Update(PeerFill, DefaultFillImage); HandleImage.ValueFor(this).Update(PeerHandle, DefaultHandleImage); } protected override EventTracker<UESlider> CreateInterationTracker() => new PointerDragTracker<UESlider>(PeerHotspot); protected override void ResetFromInstance(UIComponent component) { base.ResetFromInstance(component); var source = (Slider) component; MinValue = 0; MaxValue = 1; Value = 0; Background = new ImageAndColorSet(source.Background); FillImage = new ImageAndColorSet(source.FillImage); HandleImage = new ImageAndColorSet(source.HandleImage); } protected override UIComponent CreatePristineInstance() => CreateInstance(); public static Slider CreateInstance() { var prefab = Resources.Load<GameObject>("UI/Components/Slider"); Assert.IsNotNull(prefab, "prefab != null"); return Instantiate(prefab).GetComponent<Slider>(); } } }
// 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.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { public abstract class Stream : IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int DefaultCopyBufferSize = 81920; // To implement Async IO operations on streams that don't support async IO private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } public abstract bool CanRead { [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { [Pure] get; } public virtual bool CanTimeout { [Pure] get { return false; } } public abstract bool CanWrite { [Pure] get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public virtual int WriteTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public Task CopyToAsync(Stream destination) { return CopyToAsync(destination, DefaultCopyBufferSize); } public Task CopyToAsync(Stream destination, int bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { if (destination == null) { throw new ArgumentNullException("destination"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum); } if (!CanRead && !CanWrite) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException("destination", SR.ObjectDisposed_StreamClosed); } if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (!destination.CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken) { Debug.Assert(destination != null); Debug.Assert(bufferSize > 0); Debug.Assert(CanRead); Debug.Assert(destination.CanWrite); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { if (destination == null) { throw new ArgumentNullException("destination"); } if (!CanRead && !CanWrite) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException("destination", SR.ObjectDisposed_StreamClosed); } if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (!destination.CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } InternalCopyTo(destination, DefaultCopyBufferSize); } public void CopyTo(Stream destination, int bufferSize) { if (destination == null) { throw new ArgumentNullException("destination"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum); } if (!CanRead && !CanWrite) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException("destination", SR.ObjectDisposed_StreamClosed); } if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (!destination.CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } InternalCopyTo(destination, bufferSize); } private void InternalCopyTo(Stream destination, int bufferSize) { Debug.Assert(destination != null); Debug.Assert(CanRead); Debug.Assert(destination.CanWrite); Debug.Assert(bufferSize > 0); byte[] buffer = new byte[bufferSize]; int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, read); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); public Task FlushAsync() { return FlushAsync(CancellationToken.None); } public virtual Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new Task(() => { }, cancellationToken); } return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } if (cancellationToken.IsCancellationRequested) { return new Task<int>(() => 0, cancellationToken); } return ReadAsyncTask(buffer, offset, count, cancellationToken); } private async Task<int> ReadAsyncTask(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. EnsureAsyncActiveSemaphoreInitialized().Wait(); try { return await Task.Factory.StartNew(() => Read(buffer, offset, count), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } finally { _asyncActiveSemaphore.Release(); } } public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } if (cancellationToken.IsCancellationRequested) { return new Task(() => { }, cancellationToken); } return WriteAsyncTask(buffer, offset, count, cancellationToken); } private async Task WriteAsyncTask(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. EnsureAsyncActiveSemaphoreInitialized().Wait(); try { await Task.Factory.StartNew(() => Write(buffer, offset, count), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } finally { _asyncActiveSemaphore.Release(); } } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read(byte[] buffer, int offset, int count); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) { return -1; } return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { [Pure] get { return true; } } public override bool CanWrite { [Pure] get { return true; } } public override bool CanSeek { [Pure] get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } #pragma warning disable 1998 // async method with no await public override async Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); } #pragma warning restore 1998 public override int Read(byte[] buffer, int offset, int count) { return 0; } #pragma warning disable 1998 // async method with no await public override async Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return 0; } #pragma warning restore 1998 public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } #pragma warning disable 1998 // async method with no await public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); } #pragma warning restore 1998 public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.ComponentModel; using System.Reflection; using System.Web; using System.Collections.Generic; using SoftLogik.Collections; using SoftLogik.Reflection; namespace SoftLogik.Web { /// <summary> /// Marks a field or property as being bound to a specific parameter present in the /// <see cref="System.Web.HttpRequest"/>. This attribute is normally only /// applied to subclasses of <see cref="System.Web.UI.Page"/> /// </summary> /// <example> /// Here a simple page class marks field with the attribute, and then /// calls the static WebParameterAttribute.SetValues() method to /// automatically load the fields with value from Request.Form or Request.QueryString /// (depending on what was used to submit the form). Note that since /// parameter binding in this example is done both on first-request /// and on postback, this page must always be either linked to supplying /// data in the querystring, or cross-posted to with the data in the Form. /// <code><![CDATA[ /// public class BoundParameterDemo : System.Web.UI.Page{ /// [WebParameter()] /// protected string FirstName; /// /// [WebParameter("Last_Name")] /// protected string LastName; /// /// [WebParameter(IsRequired=true)] /// protected int CustomerID; /// /// private void Page_Load(object sender, System.EventArgs e) { /// WebParameterAttribute.SetValues(this, Request); /// } /// } /// ]]> /// </code> /// </example> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public abstract class WebParameterAttribute : Attribute { #region Declarations object _defaultValue; string _parameterName; bool _isRequired = false; bool _isDefaultForInvalid = false; bool _overwriteNonDefaultValue = true; #endregion #region Constructors /// <summary> /// Creates a new WebParameterAttribute to load a field from an identically-named /// parameter in the Form/QueryString collection, if it exists. /// The parameter has no default value, and is not required /// </summary> protected WebParameterAttribute() { } /// <summary> /// Creates a new WebParameterAttribute to load a field from the given parameter name /// The parameter has no default value, and is not required /// </summary> /// <param name="paramName">The key of a parameter in the Form or QueryString collections</param> protected WebParameterAttribute(string paramName) { _parameterName = paramName; } #endregion /// <summary> /// The name (key) of the parameter being bound against in the Request /// </summary> public string ParameterName { get { return _parameterName; } set { _parameterName = value; } } /// <summary> /// An optional default value to use if the parameter doesn't exist /// in the current Request, or null to clear /// </summary> /// <remarks>Whilst this is a bit unneccesary for a field, its /// handy for properties - can save all that <code>if(ViewState["x"]==null)</code> /// stuff...</remarks> public object DefaultValue { get { return _defaultValue; } set { _defaultValue = value; } } /// <summary> /// Whether the absence of the parameter, along with the absence /// of a default, causes an error, rather than the default /// behaviour which is that the field will just be skipped. /// The default is false. /// </summary> public bool IsRequired { get { return _isRequired; } set { _isRequired = value; } } /// <summary> /// Whether the default value can be used if the value passed to /// the page is invalid in some way (rejected by the type converter, /// or causes an error on the field/property set). /// The default is false. /// </summary> public bool IsDefaultUsedForInvalid { get { return _isDefaultForInvalid; } set { _isDefaultForInvalid = value; } } /// <summary> /// Whether the value is retrieved from the parameter /// on post back. /// </summary> public bool OverwriteNonDefaultValue { get { return _overwriteNonDefaultValue; } set { _overwriteNonDefaultValue = value; } } /// <summary> /// Retrieves an item either from the Query or POST collections, depending on the /// mode of the request, or performs custom retrieval in derived classes /// </summary> protected abstract string GetValue(string paramName, HttpRequest request); /// <summary> /// Sets public properties and fields on <c>target</c> that are marked with /// <see cref="WebParameterAttribute"/> to the corresponding values retrieved from /// <c>request</c>, or a default value as set on the attribute /// </summary> /// <param name="target">The object (typically a <see cref="System.Web.UI.Page"/>) being bound</param> /// <param name="request">The <see cref="System.Web.HttpRequest"/> to load the data from. /// The attribute determines whether data is loaded from request.Form, request.QueryString /// or other parts of request</param> public static void SetValues(object target, HttpRequest request, bool isPostBack) { // Get the page type Type pageType = target.GetType().BaseType; List<MemberInfo> targetMembers = ReflectionUtils.GetFieldsAndProperties(pageType, BindingFlags.Instance | BindingFlags.Public); // Loop over the fields and properties for (int i = 0; i < targetMembers.Count; i++) SetValue(targetMembers[i], target, request, isPostBack); } public static T GetAttribute<T>(MemberInfo member) where T : Attribute { T[] attributes = (T[])member.GetCustomAttributes(typeof(T), true); if (!CollectionUtils.IsNullOrEmpty<T>(attributes)) return attributes[0]; else return null; } /// <summary> /// Examines a single <c>member</c> (a property or field) for <see cref="WebParameterAttribute"/>. /// If so marked then the member is set on <c>target</c> with the relevant value /// retrieved from <c>request</c>, or the default value provided in the attribute /// </summary> /// <param name="target">The object (typically a <see cref="System.Web.UI.Page"/>) being bound</param> /// <param name="request">The <see cref="System.Web.HttpRequest"/> to load the data from. /// The attribute determines whether data is loaded from request.Form, request.QueryString /// or other parts of request</param> private static void SetValue(MemberInfo member, object target, HttpRequest request, bool isPostBack) { WebParameterAttribute attrib; TypeConverter converter; object paramValue; string paramName; attrib = ReflectionUtils.GetAttribute<WebParameterAttribute>(member, true); if (attrib != null) { // Use the attribute name if supplied, otherwise use the member's name if (attrib.ParameterName != null) paramName = attrib.ParameterName; else paramName = member.Name; // Make sure we're not going after an indexed property if (member.MemberType == MemberTypes.Property) { ParameterInfo[] ps = ((PropertyInfo)member).GetIndexParameters(); if (!CollectionUtils.IsNullOrEmpty<ParameterInfo>(ps)) throw new NotSupportedException(string.Format("Parameter '{0}' applied to an indexed Property. Cannot apply WebParameterAttribute to indexed property", paramName)); } Type underlyingType = ReflectionUtils.GetMemberUnderlyingType(member); // If a default is supplied, insure it is of the underlying type if (attrib.DefaultValue != null) { if (!underlyingType.IsAssignableFrom(attrib.DefaultValue.GetType())) { throw new ApplicationException(string.Format("The default value for the parameter '{0}' has different type then the one of the property itself.", paramName)); } } if (!attrib.OverwriteNonDefaultValue) { // return if member value is non default or empty string object currentMemberValue = ReflectionUtils.GetMemberValue(member, target); bool isDefaultValue; if (underlyingType == typeof(string)) isDefaultValue = string.IsNullOrEmpty((string)currentMemberValue); else isDefaultValue = ReflectionUtils.IsUnitializedValue(currentMemberValue); // value is not default. don't set value if (!isDefaultValue) return; } // Use parameter name to get the value from the request object paramValue = attrib.GetValue(paramName, request); if (paramValue != null) { // Now assign the loaded value onto the member, using the relevant type converter // Have to perform the assignment slightly differently for fields and properties converter = TypeDescriptor.GetConverter(underlyingType); if (converter == null || !converter.CanConvertFrom(paramValue.GetType())) throw new ApplicationException(string.Format("Could not convert from {0} to {1}", paramValue.GetType(), underlyingType)); if (ReflectionUtils.CanSetMemberValue(member)) { try { ReflectionUtils.SetMemberValue(member, target, converter.ConvertFrom(paramValue)); } catch { // We catch errors both from the type converter // and from any problems in setting the field/property // (eg property-set rules, security, readonly properties) // If there is a default and it is used for invalid data // then set member to default if (attrib.IsDefaultUsedForInvalid && attrib.DefaultValue != null) { ReflectionUtils.SetMemberValue(member, target, attrib.DefaultValue); } else { throw; } } } else { throw new Exception(string.Format("Member '{0}' on type '{1}' could not be set.", member.Name, member.DeclaringType.FullName)); } } else if (attrib.DefaultValue != null) { ReflectionUtils.SetMemberValue(member, target, attrib.DefaultValue); } else { if (attrib.IsRequired) throw new ApplicationException(string.Format("Required parameter '{0}' evaluated to null", paramName)); // Throw an error if cannot assign null to member's underlying type if (!ReflectionUtils.IsNullable(underlyingType)) throw new ApplicationException(string.Format("Parameter '{0}' mapped to a non-nullable ValueType evaluated to null", paramName)); ReflectionUtils.SetMemberValue(member, target, null); } } } } }
//css_import d:\\wsod\\scripts\\include\\WSODCs\\CSWrapper.cs; // // Creator: Jason Wooten using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; class DAGScript { // private int jobStatus = "STAGE_SUCCESS"; private Dictionary<string, string> dTableMap = new Dictionary<string, string>(); private ArrayList lFilesToIgnore = new ArrayList(); //public static void Main(string[] args) //{ // DAGScript script = new DAGScript(); // script.Execute(args); //} public string GetWIPDirectory() { return @"c:\projects\playground\Eric.Scott\01TestData\output\"; } public void run() { FileLineCache = new Dictionary<string, List<string>>(); string [] sFileNames = { @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20120813.txt", @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20171017.txt", @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20171018.txt", @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20171019.txt", @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20171020.txt" }; string sFileName = @"C:\Projects\Playground\Eric.Scott\01TestData\mkt_ETF_Analytics_Data_20120813.txt"; //oLog.Log("ENV: " + GetEnvironment()); //grabs current env (D1,A1,P1,P2,P3) and writes to log //InitDictionary(dTableMap); //int iFilesProcessed = 0; //int iResultCount = ScriptData.GetValueAs<int>("File.ResultCount", 0); //for (int iResult = 0; iResult < iResultCount; iResult++) //{ // int iRowCount = ScriptData.GetValueAs<int>("File.Result[" + iResult + "].RowCount", 0); // for (int iRow = 0; iRow < iRowCount; iRow++) // { // string sFileName = ScriptData.GetValueAs<string>("File.Result[" + iResult + "].Row[" + iRow + "].File.Name"); // if (sFileName.Contains("mkt_ETF_Analytics_Data")) // { InitDictionary(dTableMap); //Parallel.ForEach(sFileNames, (file) => // { // ParseFile(file); // }); foreach (string esFileName in sFileNames) ParseFile(esFileName); //iFilesProcessed++; // } // else // { // lFilesToIgnore.Add(sFileName); // } // oLog.Log("sFileName: " + sFileName); //} // } //PrepareGPSA(); //ScriptData["StageStatus"] = jobStatus; } private void InitDictionary(Dictionary<string, string> dTableMap) { // Xref population file string sFileT0 = GetWIPDirectory() + "XrefPopulation.txt"; string sCoulumnT0 = "0,1,2,5,6,7,8"; dTableMap.Add(sFileT0, sCoulumnT0); //dbo.MarkitETPNAV string sFileT1 = GetWIPDirectory() + "MarkitETPNAV.txt"; string sCoulumnT1 = "0,5,8,3,7,12,15,16,17"; dTableMap.Add(sFileT1, sCoulumnT1); //dbo.MarkitETPAUM string sFileT2 = GetWIPDirectory() + "MarkitETPAUM.txt"; string sCoulumnT2 = "0,5,8,12,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74"; dTableMap.Add(sFileT2, sCoulumnT2); //dbo.MarkitETPPricing string sFileT3 = GetWIPDirectory() + "MarkitETPPricing.txt"; string sCoulumnT3 = "0,5,8,140,141,142,145,146,147,148,149,150,154,155,156,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,298,299,300,301,302,303,304,305,306,307,308,309,870,871,869"; dTableMap.Add(sFileT3, sCoulumnT3); //dbo.MarkitETPSharesOutstanding string sFileT4 = GetWIPDirectory() + "MarkitETPSharesOutstanding.txt"; string sCoulumnT4 = "0,5,8,12,18,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89"; dTableMap.Add(sFileT4, sCoulumnT4); //dbo.MarkitETPTopHoldingsPercent //string sFileT5 = GetWIPDirectory() + "MarkitETPTopHoldingsPercent.txt"; //string sCoulumnT5 = "0,5,8,818"; //dTableMap.Add(sFileT5, sCoulumnT5); //dbo.MarkitETPDividends string sFileT6 = GetWIPDirectory() + "MarkitETPDividends.txt"; string sCoulumnT6 = "0,5,8,12,4,869,14"; dTableMap.Add(sFileT6, sCoulumnT6); //dbo.MarkitETPBenchmark - MarkitETPBRUKBenchmark string sFileT7 = GetWIPDirectory() + "MarkitETPBRUKBenchmark.txt"; string sCoulumnT7 = "0,5,8,9,10,11,12"; dTableMap.Add(sFileT7, sCoulumnT7); //dbo.MarkitETPSplits //string sFileT8 = GetWIPDirectory() + "MarkitETPSplits.txt"; //string sCoulumnT8 = "0,5,8,13"; //dTableMap.Add(sFileT8, sCoulumnT8); //dbo.MarkitETPPricingVolumeOther string sFileT9 = GetWIPDirectory() + "MarkitETPPricingVolumeOther.txt"; string sCoulumnT9 = "0,5,8,334,335,336,337,338,339,340,341,342,343,344,345"; dTableMap.Add(sFileT9, sCoulumnT9); //dbo.MarkitETPPremiumDiscount //string sFileT10 = GetWIPDirectory() + "MarkitETPPremiumDiscount.txt"; //string sCoulumnT10 = "0,5,8,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174"; //dTableMap.Add(sFileT10, sCoulumnT10); //dbo.MarkitETPPerformance string sFileT11 = GetWIPDirectory() + "MarkitETPPerformance.txt"; string sCoulumnT11 = "0,5,8,12,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505"; dTableMap.Add(sFileT11, sCoulumnT11); //dbo.MarkitETPBenchmarkPerformance string sFileT12 = GetWIPDirectory() + "MarkitETPBenchmarkPerformance.txt"; string sCoulumnT12 = "0,5,8,382,383,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675"; dTableMap.Add(sFileT12, sCoulumnT12); //dbo.MarkitETPRegionalAllocation - MarkitETPBRUKRegionalAllocation string sFileT13 = GetWIPDirectory() + "MarkitETPBRUKRegionalAllocation.txt"; string sCoulumnT13 = "0,5,8,819,820,821,822,823,824,825,12"; dTableMap.Add(sFileT13, sCoulumnT13); //dbo.MarkitETPAssetClassBreakdown - MarkitETPBRUKAssetClassBreakdown string sFileT14 = GetWIPDirectory() + "MarkitETPBRUKAssetClassBreakdown.txt"; string sCoulumnT14 = "0,5,8,826,827,828,829,830,831,832,833,834,835,836,837,12"; dTableMap.Add(sFileT14, sCoulumnT14); //dbo.MarkitETPSectorAllocation - MarkitETPBRUKSectorAllocation string sFileT15 = GetWIPDirectory() + "MarkitETPBRUKSectorAllocation.txt"; string sCoulumnT15 = "0,5,8,838,839,840,841,842,843,844,845,846,847,848,12"; dTableMap.Add(sFileT15, sCoulumnT15); //dbo.MarkitETPEconomicAllocation //string sFileT16 = GetWIPDirectory() + "MarkitETPEconomicAllocation.txt"; //string sCoulumnT16 = "0,5,8,849,850,851,852"; //dTableMap.Add(sFileT16, sCoulumnT16); //dbo.MarkitETPRiskMeasures - MarkitETPBRUKRiskMeasures string sFileT17 = GetWIPDirectory() + "MarkitETPBRUKRiskMeasures.txt"; string sCoulumnT17 = "0,5,8,853,854,855,856,857,858,859,860,861,12"; dTableMap.Add(sFileT17, sCoulumnT17); //dbo.MarkitETPListingPerformance string sFileT18 = GetWIPDirectory() + "MarkitETPListingPerformance.txt"; string sCoulumnT18 = "0,5,8,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611"; dTableMap.Add(sFileT18, sCoulumnT18); //dbo.MarkitETPListingPerformanceSupplemental string sFileT19 = GetWIPDirectory() + "MarkitETPListingPerformanceSupplemental.txt"; string sCoulumnT19 = "0,5,6,8,558,559,560,561,562,563,564,565,566,567,568,569,570,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635"; dTableMap.Add(sFileT19, sCoulumnT19); //2017/09/27 //dbo.MarkitETPTrackingDifference string sFileT20 = GetWIPDirectory() + "MarkitETPTrackingDifference.txt"; string sCoulumnT20 = "0,5,8,12,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749"; dTableMap.Add(sFileT20, sCoulumnT20); //2017/09/27 //dbo.MarkitETPTrackingError string sFileT21 = GetWIPDirectory() + "MarkitETPTrackingError.txt"; string sCoulumnT21 = "0,5,8,12,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817"; dTableMap.Add(sFileT21, sCoulumnT21); } private void ParseFile(string sFileName) { string sDate = sFileName.Substring(sFileName.Length - 12, 8); using (StreamReader SR = new StreamReader(sFileName)) { while (SR.Peek() > 0) { string sLine = SR.ReadLine(); //Parallel.ForEach(dTableMap, (Pair) => // { // ExtractData(sLine, Pair, sDate); // }); //foreach (KeyValuePair<string, string> Pair in dTableMap) //{ // ExtractData(sLine, Pair, sDate); //} foreach (KeyValuePair<string, string> Pair in dTableMap) { ExtractData(sLine, Pair, sDate); } } FlushCache(); } } private void ExtractData(string sLineData, KeyValuePair<string, string> Pair, string sDate) { string sFileName = Pair.Key; string sColumDef = Pair.Value; string[] oColumDef = sColumDef.Split(','); // the column number I'm after in the Line. string[] oLineData = sLineData.Split('|'); // the array of data in the file I care about. string sNewLineForTable = ""; foreach (string colNo in oColumDef) { sNewLineForTable += oLineData[int.Parse(colNo)] + "|"; } //for (int jx = 0; jx < oColumDef.Length; jx++) //{ // for (int idx = 0; idx < oLineData.Length; idx++) // { // if (oColumDef[jx] == idx.ToString()) // { // sNewLineForTable += oLineData[idx] + "|"; // break; // } // } //} sNewLineForTable = sNewLineForTable.Substring(0, sNewLineForTable.LastIndexOf('|')); sFileName = sFileName.Substring(0, sFileName.Length - 4) + "_" + sDate + ".txt"; eAddLines(sFileName, sNewLineForTable); } Dictionary<string, List<string>> FileLineCache {get;set;} private void eAddLines(string sFileName, string sLinesOfData) { if(!FileLineCache.ContainsKey(sFileName)) FileLineCache.Add(sFileName, new List<string>()); FileLineCache[sFileName].Add(sLinesOfData); if(FileLineCache[sFileName].Count>20){ using (StreamWriter SW = new StreamWriter(sFileName, true)) { foreach(string line in FileLineCache[sFileName]) SW.WriteLine(line); } FileLineCache[sFileName].Clear(); } } private void FlushCache() { foreach(KeyValuePair<string, List<string>> kvp in FileLineCache) { using (StreamWriter SW = new StreamWriter(kvp.Key, true)) { foreach (string line in kvp.Value) SW.WriteLine(line); } } FileLineCache.Clear(); } private void AddLine(string sFileName, string sLineData) { using (StreamWriter SW = new StreamWriter(sFileName, true)) { SW.WriteLine(sLineData); } } //private void PrepareGPSA() //{ // int iRow = 0; // foreach (KeyValuePair<string, string> Pair in dTableMap) // { // if (File.Exists(Pair.Key)) // { // ScriptData["File.Result[0].Row[" + iRow++ + "].File.Name"] = Pair.Key; // } // } // foreach (string sFile in lFilesToIgnore) // { // ScriptData["File.Result[0].Row[" + iRow++ + "].File.Name"] = sFile; // } // ScriptData["File.Result[0].RowCount"] = iRow; // ScriptData["File.ResultCount"] = 1; // jobStatus = iRow == 0 ? STAGE_FAILED_SOFT : jobStatus; //} }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using NPOI.HSSF.Record; using NPOI.HSSF.Record.CF; using NPOI.SS.UserModel; /** * High level representation for Font Formatting component * of Conditional Formatting Settings * * @author Dmitriy Kumshayev * */ public class HSSFFontFormatting : IFontFormatting { private FontFormatting fontFormatting; public HSSFFontFormatting(CFRuleRecord cfRuleRecord) { this.fontFormatting = cfRuleRecord.FontFormatting; } protected FontFormatting GetFontFormattingBlock() { return fontFormatting; } /** * Get the type of base or subscript for the font * * @return base or subscript option */ public FontSuperScript EscapementType { get { return (FontSuperScript)fontFormatting.EscapementType; } set { switch (value) { case FontSuperScript.Sub: case FontSuperScript.Super: fontFormatting.EscapementType = value; fontFormatting.IsEscapementTypeModified = true; break; case FontSuperScript.None: fontFormatting.EscapementType = value; fontFormatting.IsEscapementTypeModified = false; break; } } } /** * @return font color index */ public short FontColorIndex { get { return fontFormatting.FontColorIndex; } set { fontFormatting.FontColorIndex=(value); } } /** * Gets the height of the font in 1/20th point Units * * @return fontheight (in points/20); or -1 if not modified */ public int FontHeight { get { return fontFormatting.FontHeight; } set { fontFormatting.FontHeight=(value); } } /** * Get the font weight for this font (100-1000dec or 0x64-0x3e8). Default Is * 0x190 for normal and 0x2bc for bold * * @return bw - a number between 100-1000 for the fonts "boldness" */ public short FontWeight { get { return fontFormatting.FontWeight; } } /** * @return * @see org.apache.poi.hssf.record.cf.FontFormatting#GetRawRecord() */ protected byte[] GetRawRecord() { return fontFormatting.GetRawRecord(); } /** * Get the type of Underlining for the font * * @return font Underlining type * * @see #U_NONE * @see #U_SINGLE * @see #U_DOUBLE * @see #U_SINGLE_ACCOUNTING * @see #U_DOUBLE_ACCOUNTING */ public FontUnderlineType UnderlineType { get { return (FontUnderlineType)fontFormatting.UnderlineType; } set { switch (value) { case FontUnderlineType.Single: case FontUnderlineType.Double: case FontUnderlineType.SingleAccounting: case FontUnderlineType.DoubleAccounting: fontFormatting.UnderlineType = value; IsUnderlineTypeModified = true; break; case FontUnderlineType.None: fontFormatting.UnderlineType = value; IsUnderlineTypeModified = false; break; } } } /** * Get whether the font weight Is Set to bold or not * * @return bold - whether the font Is bold or not */ public bool IsBold { get { return fontFormatting.IsFontWeightModified && fontFormatting.IsBold; } } /** * @return true if escapement type was modified from default */ public bool IsEscapementTypeModified { get{ return fontFormatting.IsEscapementTypeModified; } set { fontFormatting.IsEscapementTypeModified=value; } } /** * @return true if font cancellation was modified from default */ public bool IsFontCancellationModified { get{ return fontFormatting.IsFontCancellationModified; } set { fontFormatting.IsFontCancellationModified=(value); } } /** * @return true if font outline type was modified from default */ public bool IsFontOutlineModified { get { return fontFormatting.IsFontOutlineModified; } set { fontFormatting.IsFontOutlineModified=(value); } } /** * @return true if font shadow type was modified from default */ public bool IsFontShadowModified { get { return fontFormatting.IsFontShadowModified; } set { fontFormatting.IsFontShadowModified=value; } } /** * @return true if font style was modified from default */ public bool IsFontStyleModified { get { return fontFormatting.IsFontStyleModified; } set { fontFormatting.IsFontStyleModified=value; } } /** * @return true if font style was Set to <i>italic</i> */ public bool IsItalic { get { return fontFormatting.IsFontStyleModified && fontFormatting.IsItalic; } } /** * @return true if font outline Is on */ public bool IsOutlineOn { get { return fontFormatting.IsFontOutlineModified && fontFormatting.IsOutlineOn; } set { fontFormatting.IsOutlineOn=value; fontFormatting.IsFontOutlineModified=value; } } /** * @return true if font shadow Is on */ public bool IsShadowOn { get{return fontFormatting.IsFontOutlineModified && fontFormatting.IsShadowOn;} set { fontFormatting.IsShadowOn=value; fontFormatting.IsFontShadowModified=value; } } /** * @return true if font strikeout Is on */ public bool IsStrikeout { get { return fontFormatting.IsFontCancellationModified && fontFormatting.IsStruckout; } set { fontFormatting.IsStruckout = (value); fontFormatting.IsFontCancellationModified = (value); } } /** * @return true if font Underline type was modified from default */ public bool IsUnderlineTypeModified { get{return fontFormatting.IsUnderlineTypeModified;} set { fontFormatting.IsUnderlineTypeModified=value; } } /** * @return true if font weight was modified from default */ public bool IsFontWeightModified { get{ return fontFormatting.IsFontWeightModified; } } /** * Set font style options. * * @param italic - if true, Set posture style to italic, otherwise to normal * @param bold- if true, Set font weight to bold, otherwise to normal */ public void SetFontStyle(bool italic, bool bold) { bool modified = italic || bold; fontFormatting.IsItalic=italic; fontFormatting.IsBold=bold; fontFormatting.IsFontStyleModified=modified; fontFormatting.IsFontWeightModified=modified; } /** * Set font style options to default values (non-italic, non-bold) */ public void ResetFontStyle() { SetFontStyle(false, false); } } }
// // Photo.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Stephane Delcroix <sdelcroix@src.gnome.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2008-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2008-2009 Stephane Delcroix // // 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 Hyena; using System; using System.IO; using System.Linq; using System.Collections.Generic; using Mono.Unix; using FSpot.Core; using FSpot.Utils; using FSpot.Imaging; namespace FSpot { public class Photo : DbItem, IComparable, IPhoto, IPhotoVersionable { #region Properties PhotoChanges changes = new PhotoChanges (); public PhotoChanges Changes { get{ return changes; } set { if (value != null) throw new ArgumentException ("The only valid value is null"); changes = new PhotoChanges (); } } // The time is always in UTC. private DateTime time; public DateTime Time { get { return time; } set { if (time == value) return; time = value; changes.TimeChanged = true; } } public string Name { get { return Uri.UnescapeDataString (System.IO.Path.GetFileName (VersionUri (OriginalVersionId).AbsolutePath)); } } private List<Tag> tags; public Tag [] Tags { get { return tags.ToArray (); } } private bool all_versions_loaded = false; internal bool AllVersionsLoaded { get { return all_versions_loaded; } set { if (value) if (DefaultVersionId != OriginalVersionId && !versions.ContainsKey (DefaultVersionId)) DefaultVersionId = OriginalVersionId; all_versions_loaded = value; } } private string description; public string Description { get { return description; } set { if (description == value) return; description = value; changes.DescriptionChanged = true; } } private uint roll_id = 0; public uint RollId { get { return roll_id; } set { if (roll_id == value) return; roll_id = value; changes.RollIdChanged = true; } } private uint rating; public uint Rating { get { return rating; } set { if (rating == value || value > 5) return; rating = value; changes.RatingChanged = true; } } #endregion #region Properties Version Management public const int OriginalVersionId = 1; private uint highest_version_id; private Dictionary<uint, PhotoVersion> versions = new Dictionary<uint, PhotoVersion> (); public IEnumerable<IPhotoVersion> Versions { get { foreach (var version in versions.Values) { yield return version; } } } public uint [] VersionIds { get { if (versions == null) return new uint [0]; uint [] ids = new uint [versions.Count]; versions.Keys.CopyTo (ids, 0); Array.Sort (ids); return ids; } } private uint default_version_id = OriginalVersionId; public uint DefaultVersionId { get { return default_version_id; } set { if (default_version_id == value) return; default_version_id = value; changes.DefaultVersionIdChanged = true; } } #endregion #region Photo Version Management public PhotoVersion GetVersion (uint version_id) { if (versions == null) return null; return versions [version_id]; } // This doesn't check if a version of that name already exists, // it's supposed to be used only within the Photo and PhotoStore classes. internal void AddVersionUnsafely (uint version_id, SafeUri base_uri, string filename, string import_md5, string name, bool is_protected) { versions [version_id] = new PhotoVersion (this, version_id, base_uri, filename, import_md5, name, is_protected); highest_version_id = Math.Max (version_id, highest_version_id); changes.AddVersion (version_id); } public uint AddVersion (SafeUri base_uri, string filename, string name) { return AddVersion (base_uri, filename, name, false); } public uint AddVersion (SafeUri base_uri, string filename, string name, bool is_protected) { if (VersionNameExists (name)) throw new ApplicationException ("A version with that name already exists"); highest_version_id ++; string import_md5 = String.Empty; // Modified version versions [highest_version_id] = new PhotoVersion (this, highest_version_id, base_uri, filename, import_md5, name, is_protected); changes.AddVersion (highest_version_id); return highest_version_id; } //FIXME: store versions next to originals. will crash on ro locations. private string GetFilenameForVersionName (string version_name, string extension) { string name_without_extension = System.IO.Path.GetFileNameWithoutExtension (Name); return name_without_extension + " (" + UriUtils.EscapeString (version_name, true, true, true) + ")" + extension; } public bool VersionNameExists (string version_name) { return Versions.Any (v => v.Name == version_name); } public SafeUri VersionUri (uint version_id) { if (!versions.ContainsKey (version_id)) return null; PhotoVersion v = versions [version_id]; return v != null ? v.Uri : null; } public IPhotoVersion DefaultVersion { get { if (!versions.ContainsKey (DefaultVersionId)) throw new Exception ("Something is horribly wrong, this should never happen: no default version!"); return versions [DefaultVersionId]; } } public void SetDefaultVersion (IPhotoVersion version) { PhotoVersion photo_version = version as PhotoVersion; if (photo_version == null) throw new ArgumentException ("Not a valid version for this photo"); DefaultVersionId = photo_version.VersionId; } //FIXME: won't work on non file uris public uint SaveVersion (Gdk.Pixbuf buffer, bool create_version) { uint version = DefaultVersionId; using (var img = ImageFile.Create (DefaultVersion.Uri)) { // Always create a version if the source is not a jpeg for now. create_version = create_version || ImageFile.IsJpeg (DefaultVersion.Uri); if (buffer == null) throw new ApplicationException ("invalid (null) image"); if (create_version) version = CreateDefaultModifiedVersion (DefaultVersionId, false); try { var versionUri = VersionUri (version); PixbufUtils.CreateDerivedVersion (DefaultVersion.Uri, versionUri, 95, buffer); GetVersion (version).ImportMD5 = HashUtils.GenerateMD5 (VersionUri (version)); DefaultVersionId = version; } catch (System.Exception e) { Log.Exception (e); if (create_version) DeleteVersion (version); throw e; } } return version; } public void DeleteVersion (uint version_id) { DeleteVersion (version_id, false, false); } public void DeleteVersion (uint version_id, bool remove_original) { DeleteVersion (version_id, remove_original, false); } public void DeleteVersion (uint version_id, bool remove_original, bool keep_file) { if (version_id == OriginalVersionId && !remove_original) throw new Exception ("Cannot delete original version"); SafeUri uri = VersionUri (version_id); if (!keep_file) { GLib.File file = GLib.FileFactory.NewForUri (uri); if (file.Exists) { try { file.Trash (null); } catch (GLib.GException) { Log.Debug ("Unable to Trash, trying to Delete"); file.Delete (); } } try { XdgThumbnailSpec.RemoveThumbnail (uri); } catch { // ignore an error here we don't really care. } // do we really need to check if the parent is a directory? // i.e. is file.Parent always a directory if the file instance is // an actual file? GLib.File directory = file.Parent; GLib.FileType file_type = directory.QueryFileType (GLib.FileQueryInfoFlags.None, null); if (directory.Exists && file_type == GLib.FileType.Directory) DeleteEmptyDirectory (directory); } versions.Remove (version_id); changes.RemoveVersion (version_id); for (version_id = highest_version_id; version_id >= OriginalVersionId; version_id--) { if (versions.ContainsKey (version_id)) { DefaultVersionId = version_id; break; } } } private void DeleteEmptyDirectory (GLib.File directory) { // if the directory we're dealing with is not in the // F-Spot photos directory, don't delete anything, // even if it is empty string photo_uri = SafeUri.UriToFilename (Global.PhotoUri.ToString ()); bool path_matched = directory.Path.IndexOf (photo_uri) > -1; if (directory.Path.Equals (photo_uri) || !path_matched) return; if (DirectoryIsEmpty (directory)) { try { Log.DebugFormat ("Removing empty directory: {0}", directory.Path); directory.Delete (); } catch (GLib.GException e) { // silently log the exception, but don't re-throw it // as to not annoy the user Log.Exception (e); } // check to see if the parent is empty DeleteEmptyDirectory (directory.Parent); } } private bool DirectoryIsEmpty (GLib.File directory) { uint count = 0; GLib.FileEnumerator list = directory.EnumerateChildren ("standard::name", GLib.FileQueryInfoFlags.None, null); foreach (var item in list) { count++; } return count == 0; } public uint CreateVersion (string name, uint base_version_id, bool create) { return CreateVersion (name, null, base_version_id, create, false); } private uint CreateVersion (string name, string extension, uint base_version_id, bool create) { return CreateVersion (name, extension, base_version_id, create, false); } private uint CreateVersion (string name, string extension, uint base_version_id, bool create, bool is_protected) { extension = extension ?? VersionUri (base_version_id).GetExtension (); SafeUri new_base_uri = DefaultVersion.BaseUri; string filename = GetFilenameForVersionName (name, extension); SafeUri original_uri = VersionUri (base_version_id); SafeUri new_uri = new_base_uri.Append (filename); string import_md5 = DefaultVersion.ImportMD5; if (VersionNameExists (name)) throw new Exception ("This version name already exists"); if (create) { GLib.File destination = GLib.FileFactory.NewForUri (new_uri); if (destination.Exists) throw new Exception (String.Format ("An object at this uri {0} already exists", new_uri)); //FIXME. or better, fix the copy api ! GLib.File source = GLib.FileFactory.NewForUri (original_uri); source.Copy (destination, GLib.FileCopyFlags.None, null, null); } highest_version_id ++; versions [highest_version_id] = new PhotoVersion (this, highest_version_id, new_base_uri, filename, import_md5, name, is_protected); changes.AddVersion (highest_version_id); return highest_version_id; } public uint CreateReparentedVersion (PhotoVersion version) { return CreateReparentedVersion (version, false); } public uint CreateReparentedVersion (PhotoVersion version, bool is_protected) { // Try to derive version name from its filename string filename = Uri.UnescapeDataString (Path.GetFileNameWithoutExtension (version.Uri.AbsolutePath)); string parent_filename = Path.GetFileNameWithoutExtension (Name); string name = null; if (filename.StartsWith (parent_filename)) name = filename.Substring (parent_filename.Length).Replace ("(", "").Replace (")", "").Replace ("_", " "). Trim (); if (String.IsNullOrEmpty (name)) { // Note for translators: Reparented is a picture becoming a version of another one string rep = name = Catalog.GetString ("Reparented"); for (int num = 1; VersionNameExists (name); num++) { name = String.Format (rep + " ({0})", num); } } highest_version_id ++; versions [highest_version_id] = new PhotoVersion (this, highest_version_id, version.BaseUri, version.Filename, version.ImportMD5, name, is_protected); changes.AddVersion (highest_version_id); return highest_version_id; } public uint CreateDefaultModifiedVersion (uint base_version_id, bool create_file) { int num = 1; while (true) { string name = Catalog.GetPluralString ("Modified", "Modified ({0})", num); name = String.Format (name, num); //SafeUri uri = GetUriForVersionName (name, System.IO.Path.GetExtension (VersionUri(base_version_id).GetFilename())); string filename = GetFilenameForVersionName (name, System.IO.Path.GetExtension (versions [base_version_id].Filename)); SafeUri uri = DefaultVersion.BaseUri.Append (filename); GLib.File file = GLib.FileFactory.NewForUri (uri); if (! VersionNameExists (name) && ! file.Exists) return CreateVersion (name, base_version_id, create_file); num ++; } } public uint CreateNamedVersion (string name, string extension, uint base_version_id, bool create_file) { int num = 1; string final_name; while (true) { final_name = String.Format ( (num == 1) ? Catalog.GetString ("Modified in {1}") : Catalog.GetString ("Modified in {1} ({0})"), num, name); string filename = GetFilenameForVersionName (name, System.IO.Path.GetExtension (versions [base_version_id].Filename)); SafeUri uri = DefaultVersion.BaseUri.Append (filename); GLib.File file = GLib.FileFactory.NewForUri (uri); if (! VersionNameExists (final_name) && ! file.Exists) return CreateVersion (final_name, extension, base_version_id, create_file); num ++; } } public void RenameVersion (uint version_id, string new_name) { if (version_id == OriginalVersionId) throw new Exception ("Cannot rename original version"); if (VersionNameExists (new_name)) throw new Exception ("This name already exists"); GetVersion (version_id).Name = new_name; changes.ChangeVersion (version_id); //TODO: rename file too ??? // if (System.IO.File.Exists (new_path)) // throw new Exception ("File with this name already exists"); // // File.Move (old_path, new_path); // PhotoStore.MoveThumbnail (old_path, new_path); } public void CopyAttributesFrom (Photo that) { Time = that.Time; Description = that.Description; Rating = that.Rating; AddTag (that.Tags); } #endregion #region Tag management // This doesn't check if the tag is already there, use with caution. public void AddTagUnsafely (Tag tag) { tags.Add (tag); changes.AddTag (tag); } // This on the other hand does, but is O(n) with n being the number of existing tags. public void AddTag (Tag tag) { if (!tags.Contains (tag)) AddTagUnsafely (tag); } public void AddTag (IEnumerable<Tag> taglist) { /* * FIXME need a better naming convention here, perhaps just * plain Add. * * tags.AddRange (taglist); * but, AddTag calls AddTagUnsafely which * adds and calls changes.AddTag on each tag? * Need to investigate that. */ foreach (Tag tag in taglist) { AddTag (tag); } } public void RemoveTag (Tag tag) { if (!tags.Contains (tag)) return; tags.Remove (tag); changes.RemoveTag (tag); } public void RemoveTag (Tag []taglist) { foreach (Tag tag in taglist) { RemoveTag (tag); } } public void RemoveCategory (IList<Tag> taglist) { foreach (Tag tag in taglist) { Category cat = tag as Category; if (cat != null) RemoveCategory (cat.Children); RemoveTag (tag); } } // FIXME: This should be removed (I think) public bool HasTag (Tag tag) { return tags.Contains (tag); } private static IDictionary<SafeUri, string> md5_cache = new Dictionary<SafeUri, string> (); public static void ResetMD5Cache () { if (md5_cache != null) md5_cache.Clear (); } #endregion #region Constructor public Photo (uint id, long unix_time) : base (id) { time = DateTimeUtil.ToDateTime (unix_time); tags = new List<Tag> (); description = String.Empty; rating = 0; } #endregion #region IComparable implementation public int CompareTo (object obj) { if (GetType () == obj.GetType ()) return this.Compare((Photo)obj); if (obj is DateTime) return time.CompareTo ((DateTime)obj); throw new Exception ("Object must be of type Photo"); } public int CompareTo (Photo photo) { int result = Id.CompareTo (photo.Id); if (result == 0) return 0; return this.Compare (photo); } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- singleton TSShapeConstructor(SoldierDAE) { baseShape = "./soldier_rigged.DAE"; loadLights = "0"; unit = "1.0"; upAxis = "DEFAULT"; lodType = "TrailingNumber"; ignoreNodeScale = "0"; adjustCenter = "0"; adjustFloor = "0"; forceUpdateMaterials = "0"; }; function SoldierDAE::onLoad(%this) { %this.addSequence("./Anims/PlayerAnim_Lurker_Back.dae Back", "Back", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Celebrate_01.dae Celebrate_01", "Celebrate_01", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Crouch_Backward.dae Crouch_Backward", "Crouch_Backward", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Crouch_Forward.dae Crouch_Forward", "Crouch_Forward", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Crouch_Side.dae Crouch_Side", "Crouch_Side", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Crouch_Root.dae Crouch_Root", "Crouch_Root", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Death1.dae Death1", "Death1", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Death2.dae Death2", "Death2", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Fall.dae Fall", "Fall", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Head.dae Head", "Head", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Jump.dae Jump", "Jump", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Land.dae Land", "Land", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Look.dae Look", "Look", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Reload.dae Reload", "Reload", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Root.dae Root", "Root", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Run.dae Run", "Run", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Side.dae Side", "Side", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Sitting.dae Sitting", "Sitting", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Swim_Backward.dae Swim_Backward", "Swim_Backward", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Swim_Forward.dae Swim_Forward", "Swim_Forward", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Swim_Root.dae Swim_Root", "Swim_Root", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Swim_Left.dae Swim_Left", "Swim_Left", "0", "-1", "1", "0"); %this.addSequence("./Anims/PlayerAnim_Lurker_Swim_Right.dae Swim_Right", "Swim_Right", "0", "-1", "1", "0"); %this.setSequenceBlend("Head", "1", "Root", "0"); %this.setSequenceBlend("Look", "1", "Root", "0"); %this.setSequenceBlend("Reload", "1", "Root", "0"); %this.setSequenceGroundSpeed("Back", "0 -3.6 0", "0 0 0"); %this.setSequenceGroundSpeed("Run", "0 5 0", "0 0 0"); %this.setSequenceGroundSpeed("Side", "-3.6 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Swim_Backward", "0 -1 0", "0 0 0"); %this.setSequenceGroundSpeed("Swim_Forward", "0 1 0", "0 0 0"); %this.setSequenceGroundSpeed("Swim_Left", "-1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Swim_Right", "1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Crouch_Backward", "0 -2 0", "0 0 0"); %this.setSequenceGroundSpeed("Crouch_Forward", "0 2 0", "0 0 0"); %this.setSequenceGroundSpeed("Crouch_Side", "1 0 0", "0 0 0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Back.dae Back", "Pistol_Back", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Crouch_Backward.dae Crouch_Backward", "Pistol_Crouch_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Crouch_Forward.dae Crouch_Forward", "Pistol_Crouch_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Crouch_Side.dae Crouch_Side", "Pistol_Crouch_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Crouch_Root.dae Crouch_Root", "Pistol_Crouch_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Death1.dae Death1", "Pistol_Death1", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Death2.dae Death2", "Pistol_Death2", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Fall.dae Fall", "Pistol_Fall", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Head.dae Head", "Pistol_Head", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Jump.dae Jump", "Pistol_Jump", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Land.dae Land", "Pistol_Land", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Look.dae Look", "Pistol_Look", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Reload.dae Reload", "Pistol_Reload", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Root.dae Root", "Pistol_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Run.dae Run", "Pistol_Run", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Side.dae Side", "Pistol_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Sitting.dae Sitting", "Pistol_Sitting", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Swim_Backward.dae Swim_Backward", "Pistol_Swim_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Swim_Forward.dae Swim_Forward", "Pistol_Swim_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Swim_Root.dae Swim_Root", "Pistol_Swim_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Swim_Left.dae Swim_Left", "Pistol_Swim_Left", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Swim_Right.dae Swim_Right", "Pistol_Swim_Right", "0", "-1", "1", "0"); %this.setSequenceCyclic("Pistol_Fall", "1"); %this.setSequenceCyclic("Pistol_Sitting", "1"); %this.setSequenceBlend("Pistol_Head", "1", "Pistol_Root", "0"); %this.setSequenceBlend("Pistol_Look", "1", "Pistol_Root", "0"); %this.setSequenceBlend("Pistol_Reload", "1", "Pistol_Root", "0"); %this.setSequenceGroundSpeed("Pistol_Back", "0 -3.6 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Run", "0 5 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Side", "3.6 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Swim_Backward", "0 -1 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Swim_Forward", "0 1 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Swim_Left", "-1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Swim_Right", "1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Crouch_Backward", "0 -2 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Crouch_Forward", "0 2 0", "0 0 0"); %this.setSequenceGroundSpeed("Pistol_Crouch_Side", "1 0 0", "0 0 0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Back.dae Back", "ProxMine_Back", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Crouch_Backward.dae Crouch_Backward", "ProxMine_Crouch_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Crouch_Forward.dae Crouch_Forward", "ProxMine_Crouch_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Crouch_Side.dae Crouch_Side", "ProxMine_Crouch_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Crouch_Root.dae Crouch_Root", "ProxMine_Crouch_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Death1.dae Death1", "ProxMine_Death1", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Death2.dae Death2", "ProxMine_Death2", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Fall.dae Fall", "ProxMine_Fall", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Head.dae Head", "ProxMine_Head", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Jump.dae Jump", "ProxMine_Jump", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Land.dae Land", "ProxMine_Land", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Look.dae Look", "ProxMine_Look", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Reload.dae Reload", "ProxMine_Reload", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Fire.dae Fire", "ProxMine_Fire", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Fire_Release.dae Fire_Release", "ProxMine_Fire_Release", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Root.dae Root", "ProxMine_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Run.dae Run", "ProxMine_Run", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Side.dae Side", "ProxMine_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Sitting.dae Sitting", "ProxMine_Sitting", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Swim_Backward.dae Swim_Backward", "ProxMine_Swim_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Swim_Forward.dae Swim_Forward", "ProxMine_Swim_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Swim_Root.dae Swim_Root", "ProxMine_Swim_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Swim_Left.dae Swim_Left", "ProxMine_Swim_Left", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/ProxMine/PlayerAnims/PlayerAnim_ProxMine_Swim_Right.dae Swim_Right", "ProxMine_Swim_Right", "0", "-1", "1", "0"); %this.setSequenceCyclic("ProxMine_Fall", "1"); %this.setSequenceBlend("ProxMine_Head", "1", "ProxMine_Root", "0"); %this.setSequenceBlend("ProxMine_Look", "1", "ProxMine_Root", "0"); %this.setSequenceBlend("ProxMine_Reload", "1", "ProxMine_Root", "0"); %this.setSequenceBlend("ProxMine_Fire", "1", "ProxMine_Root", "0"); %this.setSequenceBlend("ProxMine_Fire_Release", "1", "ProxMine_Root", "0"); %this.setSequenceGroundSpeed("ProxMine_Back", "0 -3.6 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Run", "0 5 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Side", "3.6 0 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Swim_Backward", "0 -1 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Swim_Forward", "0 1 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Swim_Left", "-1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Swim_Right", "1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Crouch_Backward", "0 -2 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Crouch_Forward", "0 2 0", "0 0 0"); %this.setSequenceGroundSpeed("ProxMine_Crouch_Side", "1 0 0", "0 0 0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Back.dae Back", "Turret_Back", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Crouch_Root.dae Crouch_Root", "Turret_Crouch_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Crouch_Backward.dae Crouch_Backward", "Turret_Crouch_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Crouch_Forward.dae Crouch_Forward", "Turret_Crouch_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Crouch_Side.dae Crouch_Side", "Turret_Crouch_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Death1.dae Death1", "Turret_Death1", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Death2.dae Death2", "Turret_Death2", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Fall.dae Fall", "Turret_Fall", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Run.dae Run", "Turret_Run", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Jump.dae Jump", "Turret_Jump", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Land.dae Land", "Turret_Land", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Look.dae Look", "Turret_Look", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Head.dae Head", "Turret_Head", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Recoil.dae Recoil", "Turret_Recoil", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Fire_Release.dae Fire_Release", "Turret_Fire_Release", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Root.dae Root", "Turret_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Side.dae Side", "Turret_Side", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Sitting.dae Sitting", "Turret_Sitting", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Swim_Backward.dae Swim_Backward", "Turret_Swim_Backward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Swim_Forward.dae Swim_Forward", "Turret_Swim_Forward", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Swim_Root.dae Swim_Root", "Turret_Swim_Root", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Swim_Left.dae Swim_Left", "Turret_Swim_Left", "0", "-1", "1", "0"); %this.addSequence("data/FPSGameplay/art/shapes/weapons/Turret/PlayerAnims/PlayerAnim_Turret_Swim_Right.dae Swim_Right", "Turret_Swim_Right", "0", "-1", "1", "0"); %this.setSequenceBlend("Turret_Head", "1", "Turret_Root", "0"); %this.setSequenceBlend("Turret_Look", "1", "Turret_Root", "0"); %this.setSequenceBlend("Turret_Recoil", "1", "Turret_Root", "0"); %this.setSequenceBlend("Turret_Fire_Release", "1", "Turret_Root", "0"); %this.setSequenceGroundSpeed("Turret_Back", "0 -3.6 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Run", "0 5 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Side", "3.6 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Swim_Backward", "0 -1 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Swim_Forward", "0 1 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Swim_Left", "-1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Swim_Right", "1 0 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Crouch_Backward", "0 -2 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Crouch_Forward", "0 2 0", "0 0 0"); %this.setSequenceGroundSpeed("Turret_Crouch_Side", "1 0 0", "0 0 0"); %this.addTrigger("Back", "4", "1"); %this.addTrigger("Back", "13", "2"); %this.addTrigger("jump", "6", "1"); %this.addTrigger("Land", "5", "1"); %this.addTrigger("Run", "8", "1"); %this.addTrigger("Run", "16", "2"); %this.addTrigger("Pistol_Back", "6", "1"); %this.addTrigger("Pistol_Back", "12", "2"); %this.addTrigger("Crouch_Backward", "8", "1"); %this.addTrigger("Crouch_Backward", "19", "2"); %this.addTrigger("Crouch_Forward", "12", "1"); %this.addTrigger("Crouch_Forward", "24", "2"); %this.addTrigger("Crouch_Side", "16", "1"); %this.addTrigger("Crouch_Side", "23", "2"); %this.addTrigger("Side", "7", "1"); %this.addTrigger("Side", "17", "2"); %this.addTrigger("Pistol_Crouch_Backward", "10", "1"); %this.addTrigger("Pistol_Crouch_Backward", "24", "2"); %this.addTrigger("Pistol_Crouch_Forward", "9", "1"); %this.addTrigger("Pistol_Crouch_Forward", "25", "2"); %this.addTrigger("Pistol_Crouch_Side", "8", "1"); %this.addTrigger("Pistol_Crouch_Side", "23", "2"); %this.addTrigger("Pistol_Jump", "5", "1"); %this.addTrigger("Pistol_Land", "9", "1"); %this.addTrigger("Pistol_Run", "8", "1"); %this.addTrigger("Pistol_Run", "16", "2"); %this.addTrigger("Pistol_Side", "8", "1"); %this.addTrigger("Pistol_Side", "17", "2"); %this.addTrigger("ProxMine_Back", "3", "1"); %this.addTrigger("ProxMine_Back", "12", "2"); %this.addTrigger("ProxMine_Crouch_Backward", "9", "1"); %this.addTrigger("ProxMine_Crouch_Backward", "18", "2"); %this.addTrigger("ProxMine_Crouch_Forward", "12", "1"); %this.addTrigger("ProxMine_Crouch_Forward", "25", "2"); %this.addTrigger("ProxMine_Crouch_Side", "12", "1"); %this.addTrigger("ProxMine_Crouch_Side", "27", "2"); %this.addTrigger("ProxMine_Fall", "15", "1"); %this.addTrigger("ProxMine_Jump", "5", "1"); %this.addTrigger("ProxMine_Land", "7", "1"); %this.addTrigger("ProxMine_Run", "8", "1"); %this.addTrigger("ProxMine_Run", "17", "2"); %this.addTrigger("ProxMine_Side", "7", "1"); %this.addTrigger("ProxMine_Side", "18", "2"); %this.addTrigger("Turret_Back", "4", "1"); %this.addTrigger("Turret_Back", "11", "2"); %this.addTrigger("Turret_Crouch_Backward", "8", "1"); %this.addTrigger("Turret_Crouch_Backward", "26", "2"); %this.addTrigger("Turret_Crouch_Forward", "12", "1"); %this.addTrigger("Turret_Crouch_Forward", "24", "2"); %this.addTrigger("Turret_Crouch_Side", "13", "1"); %this.addTrigger("Turret_Crouch_Side", "24", "2"); %this.addTrigger("Turret_Run", "7", "1"); %this.addTrigger("Turret_Run", "17", "2"); %this.addTrigger("Turret_Jump", "6", "1"); %this.addTrigger("Turret_Land", "3", "1"); %this.addTrigger("Turret_Side", "9", "1"); %this.addTrigger("Turret_Side", "17", "2"); }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V10.Common; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Resources; using Google.Ads.GoogleAds.V10.Services; using Google.Api.Gax; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using static Google.Ads.GoogleAds.V10.Enums.CustomerMatchUploadKeyTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.OfflineUserDataJobTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This code example uses Customer Match to create a new user list (a.k.a. audience) and adds /// users to it. /// /// Note: It may take up to several hours for the list to be populated with users. /// Email addresses must be associated with a Google account. /// For privacy purposes, the user list size will show as zero until the list has /// at least 1,000 users. After that, the size will be rounded to the two most /// significant digits. /// </summary> public class AddCustomerMatchUserList : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddCustomerMatchUserList"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the user list is added. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the user list is added.")] public long CustomerId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID for which the user list is added. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); return 0; }); AddCustomerMatchUserList codeExample = new AddCustomerMatchUserList(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } private const int POLL_FREQUENCY_SECONDS = 1; private const int MAX_TOTAL_POLL_INTERVAL_SECONDS = 60; private static SHA256 digest = SHA256.Create(); /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example uses Customer Match to create a new user list (a.k.a. audience) " + "and adds users to it. \nNote: It may take up to several hours for the list to be " + "populated with users. Email addresses must be associated with a Google account. For " + "privacy purposes, the user list size will show as zero until the list has at least " + "1,000 users. After that, the size will be rounded to the two most significant digits."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the user list is added. /// </param> public void Run(GoogleAdsClient client, long customerId) { try { string userListResourceName = CreateCustomerMatchUserList(client, customerId); AddUsersToCustomerMatchUserList(client, customerId, userListResourceName); PrintCustomerMatchUserListInfo(client, customerId, userListResourceName); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates the customer match user list. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the user list is added. /// </param> /// <returns>The resource name of the newly created user list</returns> private string CreateCustomerMatchUserList(GoogleAdsClient client, long customerId) { // Get the UserListService. UserListServiceClient service = client.GetService(Services.V10.UserListService); // Creates the user list. UserList userList = new UserList() { Name = $"Customer Match list# {ExampleUtilities.GetShortRandomString()}", Description = "A list of customers that originated from email and physical" + " addresses", // Customer Match user lists can use a membership life span of 10000 to // indicate unlimited; otherwise normal values apply. // Sets the membership life span to 30 days. MembershipLifeSpan = 30, CrmBasedUserList = new CrmBasedUserListInfo() { UploadKeyType = CustomerMatchUploadKeyType.ContactInfo } }; // Creates the user list operation. UserListOperation operation = new UserListOperation() { Create = userList }; // Issues a mutate request to add the user list and prints some information. MutateUserListsResponse response = service.MutateUserLists( customerId.ToString(), new[] { operation }); string userListResourceName = response.Results[0].ResourceName; Console.WriteLine($"User list with resource name '{userListResourceName}' " + $"was created."); return userListResourceName; } /// <summary> /// Creates and executes an asynchronous job to add users to the Customer Match user list. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which calls are made. /// </param> /// <param name="userListResourceName">the resource name of the Customer Match user list /// to add users to</param> // [START add_customer_match_user_list] private static void AddUsersToCustomerMatchUserList(GoogleAdsClient client, long customerId, string userListResourceName) { // Get the OfflineUserDataJobService. OfflineUserDataJobServiceClient service = client.GetService( Services.V10.OfflineUserDataJobService); // Creates a new offline user data job. OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob() { Type = OfflineUserDataJobType.CustomerMatchUserList, CustomerMatchUserListMetadata = new CustomerMatchUserListMetadata() { UserList = userListResourceName } }; // Issues a request to create the offline user data job. CreateOfflineUserDataJobResponse response1 = service.CreateOfflineUserDataJob( customerId.ToString(), offlineUserDataJob); string offlineUserDataJobResourceName = response1.ResourceName; Console.WriteLine($"Created an offline user data job with resource name: " + $"'{offlineUserDataJobResourceName}'."); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest() { ResourceName = offlineUserDataJobResourceName, Operations = { BuildOfflineUserDataJobOperations() }, EnablePartialFailure = true, }; // Issues a request to add the operations to the offline user data job. AddOfflineUserDataJobOperationsResponse response2 = service.AddOfflineUserDataJobOperations(request); // Prints the status message if any partial failure error is returned. // Note: The details of each partial failure error are not printed here, // you can refer to the example HandlePartialFailure.cs to learn more. if (response2.PartialFailureError != null) { // Extracts the partial failure from the response status. GoogleAdsFailure partialFailure = response2.PartialFailure; Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " + $"occurred"); } Console.WriteLine("The operations are added to the offline user data job."); // Issues an asynchronous request to run the offline user data job for executing // all added operations. Operation<Empty, OfflineUserDataJobMetadata> operationResponse = service.RunOfflineUserDataJob(offlineUserDataJobResourceName); Console.WriteLine("Asynchronous request to execute the added operations started."); ; Console.WriteLine("Waiting until operation completes."); // PollUntilCompleted() implements a default back-off policy for retrying. You can // tweak the polling behaviour using a PollSettings as illustrated below. operationResponse.PollUntilCompleted(new PollSettings( Expiration.FromTimeout(TimeSpan.FromSeconds(MAX_TOTAL_POLL_INTERVAL_SECONDS)), TimeSpan.FromSeconds(POLL_FREQUENCY_SECONDS))); if (operationResponse.IsCompleted) { Console.WriteLine($"Offline user data job with resource name " + $"'{offlineUserDataJobResourceName}' has finished."); } else { Console.WriteLine($"Offline user data job with resource name" + $" '{offlineUserDataJobResourceName}' is pending after " + $"{MAX_TOTAL_POLL_INTERVAL_SECONDS} seconds."); } } // [END add_customer_match_user_list] /// <summary> /// Builds and returns offline user data job operations to add one user identified by an /// email address and one user identified based on a physical address. /// </summary> /// <returns>An array with the operations</returns> private static OfflineUserDataJobOperation[] BuildOfflineUserDataJobOperations() { // [START add_customer_match_user_list_2] // Creates a first user data based on an email address. UserData userDataWithEmailAddress = new UserData() { UserIdentifiers = { new UserIdentifier() { // Hash normalized email addresses based on SHA-256 hashing algorithm. HashedEmail = NormalizeAndHash("customer@example.com") } } }; // Creates a second user data based on a physical address. UserData userDataWithPhysicalAddress = new UserData() { UserIdentifiers = { new UserIdentifier() { AddressInfo = new OfflineUserAddressInfo() { // First and last name must be normalized and hashed. HashedFirstName = NormalizeAndHash("John"), HashedLastName = NormalizeAndHash("Doe"), // Country code and zip code are sent in plain text. CountryCode = "US", PostalCode = "10011" } } } }; // [END add_customer_match_user_list_2] // Creates the operations to add the two users. return new OfflineUserDataJobOperation[] { new OfflineUserDataJobOperation() { Create = userDataWithEmailAddress }, new OfflineUserDataJobOperation() { Create = userDataWithPhysicalAddress } }; } /// <summary> /// Prints information about the Customer Match user list. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which calls are made. /// </param> /// <param name="userListResourceName">The resource name of the Customer Match user list /// to print information about.</param> private void PrintCustomerMatchUserListInfo(GoogleAdsClient client, long customerId, string userListResourceName) { // Get the GoogleAdsService. GoogleAdsServiceClient service = client.GetService(Services.V10.GoogleAdsService); // Creates a query that retrieves the user list. string query = "SELECT user_list.size_for_display, user_list.size_for_search " + "FROM user_list " + $"WHERE user_list.resource_name = '{userListResourceName}'"; // Issues a search stream request. service.SearchStream(customerId.ToString(), query, delegate (SearchGoogleAdsStreamResponse resp) { // Display the results. foreach (GoogleAdsRow userListRow in resp.Results) { UserList userList = userListRow.UserList; Console.WriteLine("The estimated number of users that the user list " + $"'{userList.ResourceName}' has is {userList.SizeForDisplay}" + $" for Display and {userList.SizeForSearch} for Search."); } } ); Console.WriteLine("Reminder: It may take several hours for the user list to be " + "populated with the users so getting zeros for the estimations is expected."); } /// <summary> /// Normalizes and hashes a string value. /// </summary> /// <param name="value">The value to normalize and hash.</param> /// <returns>The normalized and hashed value.</returns> private static string NormalizeAndHash(string value) { return ToSha256String(digest, ToNormalizedValue(value)); } /// <summary> /// Hash a string value using SHA-256 hashing algorithm. /// </summary> /// <param name="digest">Provides the algorithm for SHA-256.</param> /// <param name="value">The string value (e.g. an email address) to hash.</param> /// <returns>The hashed value.</returns> private static string ToSha256String(SHA256 digest, string value) { byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value)); // Convert the byte array into an unhyphenated hexadecimal string. return BitConverter.ToString(digestBytes).Replace("-", string.Empty); } /// <summary> /// Removes leading and trailing whitespace and converts all characters to /// lower case. /// </summary> /// <param name="value">The value to normalize.</param> /// <returns>The normalized value.</returns> private static string ToNormalizedValue(string value) { return value.Trim().ToLower(); } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Raksha.Crypto; using Raksha.Crypto.Parameters; using Raksha.Crypto.IO; using Raksha.Security; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Misc { /// <remarks> /// Basic test class for key generation for a DES-EDE block cipher, basically /// this just exercises the provider, and makes sure we are behaving sensibly, /// correctness of the implementation is shown in the lightweight test classes. /// </remarks> [TestFixture] public class DesEdeTest : SimpleTest { private static string[] cipherTests1 = { "112", "2f4bc6b30c893fa549d82c560d61cf3eb088aed020603de249d82c560d61cf3e529e95ecd8e05394", "128", "2f4bc6b30c893fa549d82c560d61cf3eb088aed020603de249d82c560d61cf3e529e95ecd8e05394", "168", "50ddb583a25c21e6c9233f8e57a86d40bb034af421c03096c9233f8e57a86d402fce91e8eb639f89", "192", "50ddb583a25c21e6c9233f8e57a86d40bb034af421c03096c9233f8e57a86d402fce91e8eb639f89", }; private static byte[] input1 = Hex.Decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); /** * a fake random number generator - we just want to make sure the random numbers * aren't random so that we get the same output, while still getting to test the * key generation facilities. */ private class FixedSecureRandom : SecureRandom { private byte[] seed = { (byte)0xaa, (byte)0xfd, (byte)0x12, (byte)0xf6, (byte)0x59, (byte)0xca, (byte)0xe6, (byte)0x34, (byte)0x89, (byte)0xb4, (byte)0x79, (byte)0xe5, (byte)0x07, (byte)0x6d, (byte)0xde, (byte)0xc2, (byte)0xf0, (byte)0x6c, (byte)0xb5, (byte)0x8f }; public override void NextBytes( byte[] bytes) { int offset = 0; while ((offset + seed.Length) < bytes.Length) { Array.Copy(seed, 0, bytes, offset, seed.Length); offset += seed.Length; } Array.Copy(seed, 0, bytes, offset, bytes.Length - offset); } } public override string Name { get { return "DESEDE"; } } private void wrapTest( int id, byte[] kek, byte[] iv, byte[] input, byte[] output) { try { IWrapper wrapper = WrapperUtilities.GetWrapper("DESedeWrap"); KeyParameter desEdeKey = new DesEdeParameters(kek); wrapper.Init(true, new ParametersWithIV(desEdeKey, iv)); try { // byte[] cText = wrapper.Wrap(new SecretKeySpec(input, "DESEDE")); byte[] cText = wrapper.Wrap(input, 0, input.Length); if (!Arrays.AreEqual(cText, output)) { Fail("failed wrap test " + id + " expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(cText)); } } catch (Exception e) { Fail("failed wrap test exception " + e.ToString()); } wrapper.Init(false, desEdeKey); try { // Key pText = wrapper.unwrap(output, "DESede", IBufferedCipher.SECRET_KEY); byte[] pText = wrapper.Unwrap(output, 0, output.Length); // if (!Arrays.AreEqual(pText.getEncoded(), input)) if (!Arrays.AreEqual(pText, input)) { Fail("failed unwrap test " + id + " expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(pText)); } } catch (Exception e) { Fail("failed unwrap test exception " + e.ToString()); } } catch (Exception ex) { Fail("failed exception " + ex.ToString()); } } private void doTest( int strength, byte[] input, byte[] output) { KeyParameter key = null; CipherKeyGenerator keyGen; SecureRandom rand; IBufferedCipher inCipher = null; IBufferedCipher outCipher = null; CipherStream cIn; CipherStream cOut; MemoryStream bIn; MemoryStream bOut; rand = new FixedSecureRandom(); try { keyGen = GeneratorUtilities.GetKeyGenerator("DESEDE"); keyGen.Init(new KeyGenerationParameters(rand, strength)); key = new DesEdeParameters(keyGen.GenerateKey()); inCipher = CipherUtilities.GetCipher("DESEDE/ECB/PKCS7Padding"); outCipher = CipherUtilities.GetCipher("DESEDE/ECB/PKCS7Padding"); outCipher.Init(true, new ParametersWithRandom(key, rand)); } catch (Exception e) { Fail("DESEDE failed initialisation - " + e.ToString()); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("DESEDE failed initialisation - " + e.ToString()); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail("DESEDE failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { Fail("DESEDE failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { // DataInputStream dIn = new DataInputStream(cIn); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = (byte)dIn.ReadByte(); } // dIn.readFully(bytes, input.Length / 2, bytes.Length - input.Length / 2); int remaining = bytes.Length - input.Length / 2; byte[] rest = dIn.ReadBytes(remaining); if (rest.Length != remaining) throw new Exception("IO problem with BinaryReader"); rest.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail("DESEDE failed encryption - " + e.ToString()); } if (!Arrays.AreEqual(bytes, input)) { Fail("DESEDE failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } // TODO Put back in // // // // keyspec test // // // try // { // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); // DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class); // // if (!equalArray(key.getEncoded(), keySpec.getKey(), 16)) // { // Fail("DESEDE KeySpec does not match key."); // } // } // catch (Exception e) // { // Fail("DESEDE failed keyspec - " + e.ToString()); // } } public override void PerformTest() { for (int i = 0; i != cipherTests1.Length; i += 2) { doTest(int.Parse(cipherTests1[i]), input1, Hex.Decode(cipherTests1[i + 1])); } byte[] kek1 = Hex.Decode("255e0d1c07b646dfb3134cc843ba8aa71f025b7c0838251f"); byte[] iv1 = Hex.Decode("5dd4cbfc96f5453b"); byte[] in1 = Hex.Decode("2923bf85e06dd6ae529149f1f1bae9eab3a7da3d860d3e98"); byte[] out1 = Hex.Decode("690107618ef092b3b48ca1796b234ae9fa33ebb4159604037db5d6a84eb3aac2768c632775a467d4"); wrapTest(1, kek1, iv1, in1, out1); } public static void Main( string[] args) { RunTest(new DesEdeTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.Collections.Generic; using System.IO; namespace gpcc { public class CodeGenerator { public Grammar grammar; private TextWriter output; public TextWriter Output { get { return this.output; } set { this.output = value; } } public CodeGenerator(TextWriter output) { this.output = output; } public void Generate(List<State> states, Grammar grammar) { this.grammar = grammar; //this.GenerateCopyright(); this.GenerateUsingHeader(); this.output.WriteLine(grammar.headerCode); if (grammar.Namespace != null) { this.output.WriteLine("namespace {0}", grammar.Namespace); this.output.WriteLine("{"); } this.GenerateTokens(grammar.terminals); this.GenerateClassHeader(grammar.ParserName); this.InsertCode(grammar.prologCode); this.GenerateInitializeMethod(grammar.ParserName, states, grammar.productions, grammar.nonTerminals); this.GenerateActionMethod(grammar.productions); this.GenerateToStringMethod(); this.InsertCode(grammar.epilogCode); this.GenerateClassFooter(); if (grammar.Namespace != null) { this.output.WriteLine("}"); } } private void GenerateCopyright() { this.output.WriteLine("// This code was generated by the Gardens Point Parser Generator"); this.output.WriteLine("// Copyright (c) Wayne Kelly, QUT 2005"); this.output.WriteLine("// Copyright (c) DEVSENSE, 2012"); this.output.WriteLine(); this.output.WriteLine(); } private void GenerateUsingHeader() { this.output.WriteLine("using System;"); this.output.WriteLine("using System.Text;"); this.output.WriteLine("using System.Collections.Generic;"); this.output.WriteLine(); } private void GenerateTokens(Dictionary<string, Terminal> terminals) { this.output.Write("{0} enum {1} {{\n", this.grammar.Visibility, this.grammar.TokenName); bool flag = true; foreach (Terminal current in terminals.Values) { if (current.symbolic) { if (!flag) { this.output.WriteLine(","); } if (string.IsNullOrEmpty(current.Comment)) this.output.Write("{0}={1}", current.ToString(), current.num); else { this.output.WriteLine("/// <summary>{0}</summary>", System.Web.HttpUtility.HtmlEncode(current.Comment)); this.output.Write("{0}={1}", current.ToString(), current.num); } flag = false; } } this.output.WriteLine("\n};"); this.output.WriteLine(); } private string GenerateValueType() { if (this.grammar.unionType != null) { this.output.WriteLine("{0}\n{1} partial struct {2}", string.IsNullOrEmpty(this.grammar.ValueTypeAttributes) ? "" : string.Format("[{0}]", this.grammar.ValueTypeAttributes), this.grammar.Visibility, this.grammar.ValueTypeName); this.InsertCode(this.grammar.unionType); return this.grammar.ValueTypeName; } return "int"; } private void GenerateClassHeader(string name) { string text = this.GenerateValueType(); this.output.WriteLine("{0}\n{1} partial class {2}: ShiftReduceParser<{3},{4}>", new object[] { string.IsNullOrEmpty(this.grammar.Attributes)? "": string.Format("[{0}]", this.grammar.Attributes), this.grammar.Visibility, name, text, this.grammar.PositionType }); this.output.WriteLine("{"); } private void GenerateClassFooter() { this.output.WriteLine("}"); } private void GenerateInitializeMethod(string className, List<State> states, List<Production> productions, Dictionary<string, NonTerminal> nonTerminals) { this.output.WriteLine(); this.output.WriteLine(" protected override string[] NonTerminals { get { return nonTerminals; } }"); this.output.WriteLine(" private static string[] nonTerminals;"); this.output.WriteLine(); this.output.WriteLine(" protected override State[] States { get { return states; } }"); this.output.WriteLine(" private static readonly State[] states;"); this.output.WriteLine(); this.output.WriteLine(" protected override Rule[] Rules { get { return rules; } }"); this.output.WriteLine(" private static readonly Rule[] rules;"); this.output.WriteLine(); this.output.WriteLine(); this.output.WriteLine(" #region Construction"); this.output.WriteLine(); this.output.WriteLine(" static {0}()", className); this.output.WriteLine(" {"); this.output.WriteLine(); this.GenerateStates(states); this.output.WriteLine(); this.output.WriteLine(" #region rules"); this.output.WriteLine(" rules = new Rule[]"); this.output.WriteLine(" {"); this.output.WriteLine(" default(Rule),"); // 0th rule foreach (Production current in productions) this.GenerateRule(current); this.output.WriteLine(" };"); this.output.WriteLine(" #endregion"); this.output.WriteLine(); this.output.Write(" nonTerminals = new string[] {\"\", "); int num = 37; foreach (NonTerminal current2 in nonTerminals.Values) { string text = string.Format("\"{0}\", ", current2.ToString()); num += text.Length; this.output.Write(text); if (num > 70) { this.output.WriteLine(); this.output.Write(" "); num = 0; } } this.output.WriteLine("};"); this.output.WriteLine(" }"); this.output.WriteLine(); this.output.WriteLine(" #endregion"); this.output.WriteLine(); } private void GenerateStates(List<State> states) { this.output.WriteLine(" #region states"); this.output.WriteLine(" states = new State[]"); this.output.WriteLine(" {"); for (int i = 0; i < states.Count; i++) { this.output.Write(" new State({0}, ", i); int defaultAction = this.GetDefaultAction(states[i]); if (defaultAction != 0) { this.output.Write(defaultAction); } else { this.output.Write("new int[] {"); bool flag = true; foreach (KeyValuePair<Terminal, ParserAction> current in states[i].parseTable) { if (!flag) { this.output.Write(","); } this.output.Write("{0},{1}", current.Key.num, current.Value.ToNum()); flag = false; } this.output.Write("}"); } if (states[i].nonTerminalTransitions.Count > 0) { this.output.Write(", new int[] {"); bool flag2 = true; foreach (Transition current2 in states[i].nonTerminalTransitions.Values) { if (!flag2) { this.output.Write(","); } this.output.Write("{0},{1}", current2.A.num, current2.next.num); flag2 = false; } this.output.Write("}"); } this.output.WriteLine("),"); } this.output.WriteLine(" };"); this.output.WriteLine(" #endregion"); } private int GetDefaultAction(State state) { IEnumerator<ParserAction> enumerator = state.parseTable.Values.GetEnumerator(); enumerator.MoveNext(); int num = enumerator.Current.ToNum(); if (num > 0) { return 0; } foreach (KeyValuePair<Terminal, ParserAction> current in state.parseTable) { if (current.Value.ToNum() != num) { return 0; } } return num; } private void GenerateRule(Production production) { this.output.Write(" new Rule(" + production.lhs.num + ", new int[]{"); bool flag = true; foreach (Symbol current in production.rhs) { if (!flag) { this.output.Write(","); } else { flag = false; } this.output.Write("{0}", current.num); } this.output.WriteLine("}),"); } private void GenerateActionMethod(List<Production> productions) { this.output.WriteLine(" protected override void DoAction(int action)"); this.output.WriteLine(" {"); this.output.WriteLine(" switch (action)"); this.output.WriteLine(" {"); foreach (Production current in productions) { if (current.semanticAction != null) { this.output.WriteLine(" case {0}: // {1}", current.num, current.ToString()); current.semanticAction.GenerateCode(this); this.output.WriteLine(" return;"); } } this.output.WriteLine(" }"); this.output.WriteLine(" }"); this.output.WriteLine(); } private void GenerateToStringMethod() { this.output.WriteLine(" protected override string TerminalToString(int terminal)"); this.output.WriteLine(" {"); this.output.WriteLine(" if (((Tokens)terminal).ToString() != terminal.ToString())"); this.output.WriteLine(" return ((Tokens)terminal).ToString();"); this.output.WriteLine(" else"); this.output.WriteLine(" return CharToString((char)terminal);"); this.output.WriteLine(" }"); this.output.WriteLine(); } private void InsertCode(string code) { if (code != null) { StringReader stringReader = new StringReader(code); while (true) { string text = stringReader.ReadLine(); if (text == null) { break; } this.output.WriteLine("{0}", text); } return; } } } }
using UnityEngine; using System; public class FSliceSprite : FSprite { private float _insetTop; private float _insetRight; private float _insetBottom; private float _insetLeft; private float _width; private float _height; private int _sliceCount; private Vector2[] _uvVertices; public FSliceSprite (string elementName, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : this(Futile.atlasManager.GetElementWithName(elementName), width, height, insetTop, insetRight, insetBottom, insetLeft) { } public FSliceSprite (FAtlasElement element, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : base() { _width = width; _height = height; _insetTop = insetTop; _insetRight = insetRight; _insetBottom = insetBottom; _insetLeft = insetLeft; Init(FFacetType.Quad, element,0); //this will call HandleElementChanged(), which will call SetupSlices(); _isAlphaDirty = true; UpdateLocalVertices(); } override public void HandleElementChanged() { SetupSlices(); } public void SetupSlices () { _insetTop = Math.Max (0,_insetTop); _insetRight = Math.Max(0,_insetRight); _insetBottom = Math.Max (0,_insetBottom); _insetLeft = Math.Max(0,_insetLeft); _sliceCount = 1; if(_insetTop > 0) _sliceCount++; if(_insetRight > 0) _sliceCount++; if(_insetLeft > 0) _sliceCount++; if(_insetBottom > 0) _sliceCount++; if(_insetTop > 0 && _insetRight > 0) _sliceCount++; if(_insetTop > 0 && _insetLeft > 0) _sliceCount++; if(_insetBottom > 0 && _insetRight > 0) _sliceCount++; if(_insetBottom > 0 && _insetLeft > 0) _sliceCount++; _numberOfFacetsNeeded = _sliceCount; _localVertices = new Vector2[_sliceCount*4]; _uvVertices = new Vector2[_sliceCount*4]; _areLocalVerticesDirty = true; if(_numberOfFacetsNeeded != _sliceCount) { _numberOfFacetsNeeded = _sliceCount; if(_isOnStage) _stage.HandleFacetsChanged(); } UpdateLocalVertices(); } override public void UpdateLocalVertices() { _areLocalVerticesDirty = false; Rect uvRect = element.uvRect; float itop = Math.Max(0,Math.Min(_insetTop, _element.sourceSize.y-_insetBottom)); float iright = Math.Max(0,Math.Min(_insetRight, _element.sourceSize.x-_insetLeft)); float ibottom = Math.Max(0,Math.Min(_insetBottom, _element.sourceSize.y-_insetTop)); float ileft = Math.Max(0,Math.Min(_insetLeft, _element.sourceSize.x-_insetRight)); float uvtop = uvRect.height*(itop/_element.sourceSize.y); float uvleft = uvRect.width*(ileft/_element.sourceSize.x); float uvbottom = uvRect.height*(ibottom/_element.sourceSize.y); float uvright = uvRect.width*(iright/_element.sourceSize.x); _textureRect.x = -_anchorX*_width; _textureRect.y = -_anchorY*_height; _textureRect.width = _width; _textureRect.height = _height; _localRect = _textureRect; float localXMin = _localRect.xMin; float localXMax = _localRect.xMax; float localYMin = _localRect.yMin; float localYMax = _localRect.yMax; float uvXMin = uvRect.xMin; float uvXMax = uvRect.xMax; float uvYMin = uvRect.yMin; float uvYMax = uvRect.yMax; int sliceVertIndex = 0; for(int s = 0; s<9; s++) { if(s == 0) //center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 1 && _insetTop > 0) //top center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMax); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 2 && _insetRight > 0) //right center slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMax,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMax,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMax,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMax,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 3 && _insetBottom > 0) //bottom center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin); sliceVertIndex += 4; } else if (s == 4 && _insetLeft > 0) //left center slice { _localVertices[sliceVertIndex].Set (localXMin,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMin,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMin,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 5 && _insetTop > 0 && _insetLeft > 0) //top left slice { _localVertices[sliceVertIndex].Set (localXMin,localYMax); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMin,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMin,uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 6 && _insetTop > 0 && _insetRight > 0) //top right slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMax); _localVertices[sliceVertIndex+1].Set (localXMax,localYMax); _localVertices[sliceVertIndex+2].Set (localXMax,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMax - uvright, uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 7 && _insetBottom > 0 && _insetRight > 0) //bottom right slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMax,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMax,localYMin); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin); _uvVertices[sliceVertIndex].Set (uvXMax - uvright, uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMin); sliceVertIndex += 4; } else if (s == 8 && _insetBottom > 0 && _insetLeft > 0) //bottom left slice { _localVertices[sliceVertIndex].Set (localXMin,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin); _localVertices[sliceVertIndex+3].Set (localXMin,localYMin); _uvVertices[sliceVertIndex].Set (uvXMin, uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft, uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft, uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMin, uvYMin); sliceVertIndex += 4; } } _isMeshDirty = true; } override public void PopulateRenderLayer() { if(_isOnStage && _firstFacetIndex != -1) { _isMeshDirty = false; for(int s = 0; s<_sliceCount; s++) { int sliceVertIndex = s*4; int vertexIndex0 = (_firstFacetIndex+s)*4; int vertexIndex1 = vertexIndex0 + 1; int vertexIndex2 = vertexIndex0 + 2; int vertexIndex3 = vertexIndex0 + 3; Vector3[] vertices = _renderLayer.vertices; Vector2[] uvs = _renderLayer.uvs; Color[] colors = _renderLayer.colors; _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _localVertices[sliceVertIndex],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex1], _localVertices[sliceVertIndex+1],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex2], _localVertices[sliceVertIndex+2],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex3], _localVertices[sliceVertIndex+3],0); uvs[vertexIndex0] = _uvVertices[sliceVertIndex]; uvs[vertexIndex1] = _uvVertices[sliceVertIndex+1]; uvs[vertexIndex2] = _uvVertices[sliceVertIndex+2]; uvs[vertexIndex3] = _uvVertices[sliceVertIndex+3]; colors[vertexIndex0] = _alphaColor; colors[vertexIndex1] = _alphaColor; colors[vertexIndex2] = _alphaColor; colors[vertexIndex3] = _alphaColor; _renderLayer.HandleVertsChange(); } } } public void SetInsets(float insetTop, float insetRight, float insetBottom, float insetLeft) { _insetTop = insetTop; _insetRight = insetRight; _insetBottom = insetBottom; _insetLeft = insetLeft; SetupSlices(); } override public float width { get { return _width; } set { _width = value; _areLocalVerticesDirty = true; } } override public float height { get { return _height; } set { _height = value; _areLocalVerticesDirty = true; } } }
using System; using System.Collections; using System.Collections.Generic; using Omnius.Base; namespace Omnius.Collections { public class LockedHashSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISynchronized { private HashSet<T> _hashSet; private int? _capacity; private readonly object _lockObject = new object(); public LockedHashSet() { _hashSet = new HashSet<T>(); } public LockedHashSet(int capacity) { _hashSet = new HashSet<T>(); _capacity = capacity; } public LockedHashSet(IEnumerable<T> collection) { _hashSet = new HashSet<T>(collection); } public LockedHashSet(IEqualityComparer<T> comparer) { _hashSet = new HashSet<T>(comparer); } public LockedHashSet(int capacity, IEqualityComparer<T> comparer) { _hashSet = new HashSet<T>(comparer); _capacity = capacity; } public LockedHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer) { _hashSet = new HashSet<T>(collection, comparer); } public T[] ToArray() { lock (this.LockObject) { var array = new T[_hashSet.Count]; _hashSet.CopyTo(array, 0); return array; } } public IEqualityComparer<T> Comparer { get { lock (this.LockObject) { return _hashSet.Comparer; } } } public int Capacity { get { lock (this.LockObject) { return _capacity ?? 0; } } set { lock (this.LockObject) { _capacity = value; } } } public void TrimExcess() { lock (this.LockObject) { _hashSet.TrimExcess(); } } public bool Add(T item) { lock (this.LockObject) { if (_capacity != null && _hashSet.Count + 1 > _capacity.Value) throw new OverflowException(); return _hashSet.Add(item); } } public void ExceptWith(IEnumerable<T> other) { lock (this.LockObject) { _hashSet.ExceptWith(other); } } public void IntersectWith(IEnumerable<T> other) { lock (this.LockObject) { _hashSet.IntersectWith(other); } } public bool IsProperSubsetOf(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.IsProperSubsetOf(other); } } public bool IsProperSupersetOf(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.IsProperSupersetOf(other); } } public bool IsSubsetOf(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.IsSubsetOf(other); } } public bool IsSupersetOf(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.IsSupersetOf(other); } } public bool Overlaps(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.Overlaps(other); } } public bool SetEquals(IEnumerable<T> other) { lock (this.LockObject) { return _hashSet.SetEquals(other); } } public void SymmetricExceptWith(IEnumerable<T> other) { lock (this.LockObject) { _hashSet.SymmetricExceptWith(other); } } public void UnionWith(IEnumerable<T> other) { lock (this.LockObject) { foreach (var item in other) { this.Add(item); } } } public void Clear() { lock (this.LockObject) { _hashSet.Clear(); } } public bool Contains(T item) { lock (this.LockObject) { return _hashSet.Contains(item); } } public void CopyTo(T[] array, int arrayIndex) { lock (this.LockObject) { _hashSet.CopyTo(array, arrayIndex); } } public int Count { get { lock (this.LockObject) { return _hashSet.Count; } } } public bool IsReadOnly { get { lock (this.LockObject) { return false; } } } public bool Remove(T item) { lock (this.LockObject) { return _hashSet.Remove(item); } } void ICollection<T>.Add(T item) { lock (this.LockObject) { this.Add(item); } } bool ICollection.IsSynchronized { get { lock (this.LockObject) { return true; } } } object ICollection.SyncRoot { get { return this.LockObject; } } void ICollection.CopyTo(Array array, int index) { lock (this.LockObject) { ((ICollection)_hashSet).CopyTo(array, index); } } public IEnumerator<T> GetEnumerator() { lock (this.LockObject) { foreach (var item in _hashSet) { yield return item; } } } IEnumerator IEnumerable.GetEnumerator() { lock (this.LockObject) { return this.GetEnumerator(); } } #region IThisLock public object LockObject { get { return _lockObject; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using AM.Collections; using Microsoft.VisualStudio.TestTools.UnitTesting; // ReSharper disable CollectionNeverQueried.Local // ReSharper disable CollectionNeverUpdated.Local // ReSharper disable UseObjectOrCollectionInitializer namespace UnitTests.AM.Collections { [TestClass] public class ChunkListTest { [TestMethod] public void ChunkList_Construction_1() { ChunkList<int> list = new ChunkList<int>(); Assert.AreEqual(0, list.Count); Assert.AreEqual(0, list.Capacity); } [TestMethod] public void ChunkList_Construction_2() { ChunkList<int> list = new ChunkList<int>(1); Assert.AreEqual(0, list.Count); Assert.AreEqual(ChunkList<int>.ChunkSize, list.Capacity); } [TestMethod] public void ChunkList_Construction_3() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(chunkSize); Assert.AreEqual(0, list.Count); Assert.AreEqual(chunkSize, list.Capacity); } [TestMethod] public void ChunkList_Construction_4() { ChunkList<int> list = new ChunkList<int>(1025); Assert.AreEqual(0, list.Count); Assert.AreEqual(1536, list.Capacity); } [TestMethod] public void ChunkList_Add_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); Assert.AreEqual(1, list.Count); Assert.AreEqual(ChunkList<int>.ChunkSize, list.Capacity); } [TestMethod] public void ChunkList_Add_2() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(); int desiredCount = chunkSize + 1; for (int i = 0; i < desiredCount; i++) { list.Add(i); } Assert.AreEqual(desiredCount, list.Count); Assert.AreEqual(chunkSize * 2, list.Capacity); } [TestMethod] public void ChunkList_CopyTo_1() { ChunkList<int> list = new ChunkList<int>(); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(0, array[0]); Assert.AreEqual(0, array[1]); Assert.AreEqual(0, array[2]); } [TestMethod] public void ChunkList_CopyTo_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(1, array[0]); Assert.AreEqual(0, array[1]); Assert.AreEqual(0, array[2]); } [TestMethod] public void ChunkList_CopyTo_3() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); Assert.AreEqual(3, array[2]); } [TestMethod] public void ChunkList_CopyTo_4() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } int[] array = new int[count * 2]; list.CopyTo(array, 0); for (int i = 0; i < count; i++) { Assert.AreEqual(i, array[i]); Assert.AreEqual(0, array[count + i]); } } [TestMethod] public void ChunkList_Clear_1() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Clear(); Assert.AreEqual(0, list.Count); Assert.AreEqual(chunkSize, list.Capacity); } [TestMethod] public void ChunkList_Contains_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Contains(2)); list.Add(1); Assert.IsFalse(list.Contains(2)); list.Add(2); Assert.IsTrue(list.Contains(2)); list.Add(2); Assert.IsTrue(list.Contains(2)); } [TestMethod] public void ChunkList_Contains_2() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Contains(2)); for (int i = 0; i < 1025; i++) { list.Add(i); } Assert.IsTrue(list.Contains(2)); Assert.IsTrue(list.Contains(1023)); Assert.IsTrue(list.Contains(1024)); Assert.IsFalse(list.Contains(1025)); } [TestMethod] public void ChunkList_IsReadOnly_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.IsReadOnly); } [TestMethod] public void ChunkList_IndexOf_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsTrue(list.IndexOf(2) < 0); list.Add(1); Assert.IsTrue(list.IndexOf(2) < 0); list.Add(2); Assert.AreEqual(1, list.IndexOf(2)); list.Add(2); Assert.AreEqual(1, list.IndexOf(2)); } [TestMethod] public void ChunkList_IndexOf_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list.IndexOf(i)); } Assert.IsTrue(list.IndexOf(count + 1) < 0); } [TestMethod] public void ChunkList_Indexer_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Indexer_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list[i]); } } [TestMethod] public void ChunkList_Indexer_3() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); list[0] = 1; list[1] = 2; list[2] = 3; Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Indexer_4() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(0); } for (int i = 0; i < count; i++) { list[i] = i; } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list[i]); } } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_5() { ChunkList<int> list = new ChunkList<int>(); Assert.AreEqual(0, list[0]); } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_6() { ChunkList<int> list = new ChunkList<int>(); list[0] = 0; } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_7() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); Assert.AreEqual(0, list[1000]); } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_8() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); list[1000] = 0; } [TestMethod] public void ChunkList_GetEnumerator_1() { ChunkList<int> list = new ChunkList<int>(); IEnumerator<int> enumerator = list.GetEnumerator(); Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); IEnumerator<int> enumerator = list.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(3, enumerator.Current); Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_3() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } IEnumerator<int> enumerator = list.GetEnumerator(); for (int i = 0; i < count; i++) { Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(i, enumerator.Current); } Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_4() { IEnumerable list = new ChunkList<int>(); IEnumerator enumerator = list.GetEnumerator(); Assert.IsFalse(enumerator.MoveNext()); } [TestMethod] public void ChunkList_GetEnumerator_5() { IEnumerable list = new ChunkList<int> { 1, 2, 3 }; IEnumerator enumerator = list.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(3, enumerator.Current); Assert.IsFalse(enumerator.MoveNext()); } [TestMethod] public void ChunkList_RemoveAt_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); list.RemoveAt(1); Assert.AreEqual(2, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(3, list[1]); } [TestMethod] public void ChunkList_RemoveAt_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } list.RemoveAt(100); Assert.AreEqual(count-1, list.Count); for (int i = 0; i < 100; i++) { Assert.AreEqual(i, list[i]); } for (int i = 100; i < count - 1; i++) { Assert.AreEqual(i + 1, list[i]); } } [TestMethod] public void ChunkList_Remove_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Remove(2)); list.Add(1); list.Add(2); list.Add(3); Assert.IsTrue(list.Remove(2)); Assert.AreEqual(2, list.Count); Assert.AreEqual(3, list[1]); Assert.IsFalse(list.Remove(2)); } [TestMethod] public void ChunkList_Insert_1() { ChunkList<int> list = new ChunkList<int>(); list.Insert(0, 3); list.Insert(0, 2); list.Insert(0, 1); Assert.AreEqual(3, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Insert_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(5); list.Insert(1, 4); list.Insert(1, 3); list.Insert(1, 2); Assert.AreEqual(5, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); Assert.AreEqual(4, list[3]); Assert.AreEqual(5, list[4]); } [TestMethod] public void ChunkList_ToArray_1() { ChunkList<int> list = new ChunkList<int>(); int[] array = list.ToArray(); Assert.AreEqual(0, array.Length); list.Add(1); array = list.ToArray(); Assert.AreEqual(1, array.Length); Assert.AreEqual(1, array[0]); list.Add(2); array = list.ToArray(); Assert.AreEqual(2, array.Length); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); list.Add(3); array = list.ToArray(); Assert.AreEqual(3, array.Length); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); Assert.AreEqual(3, array[2]); } [TestMethod] public void ChunkList_ToArray_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } int[] array = list.ToArray(); Assert.AreEqual(count, array.Length); for (int i = 0; i < count; i++) { Assert.AreEqual(i, array[i]); } } } }